You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@knox.apache.org by mo...@apache.org on 2017/09/01 13:16:59 UTC

[01/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Repository: knox
Updated Branches:
  refs/heads/KNOX-998-Package_Restructuring 115913527 -> 2e6713b6c


http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server/src/main/java/org/apache/hadoop/gateway/deploy/DeploymentContextImpl.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/hadoop/gateway/deploy/DeploymentContextImpl.java b/gateway-server/src/main/java/org/apache/hadoop/gateway/deploy/DeploymentContextImpl.java
deleted file mode 100644
index 39a2a1b..0000000
--- a/gateway-server/src/main/java/org/apache/hadoop/gateway/deploy/DeploymentContextImpl.java
+++ /dev/null
@@ -1,140 +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.hadoop.gateway.deploy;
-
-import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.GatewayDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-import org.apache.hadoop.gateway.topology.Topology;
-import org.jboss.shrinkwrap.api.spec.WebArchive;
-import org.jboss.shrinkwrap.descriptor.api.webapp30.WebAppDescriptor;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class DeploymentContextImpl implements DeploymentContext {
-
-  private GatewayConfig gatewayConfig;
-  private Topology topology;
-  private GatewayDescriptor gatewayDescriptor;
-  private WebArchive webArchive;
-  private WebAppDescriptor webAppDescriptor;
-  Map<String,List<ProviderDeploymentContributor>> providers;
-  private Map<String,Object> descriptors;
-
-  public DeploymentContextImpl(
-      GatewayConfig gatewayConfig,
-      Topology topology,
-      GatewayDescriptor gatewayDescriptor,
-      WebArchive webArchive,
-      WebAppDescriptor webAppDescriptor,
-      Map<String,List<ProviderDeploymentContributor>> providers ) {
-    this.gatewayConfig = gatewayConfig;
-    this.topology = topology;
-    this.gatewayDescriptor = gatewayDescriptor;
-    this.webArchive = webArchive;
-    this.webAppDescriptor = webAppDescriptor;
-    this.providers = providers;
-    this.descriptors = new HashMap<>();
-  }
-
-//  @Override
-//  public ServiceDeploymentContributor getServiceContributor( String role, String name ) {
-//    ServiceDeploymentContributor contributor = null;
-//    if( name == null ) {
-//      List<ServiceDeploymentContributor> list = services.get( role );
-//      if( !list.isEmpty() ) {
-//        contributor = list.get( 0 );
-//      }
-//    } else {
-//      contributor = DeploymentFactory.getServiceContributor( role, name );
-//    }
-//    return contributor;
-//  }
-
-//  @Override
-//  public ResourceDescriptorFactory getResourceDescriptorFactory( Service service ) {
-//    return GatewayDescriptorFactory.getResourceDescriptorFactory( service );
-//  }
-//
-//  @Override
-//  public FilterDescriptorFactory getFilterDescriptorFactory( String filterRole ) {
-//    return GatewayDescriptorFactory.getFilterDescriptorFactory( filterRole );
-//  }
-
-  @Override
-  public GatewayConfig getGatewayConfig() {
-    return gatewayConfig;
-  }
-
-  @Override
-  public Topology getTopology() {
-    return topology;
-  }
-
-  @Override
-  public WebArchive getWebArchive() {
-    return webArchive;
-  }
-
-  @Override
-  public WebAppDescriptor getWebAppDescriptor() {
-    return webAppDescriptor;
-  }
-
-  @Override
-  public GatewayDescriptor getGatewayDescriptor() {
-    return gatewayDescriptor;
-  }
-
-  @Override
-  public void contributeFilter(
-      Service service,
-      ResourceDescriptor resource,
-      String role,
-      String name,
-      List<FilterParamDescriptor> params ) {
-    ProviderDeploymentContributor contributor = DeploymentFactory.getProviderContributor( providers, role, name );
-    Provider provider = getTopology().getProvider( role, name );
-    if( provider == null ) {
-      provider = new Provider();
-      provider.setRole( role );
-      provider.setName( name );
-      provider.setEnabled( true );
-    }
-    if( provider.isEnabled() ) {
-      contributor.contributeFilter( this, provider, service, resource, params );
-    }
-  }
-
-  @Override
-  public void addDescriptor( String name, Object descriptor ) {
-    descriptors.put( name, descriptor );
-  }
-
-  @Override
-  @SuppressWarnings("unchecked")
-  public <T> T getDescriptor( String name ) {
-    return (T)descriptors.get( name );
-  }
-
-}


[31/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryDeploymentContributorTest.java b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryDeploymentContributorTest.java
deleted file mode 100644
index f56c398..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryDeploymentContributorTest.java
+++ /dev/null
@@ -1,102 +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.hadoop.gateway.securequery;
-
-import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.ServiceLifecycleException;
-import org.apache.hadoop.gateway.services.security.AliasService;
-import org.apache.hadoop.gateway.services.security.CryptoService;
-import org.apache.hadoop.gateway.services.security.impl.DefaultCryptoService;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Topology;
-import org.easymock.EasyMock;
-import org.jboss.shrinkwrap.api.ShrinkWrap;
-import org.jboss.shrinkwrap.api.spec.WebArchive;
-import org.junit.Test;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-public class SecureQueryDeploymentContributorTest {
-
-  @Test
-  public void testDeployment() throws IOException {
-    WebArchive webArchive = ShrinkWrap.create( WebArchive.class, "test-acrhive" );
-
-//    UrlRewriteRulesDescriptorImpl rewriteRules = new UrlRewriteRulesDescriptorImpl();
-
-    Map<String,String> providerParams = new HashMap<>();
-//    providerParams.put( "test-host-external", "test-host-internal" );
-    Provider provider = new Provider();
-    provider.setEnabled( true );
-    provider.setName( "secure-query" );
-    provider.setParams(  providerParams );
-
-    Topology topology = new Topology();
-    topology.setName("Sample");
-    
-    DeploymentContext context = EasyMock.createNiceMock( DeploymentContext.class );
-//    EasyMock.expect( context.getDescriptor( "rewrite" ) ).andReturn( rewriteRules ).anyTimes();
-    EasyMock.expect( context.getWebArchive() ).andReturn( webArchive ).anyTimes();
-    EasyMock.expect( context.getTopology() ).andReturn( topology ).anyTimes();
-    EasyMock.replay( context );
-
-    AliasService as = EasyMock.createNiceMock( AliasService.class );
-    CryptoService cryptoService = new DefaultCryptoService();
-    ((DefaultCryptoService)cryptoService).setAliasService(as);
-
-    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService ).anyTimes();
-
-    UrlRewriteEnvironment encEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();    
-    
-    SecureQueryDeploymentContributor contributor = new SecureQueryDeploymentContributor();
-    contributor.setAliasService(as);
-
-    assertThat( contributor.getRole(), is( "secure-query" ) );
-    assertThat( contributor.getName(), is( "default" ) );
-
-    // Just make sure it doesn't blow up.
-    contributor.contributeFilter( null, null, null, null, null );
-
-    // Just make sure it doesn't blow up.
-    contributor.initializeContribution( context );
-
-    contributor.contributeProvider( context, provider );
-
-//    HostmapFunctionDescriptor funcDesc = rewriteRules.getFunction( "hostmap" );
-//    assertThat( funcDesc.config(), is( "/WEB-INF/hostmap.txt" ) );
-//
-//    Node node = webArchive.get( "/WEB-INF/hostmap.txt" );
-//    String asset = IOUtils.toString( node.getAsset().openStream() );
-//    assertThat( asset, containsString( "test-host-external=test-host-internal" ) );
-
-    // Just make sure it doesn't blow up.
-    contributor.finalizeContribution( context );
-
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeDescriptorTest.java b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeDescriptorTest.java
deleted file mode 100644
index bdf1ad0..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeDescriptorTest.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.hadoop.gateway.securequery;
-
-import org.junit.Test;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-public class SecureQueryEncodeDescriptorTest {
-
-  @Test
-  public void testGetAndSet() {
-    SecureQueryEncodeDescriptor descriptor = new SecureQueryEncodeDescriptor();
-    assertThat( descriptor.type(), is( "encode-query" ) );
-    assertThat( descriptor.getParam(), nullValue() );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeProcessorTest.java b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeProcessorTest.java
deleted file mode 100644
index 0b72e91..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeProcessorTest.java
+++ /dev/null
@@ -1,75 +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.hadoop.gateway.securequery;
-
-import java.util.Arrays;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.security.AliasService;
-import org.apache.hadoop.gateway.services.security.CryptoService;
-import org.apache.hadoop.gateway.services.security.impl.DefaultCryptoService;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-import org.easymock.Capture;
-import org.easymock.EasyMock;
-import org.junit.Test;
-import sun.misc.BASE64Encoder;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-public class SecureQueryEncodeProcessorTest {
-
-  @Test
-  public void testSimpleQueryEncoding() throws Exception {
-    AliasService as = EasyMock.createNiceMock( AliasService.class );
-    String secret = "sdkjfhsdkjfhsdfs";
-    EasyMock.expect( as.getPasswordFromAliasForCluster("test-cluster-name", "encryptQueryString")).andReturn( secret.toCharArray() ).anyTimes();
-    CryptoService cryptoService = new DefaultCryptoService();
-    ((DefaultCryptoService)cryptoService).setAliasService(as);
-    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService );
-
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( environment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();    
-    EasyMock.expect( environment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( Arrays.asList( "test-cluster-name" ) ).anyTimes();
-
-    Template inTemplate = Parser.parseLiteral( "http://host:0/root/path?query" );
-    UrlRewriteContext context = EasyMock.createNiceMock( UrlRewriteContext.class );
-    EasyMock.expect( context.getCurrentUrl() ).andReturn( inTemplate );
-    Capture<Template> outTemplate = new Capture<Template>();
-    context.setCurrentUrl( EasyMock.capture( outTemplate ) );
-
-    EasyMock.replay( environment, context );
-
-    SecureQueryEncodeDescriptor descriptor = new SecureQueryEncodeDescriptor();
-    SecureQueryEncodeProcessor processor = new SecureQueryEncodeProcessor();
-    processor.initialize( environment, descriptor );
-    processor.process( context );
-
-    BASE64Encoder encoder = new BASE64Encoder();
-    String encQuery = encoder.encode( "query".getBytes("utf-8" ) );
-    encQuery = encQuery.replaceAll( "\\=", "" );
-    String outExpect = "http://host:0/root/path?_=" + encQuery;
-    String outActual = outTemplate.getValue().toString();
-    assertThat( outActual, is( outExpect ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryEncryptDecryptProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryEncryptDecryptProcessorTest.java b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryEncryptDecryptProcessorTest.java
deleted file mode 100644
index 453aeb9..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryEncryptDecryptProcessorTest.java
+++ /dev/null
@@ -1,179 +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.hadoop.gateway.securequery;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.security.AliasService;
-import org.apache.hadoop.gateway.services.security.CryptoService;
-import org.apache.hadoop.gateway.services.security.impl.DefaultCryptoService;
-import org.apache.hadoop.gateway.util.urltemplate.Params;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Query;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-import org.easymock.Capture;
-import org.easymock.EasyMock;
-import org.junit.Test;
-import org.junit.Assert;
-
-import java.util.Arrays;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.greaterThan;
-import static org.hamcrest.Matchers.nullValue;
-
-public class SecureQueryEncryptDecryptProcessorTest {
-
-  @Test
-  public void testEncryptDecrypt() throws Exception {
-    Query query;
-    Template origTemplate = Parser.parseLiteral( "http://host:0/path/file?query-param-name=query-param-value" );
-
-    // Test encryption.  Results are left in encTemplate
-
-    AliasService as = EasyMock.createNiceMock( AliasService.class );
-    String secret = "sdkjfhsdkjfhsdfs";
-    EasyMock.expect( as.getPasswordFromAliasForCluster("test-cluster-name", "encryptQueryString")).andReturn( secret.toCharArray() ).anyTimes();
-    CryptoService cryptoService = new DefaultCryptoService();
-    ((DefaultCryptoService)cryptoService).setAliasService(as);
-    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService );
-
-    UrlRewriteEnvironment encEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();    
-    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster-name" ).anyTimes();
-    UrlRewriteContext encContext = EasyMock.createNiceMock( UrlRewriteContext.class );
-    EasyMock.expect( encContext.getCurrentUrl() ).andReturn( origTemplate );
-    Capture<Template> encTemplate = new Capture<Template>();
-    encContext.setCurrentUrl( EasyMock.capture( encTemplate ) );
-    EasyMock.replay( gatewayServices, as, encEnvironment, encContext );
-
-    SecureQueryEncryptDescriptor descriptor = new SecureQueryEncryptDescriptor();
-    SecureQueryEncryptProcessor processor = new SecureQueryEncryptProcessor();
-    processor.initialize( encEnvironment, descriptor );
-    processor.process( encContext );
-
-    assertThat( encTemplate, notNullValue() );
-    query = encTemplate.getValue().getQuery().get( "_" );
-    assertThat( query.getFirstValue().getPattern().length(), greaterThan( 1 ) );
-    query = encTemplate.getValue().getQuery().get( "query-param-name" );
-    assertThat( query, nullValue() );
-
-    // Test decryption.  Results are left in decTemplate.
-
-    gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService );
-    as = EasyMock.createNiceMock( AliasService.class );
-    EasyMock.expect( as.getPasswordFromAliasForCluster("test-cluster-name", "encryptQueryString")).andReturn( secret.toCharArray() ).anyTimes();
-
-    UrlRewriteEnvironment decEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();    
-    EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster-name" ).anyTimes();
-    Params decParams = EasyMock.createNiceMock( Params.class );
-    EasyMock.expect( decParams.resolve( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( Arrays.asList("test-cluster-name") ).anyTimes();
-    UrlRewriteContext decContext = EasyMock.createNiceMock( UrlRewriteContext.class );
-    EasyMock.expect( decContext.getCurrentUrl() ).andReturn( encTemplate.getValue() );
-    EasyMock.expect( decContext.getParameters() ).andReturn( decParams );
-    Capture<Template> decTemplate = new Capture<Template>();
-    decContext.setCurrentUrl( EasyMock.capture( decTemplate ) );
-    EasyMock.replay( gatewayServices, as, decEnvironment, decParams, decContext );
-
-    SecureQueryDecryptDescriptor descriptor1 = new SecureQueryDecryptDescriptor();
-    SecureQueryDecryptProcessor decProcessor = new SecureQueryDecryptProcessor();
-    decProcessor.initialize( decEnvironment, descriptor1 );
-    decProcessor.process( decContext );
-
-    assertThat( decTemplate, notNullValue() );
-    assertThat( decTemplate.getValue(), notNullValue() );
-    query = decTemplate.getValue().getQuery().get( "query-param-name" );
-    assertThat( query.getFirstValue().getPattern(), is( "query-param-value" ) );
-    query = decTemplate.getValue().getQuery().get( "_" );
-    assertThat( query, nullValue() );
-  }
-
-  @Test
-  public void testEncryptBadDecrypt() throws Exception {
-    Query query;
-    Template origTemplate = Parser.parseLiteral( "http://host:0/path/file?query-param-name=query-param-value" );
-
-    // Test encryption.  Results are left in encTemplate
-
-    AliasService as = EasyMock.createNiceMock( AliasService.class );
-    String secret = "sdkjfhsdkjfhsdfs";
-    EasyMock.expect( as.getPasswordFromAliasForCluster("test-cluster-name", "encryptQueryString")).andReturn( secret.toCharArray() ).anyTimes();
-    CryptoService cryptoService = new DefaultCryptoService();
-    ((DefaultCryptoService)cryptoService).setAliasService(as);
-    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService );
-
-    UrlRewriteEnvironment encEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();
-    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster-name" ).anyTimes();
-    UrlRewriteContext encContext = EasyMock.createNiceMock( UrlRewriteContext.class );
-    EasyMock.expect( encContext.getCurrentUrl() ).andReturn( origTemplate );
-    Capture<Template> encTemplate = new Capture<Template>();
-    encContext.setCurrentUrl( EasyMock.capture( encTemplate ) );
-    EasyMock.replay( gatewayServices, as, encEnvironment, encContext );
-
-    SecureQueryEncryptDescriptor descriptor = new SecureQueryEncryptDescriptor();
-    SecureQueryEncryptProcessor processor = new SecureQueryEncryptProcessor();
-    processor.initialize( encEnvironment, descriptor );
-    processor.process( encContext );
-
-    assertThat( encTemplate, notNullValue() );
-    query = encTemplate.getValue().getQuery().get( "_" );
-    assertThat( query.getFirstValue().getPattern().length(), greaterThan( 1 ) );
-    query = encTemplate.getValue().getQuery().get( "query-param-name" );
-    assertThat( query, nullValue() );
-
-    // Test decryption with decode returning null
-
-    gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService );
-    as = EasyMock.createNiceMock( AliasService.class );
-    EasyMock.expect( as.getPasswordFromAliasForCluster("test-cluster-name", "encryptQueryString")).andReturn( secret.toCharArray() ).anyTimes();
-
-    UrlRewriteEnvironment decEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();
-    EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster-name" ).anyTimes();
-    Params decParams = EasyMock.createNiceMock( Params.class );
-    EasyMock.expect( decParams.resolve( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( Arrays.asList("test-cluster-name") ).anyTimes();
-    UrlRewriteContext decContext = EasyMock.createNiceMock( UrlRewriteContext.class );
-    EasyMock.expect( decContext.getCurrentUrl() ).andReturn( encTemplate.getValue() );
-    EasyMock.expect( decContext.getParameters() ).andReturn( decParams );
-    Capture<Template> decTemplate = new Capture<Template>();
-    decContext.setCurrentUrl( EasyMock.capture( decTemplate ) );
-    SecureQueryDecryptDescriptor descriptor1 = new SecureQueryDecryptDescriptor();
-    SecureQueryDecryptProcessor decProcessor =
-       EasyMock.createMockBuilder(
-          SecureQueryDecryptProcessor.class ).addMockedMethod( SecureQueryDecryptProcessor.class.getDeclaredMethod("decode", String.class )).createMock();
-    EasyMock.expect( decProcessor.decode(EasyMock.anyObject(String.class))).andReturn( null );
-    EasyMock.replay( gatewayServices, as, decEnvironment, decParams, decContext, decProcessor );
-
-    decProcessor.initialize( decEnvironment, descriptor1 );
-    UrlRewriteStepStatus status = decProcessor.process( decContext );
-
-    Assert.assertTrue((status == UrlRewriteStepStatus.FAILURE));
-  }
-
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryDecodeDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryDecodeDescriptorTest.java b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryDecodeDescriptorTest.java
new file mode 100644
index 0000000..7747698
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryDecodeDescriptorTest.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.knox.gateway.securequery;
+
+import org.junit.Test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public class SecureQueryDecodeDescriptorTest {
+
+  @Test
+  public void testGetAndSet() {
+    SecureQueryDecodeDescriptor descriptor = new SecureQueryDecodeDescriptor();
+    assertThat( descriptor.type(), is( "decode-query" ) );
+    assertThat( descriptor.getParam(), nullValue() );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryDecodeProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryDecodeProcessorTest.java b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryDecodeProcessorTest.java
new file mode 100644
index 0000000..4ef447f
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryDecodeProcessorTest.java
@@ -0,0 +1,125 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.securequery;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Template;
+import org.easymock.Capture;
+import org.easymock.EasyMock;
+import org.junit.Test;
+import sun.misc.BASE64Encoder;
+
+import java.io.IOException;
+import java.net.URL;
+import java.util.List;
+
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public class SecureQueryDecodeProcessorTest {
+
+  @Test
+  public void testSimpleQueryDecode() throws Exception {
+    UrlRewriteEnvironment environment = new UrlRewriteEnvironment() {
+      @Override
+      public URL getResource( String name ) throws IOException {
+        return null;
+      }
+
+      @Override
+      public <T> T getAttribute( String name ) {
+        return null;
+      }
+
+      @Override
+      public List<String> resolve( String name ) {
+        return null;
+      }
+    };
+
+    BASE64Encoder encoder = new BASE64Encoder();
+    String encQuery = encoder.encode( "test-query".getBytes("utf-8" ) );
+    encQuery = encQuery.replaceAll( "\\=", "" );
+    String inString = "http://host:0/root/path?_=" + encQuery;
+    Template inTemplate = Parser.parseLiteral( inString );
+
+    UrlRewriteContext context = EasyMock.createNiceMock( UrlRewriteContext.class );
+    EasyMock.expect( context.getCurrentUrl() ).andReturn( inTemplate );
+    Capture<Template> outTemplate = new Capture<Template>();
+    context.setCurrentUrl( EasyMock.capture( outTemplate ) );
+    EasyMock.replay( context );
+
+    SecureQueryDecodeDescriptor descriptor = new SecureQueryDecodeDescriptor();
+    SecureQueryDecodeProcessor processor = new SecureQueryDecodeProcessor();
+    processor.initialize( environment, descriptor );
+    processor.process( context );
+
+    String outActual = outTemplate.getValue().toString();
+    assertThat( outActual, is( "http://host:0/root/path?test-query" ) );
+  }
+
+  @Test
+  public void testDecodeQueryWithNonEncodedParams() throws Exception {
+    UrlRewriteEnvironment environment = new UrlRewriteEnvironment() {
+      @Override
+      public URL getResource( String name ) throws IOException {
+        return null;
+      }
+
+      @Override
+      public <T> T getAttribute( String name ) {
+        return null;
+      }
+
+      @Override
+      public List<String> resolve( String name ) {
+        return null;
+      }
+    };
+
+    BASE64Encoder encoder = new BASE64Encoder();
+    String inQuery = "test-query=test-value";
+    String encQuery = encoder.encode( inQuery.getBytes( "utf-8" ) );
+    encQuery = encQuery.replaceAll( "\\=", "" );
+    String inString = "http://host:0/root/path?_=" + encQuery + "&clear-param=clear-value";
+    Template inTemplate = Parser.parseLiteral( inString );
+
+    UrlRewriteContext context = EasyMock.createNiceMock( UrlRewriteContext.class );
+    EasyMock.expect( context.getCurrentUrl() ).andReturn( inTemplate );
+    Capture<Template> outTemplate = new Capture<Template>();
+    context.setCurrentUrl( EasyMock.capture( outTemplate ) );
+    EasyMock.replay( context );
+
+    SecureQueryDecodeDescriptor descriptor = new SecureQueryDecodeDescriptor();
+    SecureQueryDecodeProcessor processor = new SecureQueryDecodeProcessor();
+    processor.initialize( environment, descriptor );
+    processor.process( context );
+
+    String outActual = outTemplate.getValue().toString();
+    assertThat( outActual, containsString( "http://host:0/root/path?" ) );
+    assertThat( outActual, containsString( "test-query=test-value" ) );
+    assertThat( outActual, containsString( "clear-param=clear-value" ) );
+    assertThat( outActual, not( containsString( encQuery ) ) );
+  }
+
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryDeploymentContributorTest.java b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryDeploymentContributorTest.java
new file mode 100644
index 0000000..4977ebe
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryDeploymentContributorTest.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.knox.gateway.securequery;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.AliasService;
+import org.apache.knox.gateway.services.security.CryptoService;
+import org.apache.knox.gateway.services.security.impl.DefaultCryptoService;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Topology;
+import org.easymock.EasyMock;
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.spec.WebArchive;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public class SecureQueryDeploymentContributorTest {
+
+  @Test
+  public void testDeployment() throws IOException {
+    WebArchive webArchive = ShrinkWrap.create( WebArchive.class, "test-acrhive" );
+
+//    UrlRewriteRulesDescriptorImpl rewriteRules = new UrlRewriteRulesDescriptorImpl();
+
+    Map<String,String> providerParams = new HashMap<>();
+//    providerParams.put( "test-host-external", "test-host-internal" );
+    Provider provider = new Provider();
+    provider.setEnabled( true );
+    provider.setName( "secure-query" );
+    provider.setParams(  providerParams );
+
+    Topology topology = new Topology();
+    topology.setName("Sample");
+    
+    DeploymentContext context = EasyMock.createNiceMock( DeploymentContext.class );
+//    EasyMock.expect( context.getDescriptor( "rewrite" ) ).andReturn( rewriteRules ).anyTimes();
+    EasyMock.expect( context.getWebArchive() ).andReturn( webArchive ).anyTimes();
+    EasyMock.expect( context.getTopology() ).andReturn( topology ).anyTimes();
+    EasyMock.replay( context );
+
+    AliasService as = EasyMock.createNiceMock( AliasService.class );
+    CryptoService cryptoService = new DefaultCryptoService();
+    ((DefaultCryptoService)cryptoService).setAliasService(as);
+
+    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService ).anyTimes();
+
+    UrlRewriteEnvironment encEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();    
+    
+    SecureQueryDeploymentContributor contributor = new SecureQueryDeploymentContributor();
+    contributor.setAliasService(as);
+
+    assertThat( contributor.getRole(), is( "secure-query" ) );
+    assertThat( contributor.getName(), is( "default" ) );
+
+    // Just make sure it doesn't blow up.
+    contributor.contributeFilter( null, null, null, null, null );
+
+    // Just make sure it doesn't blow up.
+    contributor.initializeContribution( context );
+
+    contributor.contributeProvider( context, provider );
+
+//    HostmapFunctionDescriptor funcDesc = rewriteRules.getFunction( "hostmap" );
+//    assertThat( funcDesc.config(), is( "/WEB-INF/hostmap.txt" ) );
+//
+//    Node node = webArchive.get( "/WEB-INF/hostmap.txt" );
+//    String asset = IOUtils.toString( node.getAsset().openStream() );
+//    assertThat( asset, containsString( "test-host-external=test-host-internal" ) );
+
+    // Just make sure it doesn't blow up.
+    contributor.finalizeContribution( context );
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryEncodeDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryEncodeDescriptorTest.java b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryEncodeDescriptorTest.java
new file mode 100644
index 0000000..f6dcf03
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryEncodeDescriptorTest.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.knox.gateway.securequery;
+
+import org.junit.Test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public class SecureQueryEncodeDescriptorTest {
+
+  @Test
+  public void testGetAndSet() {
+    SecureQueryEncodeDescriptor descriptor = new SecureQueryEncodeDescriptor();
+    assertThat( descriptor.type(), is( "encode-query" ) );
+    assertThat( descriptor.getParam(), nullValue() );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryEncodeProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryEncodeProcessorTest.java b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryEncodeProcessorTest.java
new file mode 100644
index 0000000..24157a1
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryEncodeProcessorTest.java
@@ -0,0 +1,75 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.securequery;
+
+import java.util.Arrays;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.AliasService;
+import org.apache.knox.gateway.services.security.CryptoService;
+import org.apache.knox.gateway.services.security.impl.DefaultCryptoService;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Template;
+import org.easymock.Capture;
+import org.easymock.EasyMock;
+import org.junit.Test;
+import sun.misc.BASE64Encoder;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public class SecureQueryEncodeProcessorTest {
+
+  @Test
+  public void testSimpleQueryEncoding() throws Exception {
+    AliasService as = EasyMock.createNiceMock( AliasService.class );
+    String secret = "sdkjfhsdkjfhsdfs";
+    EasyMock.expect( as.getPasswordFromAliasForCluster("test-cluster-name", "encryptQueryString")).andReturn( secret.toCharArray() ).anyTimes();
+    CryptoService cryptoService = new DefaultCryptoService();
+    ((DefaultCryptoService)cryptoService).setAliasService(as);
+    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService );
+
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( environment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();    
+    EasyMock.expect( environment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( Arrays.asList( "test-cluster-name" ) ).anyTimes();
+
+    Template inTemplate = Parser.parseLiteral( "http://host:0/root/path?query" );
+    UrlRewriteContext context = EasyMock.createNiceMock( UrlRewriteContext.class );
+    EasyMock.expect( context.getCurrentUrl() ).andReturn( inTemplate );
+    Capture<Template> outTemplate = new Capture<Template>();
+    context.setCurrentUrl( EasyMock.capture( outTemplate ) );
+
+    EasyMock.replay( environment, context );
+
+    SecureQueryEncodeDescriptor descriptor = new SecureQueryEncodeDescriptor();
+    SecureQueryEncodeProcessor processor = new SecureQueryEncodeProcessor();
+    processor.initialize( environment, descriptor );
+    processor.process( context );
+
+    BASE64Encoder encoder = new BASE64Encoder();
+    String encQuery = encoder.encode( "query".getBytes("utf-8" ) );
+    encQuery = encQuery.replaceAll( "\\=", "" );
+    String outExpect = "http://host:0/root/path?_=" + encQuery;
+    String outActual = outTemplate.getValue().toString();
+    assertThat( outActual, is( outExpect ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryEncryptDecryptProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryEncryptDecryptProcessorTest.java b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryEncryptDecryptProcessorTest.java
new file mode 100644
index 0000000..c0fba80
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryEncryptDecryptProcessorTest.java
@@ -0,0 +1,179 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.securequery;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.AliasService;
+import org.apache.knox.gateway.services.security.CryptoService;
+import org.apache.knox.gateway.services.security.impl.DefaultCryptoService;
+import org.apache.knox.gateway.util.urltemplate.Params;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Query;
+import org.apache.knox.gateway.util.urltemplate.Template;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+import org.easymock.Capture;
+import org.easymock.EasyMock;
+import org.junit.Test;
+import org.junit.Assert;
+
+import java.util.Arrays;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.hamcrest.Matchers.nullValue;
+
+public class SecureQueryEncryptDecryptProcessorTest {
+
+  @Test
+  public void testEncryptDecrypt() throws Exception {
+    Query query;
+    Template origTemplate = Parser.parseLiteral( "http://host:0/path/file?query-param-name=query-param-value" );
+
+    // Test encryption.  Results are left in encTemplate
+
+    AliasService as = EasyMock.createNiceMock( AliasService.class );
+    String secret = "sdkjfhsdkjfhsdfs";
+    EasyMock.expect( as.getPasswordFromAliasForCluster("test-cluster-name", "encryptQueryString")).andReturn( secret.toCharArray() ).anyTimes();
+    CryptoService cryptoService = new DefaultCryptoService();
+    ((DefaultCryptoService)cryptoService).setAliasService(as);
+    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService );
+
+    UrlRewriteEnvironment encEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();    
+    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster-name" ).anyTimes();
+    UrlRewriteContext encContext = EasyMock.createNiceMock( UrlRewriteContext.class );
+    EasyMock.expect( encContext.getCurrentUrl() ).andReturn( origTemplate );
+    Capture<Template> encTemplate = new Capture<Template>();
+    encContext.setCurrentUrl( EasyMock.capture( encTemplate ) );
+    EasyMock.replay( gatewayServices, as, encEnvironment, encContext );
+
+    SecureQueryEncryptDescriptor descriptor = new SecureQueryEncryptDescriptor();
+    SecureQueryEncryptProcessor processor = new SecureQueryEncryptProcessor();
+    processor.initialize( encEnvironment, descriptor );
+    processor.process( encContext );
+
+    assertThat( encTemplate, notNullValue() );
+    query = encTemplate.getValue().getQuery().get( "_" );
+    assertThat( query.getFirstValue().getPattern().length(), greaterThan( 1 ) );
+    query = encTemplate.getValue().getQuery().get( "query-param-name" );
+    assertThat( query, nullValue() );
+
+    // Test decryption.  Results are left in decTemplate.
+
+    gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService );
+    as = EasyMock.createNiceMock( AliasService.class );
+    EasyMock.expect( as.getPasswordFromAliasForCluster("test-cluster-name", "encryptQueryString")).andReturn( secret.toCharArray() ).anyTimes();
+
+    UrlRewriteEnvironment decEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();    
+    EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster-name" ).anyTimes();
+    Params decParams = EasyMock.createNiceMock( Params.class );
+    EasyMock.expect( decParams.resolve( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( Arrays.asList("test-cluster-name") ).anyTimes();
+    UrlRewriteContext decContext = EasyMock.createNiceMock( UrlRewriteContext.class );
+    EasyMock.expect( decContext.getCurrentUrl() ).andReturn( encTemplate.getValue() );
+    EasyMock.expect( decContext.getParameters() ).andReturn( decParams );
+    Capture<Template> decTemplate = new Capture<Template>();
+    decContext.setCurrentUrl( EasyMock.capture( decTemplate ) );
+    EasyMock.replay( gatewayServices, as, decEnvironment, decParams, decContext );
+
+    SecureQueryDecryptDescriptor descriptor1 = new SecureQueryDecryptDescriptor();
+    SecureQueryDecryptProcessor decProcessor = new SecureQueryDecryptProcessor();
+    decProcessor.initialize( decEnvironment, descriptor1 );
+    decProcessor.process( decContext );
+
+    assertThat( decTemplate, notNullValue() );
+    assertThat( decTemplate.getValue(), notNullValue() );
+    query = decTemplate.getValue().getQuery().get( "query-param-name" );
+    assertThat( query.getFirstValue().getPattern(), is( "query-param-value" ) );
+    query = decTemplate.getValue().getQuery().get( "_" );
+    assertThat( query, nullValue() );
+  }
+
+  @Test
+  public void testEncryptBadDecrypt() throws Exception {
+    Query query;
+    Template origTemplate = Parser.parseLiteral( "http://host:0/path/file?query-param-name=query-param-value" );
+
+    // Test encryption.  Results are left in encTemplate
+
+    AliasService as = EasyMock.createNiceMock( AliasService.class );
+    String secret = "sdkjfhsdkjfhsdfs";
+    EasyMock.expect( as.getPasswordFromAliasForCluster("test-cluster-name", "encryptQueryString")).andReturn( secret.toCharArray() ).anyTimes();
+    CryptoService cryptoService = new DefaultCryptoService();
+    ((DefaultCryptoService)cryptoService).setAliasService(as);
+    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService );
+
+    UrlRewriteEnvironment encEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();
+    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster-name" ).anyTimes();
+    UrlRewriteContext encContext = EasyMock.createNiceMock( UrlRewriteContext.class );
+    EasyMock.expect( encContext.getCurrentUrl() ).andReturn( origTemplate );
+    Capture<Template> encTemplate = new Capture<Template>();
+    encContext.setCurrentUrl( EasyMock.capture( encTemplate ) );
+    EasyMock.replay( gatewayServices, as, encEnvironment, encContext );
+
+    SecureQueryEncryptDescriptor descriptor = new SecureQueryEncryptDescriptor();
+    SecureQueryEncryptProcessor processor = new SecureQueryEncryptProcessor();
+    processor.initialize( encEnvironment, descriptor );
+    processor.process( encContext );
+
+    assertThat( encTemplate, notNullValue() );
+    query = encTemplate.getValue().getQuery().get( "_" );
+    assertThat( query.getFirstValue().getPattern().length(), greaterThan( 1 ) );
+    query = encTemplate.getValue().getQuery().get( "query-param-name" );
+    assertThat( query, nullValue() );
+
+    // Test decryption with decode returning null
+
+    gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService );
+    as = EasyMock.createNiceMock( AliasService.class );
+    EasyMock.expect( as.getPasswordFromAliasForCluster("test-cluster-name", "encryptQueryString")).andReturn( secret.toCharArray() ).anyTimes();
+
+    UrlRewriteEnvironment decEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();
+    EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster-name" ).anyTimes();
+    Params decParams = EasyMock.createNiceMock( Params.class );
+    EasyMock.expect( decParams.resolve( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( Arrays.asList("test-cluster-name") ).anyTimes();
+    UrlRewriteContext decContext = EasyMock.createNiceMock( UrlRewriteContext.class );
+    EasyMock.expect( decContext.getCurrentUrl() ).andReturn( encTemplate.getValue() );
+    EasyMock.expect( decContext.getParameters() ).andReturn( decParams );
+    Capture<Template> decTemplate = new Capture<Template>();
+    decContext.setCurrentUrl( EasyMock.capture( decTemplate ) );
+    SecureQueryDecryptDescriptor descriptor1 = new SecureQueryDecryptDescriptor();
+    SecureQueryDecryptProcessor decProcessor =
+       EasyMock.createMockBuilder(
+          SecureQueryDecryptProcessor.class ).addMockedMethod( SecureQueryDecryptProcessor.class.getDeclaredMethod("decode", String.class )).createMock();
+    EasyMock.expect( decProcessor.decode(EasyMock.anyObject(String.class))).andReturn( null );
+    EasyMock.replay( gatewayServices, as, decEnvironment, decParams, decContext, decProcessor );
+
+    decProcessor.initialize( decEnvironment, descriptor1 );
+    UrlRewriteStepStatus status = decProcessor.process( decContext );
+
+    Assert.assertTrue((status == UrlRewriteStepStatus.FAILURE));
+  }
+
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/CookieScopeServletFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/CookieScopeServletFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/CookieScopeServletFilter.java
deleted file mode 100644
index 8c9eed0..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/CookieScopeServletFilter.java
+++ /dev/null
@@ -1,48 +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.hadoop.gateway.filter.rewrite.api;
-
-import java.io.IOException;
-
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.filter.rewrite.impl.CookieScopeResponseWrapper;
-
-
-public class CookieScopeServletFilter extends AbstractGatewayFilter {
-
-  private String gatewayPath;
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-    super.init( filterConfig );
-    gatewayPath = filterConfig.getInitParameter("gateway.path");
-  }
-
-  @Override
-  protected void doFilter( HttpServletRequest request, HttpServletResponse response, FilterChain chain )
-      throws IOException, ServletException {
-    chain.doFilter( request, new CookieScopeResponseWrapper(response, gatewayPath));
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/FrontendFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/FrontendFunctionDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/FrontendFunctionDescriptor.java
deleted file mode 100644
index 978ff73..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/FrontendFunctionDescriptor.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.filter.rewrite.api;
-
-public class FrontendFunctionDescriptor implements UrlRewriteFunctionDescriptor<FrontendFunctionDescriptor> {
-
-  public static final String FUNCTION_NAME = "frontend";
-
-  public static final String FRONTEND_URI_ATTRIBUTE = "org.apache.knox.gateway.frontend.uri";
-
-  @Override
-  public String name() {
-    return FUNCTION_NAME;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteEnvironment.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteEnvironment.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteEnvironment.java
deleted file mode 100644
index 228038d..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteEnvironment.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.filter.rewrite.api;
-
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-
-import java.io.IOException;
-import java.net.URL;
-
-public interface UrlRewriteEnvironment extends Resolver {
-
-  URL getResource( String name ) throws IOException;
-
-  <T> T getAttribute( String name );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterApplyDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterApplyDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterApplyDescriptor.java
deleted file mode 100644
index c6f66d8..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterApplyDescriptor.java
+++ /dev/null
@@ -1,27 +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.hadoop.gateway.filter.rewrite.api;
-
-public interface UrlRewriteFilterApplyDescriptor
-    extends UrlRewriteFilterPathDescriptor<UrlRewriteFilterApplyDescriptor> {
-
-  String rule();
-
-  UrlRewriteFilterApplyDescriptor rule( String rule );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterBufferDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterBufferDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterBufferDescriptor.java
deleted file mode 100644
index 1f12f81..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterBufferDescriptor.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.hadoop.gateway.filter.rewrite.api;
-
-public interface UrlRewriteFilterBufferDescriptor
-    extends UrlRewriteFilterPathDescriptor, UrlRewriteFilterGroupDescriptor {
-
-  public UrlRewriteFilterDetectDescriptor addDetect( String path, String value );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterContentDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterContentDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterContentDescriptor.java
deleted file mode 100644
index 73ea970..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterContentDescriptor.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.hadoop.gateway.filter.rewrite.api;
-
-public interface UrlRewriteFilterContentDescriptor extends UrlRewriteFilterGroupDescriptor {
-
-  String type();
-
-  String asType();
-
-  UrlRewriteFilterContentDescriptor type( String type );
-
-  UrlRewriteFilterContentDescriptor asType( String type );
-
-  UrlRewriteFilterBufferDescriptor addBuffer( String path );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterDescriptor.java
deleted file mode 100644
index 49369fd..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterDescriptor.java
+++ /dev/null
@@ -1,37 +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.hadoop.gateway.filter.rewrite.api;
-
-import javax.activation.MimeType;
-import java.util.List;
-
-public interface UrlRewriteFilterDescriptor {
-
-  String name();
-
-  UrlRewriteFilterDescriptor name( String name );
-
-  List<UrlRewriteFilterContentDescriptor> getContents();
-
-  UrlRewriteFilterContentDescriptor getContent( String type );
-
-  UrlRewriteFilterContentDescriptor getContent( MimeType type );
-
-  UrlRewriteFilterContentDescriptor addContent( String type );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterDetectDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterDetectDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterDetectDescriptor.java
deleted file mode 100644
index 9fe8eab..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterDetectDescriptor.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.hadoop.gateway.filter.rewrite.api;
-
-public interface UrlRewriteFilterDetectDescriptor
-    extends UrlRewriteFilterPathDescriptor, UrlRewriteFilterGroupDescriptor {
-
-  String value();
-
-  UrlRewriteFilterDetectDescriptor value( String value );
-
-  <C> C compiledValue();
-
-  UrlRewriteFilterDetectDescriptor compiledValue( String compiledValue );
-
-  <C> C compiledValue( Compiler<C> compiler );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterGroupDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterGroupDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterGroupDescriptor.java
deleted file mode 100644
index de0349f..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterGroupDescriptor.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.hadoop.gateway.filter.rewrite.api;
-
-import java.util.List;
-
-public interface UrlRewriteFilterGroupDescriptor extends UrlRewriteFilterPathDescriptor {
-
-  public List<UrlRewriteFilterPathDescriptor> getSelectors();
-
-  public void addSelector( UrlRewriteFilterPathDescriptor selector );
-
-  UrlRewriteFilterApplyDescriptor addApply( String path, String rule );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterPathDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterPathDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterPathDescriptor.java
deleted file mode 100644
index 9f4c864..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterPathDescriptor.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.hadoop.gateway.filter.rewrite.api;
-
-public interface UrlRewriteFilterPathDescriptor<T> {
-
-  String path();
-
-  T path( String path );
-
-  <C> C compiledPath();
-
-  T compiledPath( Object compilePath );
-
-  <C> C compiledPath( Compiler<C> compiler );
-
-  interface Compiler<C> {
-    // The returned compiled version of the expression must be thread safe.
-    // The compiled param will be the result of the last successful call to this method for this instance of
-    // the descriptor node.
-    C compile( String expression, C compiled );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterScopeDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterScopeDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterScopeDescriptor.java
deleted file mode 100644
index 62acc97..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFilterScopeDescriptor.java
+++ /dev/null
@@ -1,22 +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.hadoop.gateway.filter.rewrite.api;
-
-public interface UrlRewriteFilterScopeDescriptor
-    extends UrlRewriteFilterPathDescriptor, UrlRewriteFilterGroupDescriptor {
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFlowDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFlowDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFlowDescriptor.java
deleted file mode 100644
index aab4f15..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFlowDescriptor.java
+++ /dev/null
@@ -1,42 +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.hadoop.gateway.filter.rewrite.api;
-
-import java.util.List;
-
-public interface UrlRewriteFlowDescriptor<T> extends UrlRewriteStepDescriptor<T> {
-
-  UrlRewriteStepFlow flow();
-
-  <F extends UrlRewriteFlowDescriptor<?>> F flow( String flow );
-
-  <F extends UrlRewriteFlowDescriptor<?>> F flow( UrlRewriteStepFlow flow );
-
-  List<UrlRewriteStepDescriptor> steps();
-
-//  UrlRewriteMatchDescriptor addMatch();
-//
-//  UrlRewriteCheckDescriptor addCheck();
-//
-//  UrlRewriteActionDescriptor addAction();
-//
-//  UrlRewriteControlDescriptor addControl();
-
-  <T extends UrlRewriteStepDescriptor<?>> T addStep( String type );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptor.java
deleted file mode 100644
index bc491dd..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptor.java
+++ /dev/null
@@ -1,24 +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.hadoop.gateway.filter.rewrite.api;
-
-public interface UrlRewriteFunctionDescriptor<T> {
-
-  String name();
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptorFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptorFactory.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptorFactory.java
deleted file mode 100644
index 5d72695..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptorFactory.java
+++ /dev/null
@@ -1,61 +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.hadoop.gateway.filter.rewrite.api;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.ServiceLoader;
-import java.util.Set;
-
-public abstract class UrlRewriteFunctionDescriptorFactory {
-
-  private static Map<String,Class<? extends UrlRewriteFunctionDescriptor>> MAP
-      = (Map<String, Class<? extends UrlRewriteFunctionDescriptor>>)loadDescriptors();
-
-  private UrlRewriteFunctionDescriptorFactory() {
-  }
-
-  @SuppressWarnings("unchecked")
-  public static <T extends UrlRewriteFunctionDescriptor<?>> T create( String name ) {
-    try {
-      Class<? extends UrlRewriteFunctionDescriptor> descriptorClass = MAP.get( name );
-      return (T)descriptorClass.newInstance();
-    } catch( InstantiationException e ) {
-      throw new IllegalArgumentException( name );
-    } catch( IllegalAccessException e ) {
-      throw new IllegalArgumentException( name );
-    }
-  }
-
-  private static Map<String,Class<? extends UrlRewriteFunctionDescriptor>> loadDescriptors() {
-    Map<String,Class<? extends UrlRewriteFunctionDescriptor>> map
-        = new HashMap<>();
-    ServiceLoader<? extends UrlRewriteFunctionDescriptor> descriptors
-        = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
-    for( UrlRewriteFunctionDescriptor descriptor : descriptors ) {
-      String functionName = descriptor.name();
-      Class<? extends UrlRewriteFunctionDescriptor> descriptorClass = descriptor.getClass() ;
-      map.put( functionName, descriptorClass );
-    }
-    return map;
-  }
-
-  public static Set<String> getNames() {
-    return MAP.keySet();
-  }
-}


[07/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthFederationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthFederationFilter.java b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthFederationFilter.java
new file mode 100644
index 0000000..13e023f
--- /dev/null
+++ b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthFederationFilter.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.knox.gateway.preauth.filter;
+
+import java.io.IOException;
+import java.security.AccessController;
+import java.security.Principal;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.List;
+
+import javax.security.auth.Subject;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+
+public class PreAuthFederationFilter implements Filter {
+  private static final String CUSTOM_HEADER_PARAM = "preauth.customHeader";
+  private List<PreAuthValidator> validators = null;
+  private FilterConfig filterConfig;
+  private String headerName = "SM_USER";
+
+  @Override
+  public void init(FilterConfig filterConfig) throws ServletException {
+    String customHeader = filterConfig.getInitParameter(CUSTOM_HEADER_PARAM);
+    if (customHeader != null) {
+      headerName = customHeader;
+    }
+    this.filterConfig = filterConfig;
+    validators = PreAuthService.getValidators(filterConfig);
+  }
+
+  @Override
+  public void doFilter(ServletRequest request, ServletResponse response,
+                       FilterChain chain) throws IOException, ServletException {
+    HttpServletRequest httpRequest = (HttpServletRequest) request;
+    if (httpRequest.getHeader(headerName) != null) {
+      if (PreAuthService.validate(httpRequest, filterConfig, validators)) {
+        // TODO: continue as subject
+        chain.doFilter(request, response);
+      } else {
+        // TODO: log preauthenticated SSO validation failure
+        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing Required Header for SSO Validation");
+      }
+    } else {
+      ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing Required Header for PreAuth SSO Federation");
+    }
+  }
+
+  /* (non-Javadoc)
+   * @see javax.servlet.Filter#destroy()
+   */
+  @Override
+  public void destroy() {
+    // TODO Auto-generated method stub
+
+  }
+
+  /**
+   * Recreate the current Subject based upon the provided mappedPrincipal
+   * and look for the groups that should be associated with the new Subject.
+   * Upon finding groups mapped to the principal - add them to the new Subject.
+   * @param mappedPrincipalName
+   * @throws ServletException
+   * @throws IOException
+   */
+  protected void continueChainAsPrincipal(final ServletRequest request, final ServletResponse response,
+                                          final FilterChain chain, String principal) throws IOException, ServletException {
+    Subject subject = null;
+    Principal primaryPrincipal = null;
+
+    // do some check to ensure that the extracted identity matches any existing security context
+    // if not, there is may be someone tampering with the request - consult config to determine
+    // how we are to handle it
+
+    // TODO: make sure that this makes sense with existing sessions or lack thereof
+    Subject currentSubject = Subject.getSubject(AccessController.getContext());
+    if (currentSubject != null) {
+      primaryPrincipal = (PrimaryPrincipal) currentSubject.getPrincipals(PrimaryPrincipal.class).toArray()[0];
+      if (primaryPrincipal != null) {
+        if (!primaryPrincipal.getName().equals(principal)) {
+        }
+      }
+    }
+
+    subject = new Subject();
+    subject.getPrincipals().add(primaryPrincipal);
+    doAs(request, response, chain, subject);
+  }
+
+  private void doAs(final ServletRequest request,
+                    final ServletResponse response, final FilterChain chain, Subject subject)
+      throws IOException, ServletException {
+    try {
+      Subject.doAs(
+          subject,
+          new PrivilegedExceptionAction<Object>() {
+            public Object run() throws Exception {
+              doFilterInternal(request, response, chain);
+              return null;
+            }
+          }
+      );
+    } catch (PrivilegedActionException e) {
+      Throwable t = e.getCause();
+      if (t instanceof IOException) {
+        throw (IOException) t;
+      } else if (t instanceof ServletException) {
+        throw (ServletException) t;
+      } else {
+        throw new ServletException(t);
+      }
+    }
+  }
+
+  private void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+    chain.doFilter(request, response);
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthService.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthService.java b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthService.java
new file mode 100644
index 0000000..5e0ef6a
--- /dev/null
+++ b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthService.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.knox.gateway.preauth.filter;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Strings;
+
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.Collections;
+import java.util.ServiceLoader;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * This class manages few utility methods used across different classes of pre-auth module
+ * @since 0.12
+ */
+public class PreAuthService {
+
+  public static final String VALIDATION_METHOD_PARAM = "preauth.validation.method";
+  private static ConcurrentHashMap<String, PreAuthValidator> validatorMap;
+
+  static {
+    initializeValidators();
+  }
+
+
+  private static void initializeValidators() {
+    ServiceLoader<PreAuthValidator> servLoader = ServiceLoader.load(PreAuthValidator.class);
+    validatorMap = new ConcurrentHashMap<>();
+    for (Iterator<PreAuthValidator> iterator = servLoader.iterator(); iterator.hasNext(); ) {
+      PreAuthValidator validator = iterator.next();
+      validatorMap.put(validator.getName(), validator);
+    }
+  }
+
+  @VisibleForTesting
+  public static Map<String, PreAuthValidator> getValidatorMap() {
+    return Collections.unmodifiableMap(validatorMap);
+  }
+
+  /**
+   * This method returns appropriate pre-auth Validator as defined in config
+   *
+   * @since 0.12
+   * @param filterConfig
+   * @return List<PreAuthValidator>
+   * @throws ServletException
+   */
+  public static List<PreAuthValidator> getValidators(FilterConfig filterConfig) throws ServletException {
+    String validationMethods = filterConfig.getInitParameter(VALIDATION_METHOD_PARAM);
+    List<PreAuthValidator> vList = new ArrayList<>();
+    if (Strings.isNullOrEmpty(validationMethods)) {
+      validationMethods = DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE;
+    }
+    Set<String> vMethodSet = new LinkedHashSet<>();
+    Collections.addAll(vMethodSet, validationMethods.trim().split("\\s*,\\s*"));
+    for (String vName : vMethodSet) {
+      if (validatorMap.containsKey(vName)) {
+        vList.add(validatorMap.get(vName));
+      } else {
+        throw new ServletException(String.format("Unable to find validator with name '%s'", validationMethods));
+      }
+    }
+    return vList;
+  }
+
+  public static boolean validate(HttpServletRequest httpRequest, FilterConfig filterConfig, List<PreAuthValidator>
+      validators) {
+    try {
+      for (PreAuthValidator validator : validators) {
+        //Any one validator fails, it will fail the request. loginal AND behavior
+        if (!validator.validate(httpRequest, filterConfig)) {
+          return false;
+        }
+      }
+    } catch (PreAuthValidationException e) {
+      // TODO log exception
+      return false;
+    }
+    return true;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthValidationException.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthValidationException.java b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthValidationException.java
new file mode 100644
index 0000000..3a20cce
--- /dev/null
+++ b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthValidationException.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.knox.gateway.preauth.filter;
+
+/**
+ * @author larry
+ *
+ */
+public class PreAuthValidationException extends Exception {
+  PreAuthValidationException(String message) {
+    super(message);
+  }
+
+  PreAuthValidationException(String message, Exception e) {
+    super(message, e);
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthValidator.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthValidator.java b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthValidator.java
new file mode 100644
index 0000000..e0b556d
--- /dev/null
+++ b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/PreAuthValidator.java
@@ -0,0 +1,42 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.preauth.filter;
+
+import javax.servlet.FilterConfig;
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ *
+ */
+public interface PreAuthValidator {
+  /**
+   * @param httpRequest
+   * @param filterConfig
+   * @return true if validated, otherwise false
+   * @throws PreAuthValidationException
+   */
+  public abstract boolean validate(HttpServletRequest httpRequest, FilterConfig filterConfig) throws
+      PreAuthValidationException;
+
+  /**
+   * Return unique validator name
+   *
+   * @return name of validator
+   */
+  public abstract String getName();
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index 1e89ee8..0000000
--- a/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.preauth.deploy.HeaderPreAuthContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.hadoop.gateway.preauth.filter.PreAuthValidator
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.hadoop.gateway.preauth.filter.PreAuthValidator b/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.hadoop.gateway.preauth.filter.PreAuthValidator
deleted file mode 100644
index 808dbe8..0000000
--- a/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.hadoop.gateway.preauth.filter.PreAuthValidator
+++ /dev/null
@@ -1,20 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.preauth.filter.IPValidator
-org.apache.hadoop.gateway.preauth.filter.DefaultValidator
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..78da4f8
--- /dev/null
+++ b/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.preauth.deploy.HeaderPreAuthContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.knox.gateway.preauth.filter.PreAuthValidator
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.knox.gateway.preauth.filter.PreAuthValidator b/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.knox.gateway.preauth.filter.PreAuthValidator
new file mode 100644
index 0000000..e3957df
--- /dev/null
+++ b/gateway-provider-security-preauth/src/main/resources/META-INF/services/org.apache.knox.gateway.preauth.filter.PreAuthValidator
@@ -0,0 +1,20 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.preauth.filter.IPValidator
+org.apache.knox.gateway.preauth.filter.DefaultValidator
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/DefaultValidatorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/DefaultValidatorTest.java b/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/DefaultValidatorTest.java
deleted file mode 100644
index 4096b48..0000000
--- a/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/DefaultValidatorTest.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.hadoop.gateway.provider.federation;
-
-import junit.framework.TestCase;
-import org.apache.hadoop.gateway.preauth.filter.DefaultValidator;
-import org.junit.Test;
-
-import static org.mockito.Mockito.mock;
-
-import javax.servlet.FilterConfig;
-import javax.servlet.http.HttpServletRequest;
-
-public class DefaultValidatorTest extends TestCase {
-  @Test
-  public void testDefault() throws Exception {
-    final FilterConfig filterConfig = mock(FilterConfig.class);
-    final HttpServletRequest request = mock(HttpServletRequest.class);
-    DefaultValidator dv = new DefaultValidator();
-    assertTrue(dv.validate(request, filterConfig));
-  }
-
-  @Test
-  public void testName() {
-    DefaultValidator dv = new DefaultValidator();
-    assertEquals(dv.getName(), DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE);
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/HeaderPreAuthFederationFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/HeaderPreAuthFederationFilterTest.java b/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/HeaderPreAuthFederationFilterTest.java
deleted file mode 100644
index 365ec45..0000000
--- a/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/HeaderPreAuthFederationFilterTest.java
+++ /dev/null
@@ -1,140 +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.hadoop.gateway.provider.federation;
-
-import junit.framework.TestCase;
-import org.apache.hadoop.gateway.preauth.filter.*;
-import org.junit.Test;
-
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-
-import java.util.List;
-
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class HeaderPreAuthFederationFilterTest extends TestCase {
-
-  @Test
-  public void testDefaultValidator() throws ServletException, PreAuthValidationException {
-    HeaderPreAuthFederationFilter hpaff = new HeaderPreAuthFederationFilter();
-    final HttpServletRequest request = mock(HttpServletRequest.class);
-    final FilterConfig filterConfig = mock(FilterConfig.class);
-    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn
-        (DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE);
-    hpaff.init(filterConfig);
-    List<PreAuthValidator> validators = hpaff.getValidators();
-    assertEquals(validators.size(), 1);
-    assertEquals(validators.get(0).getName(), DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE);
-    assertTrue(PreAuthService.validate(request, filterConfig, validators));
-  }
-
-  @Test
-  public void testIPValidator() throws ServletException, PreAuthValidationException {
-    HeaderPreAuthFederationFilter hpaff = new HeaderPreAuthFederationFilter();
-    final HttpServletRequest request = mock(HttpServletRequest.class);
-    when(request.getRemoteAddr()).thenReturn("10.1.23.42");
-    final FilterConfig filterConfig = mock(FilterConfig.class);
-    when(filterConfig.getInitParameter(IPValidator.IP_ADDRESSES_PARAM)).thenReturn("5.4.3.2,10.1.23.42");
-    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn(IPValidator
-        .IP_VALIDATION_METHOD_VALUE);
-    hpaff.init(filterConfig);
-    List<PreAuthValidator> validators = hpaff.getValidators();
-    assertEquals(validators.size(), 1);
-    assertEquals(validators.get(0).getName(), IPValidator.IP_VALIDATION_METHOD_VALUE);
-    assertTrue(PreAuthService.validate(request, filterConfig, validators));
-    //Negative testing
-    when(request.getRemoteAddr()).thenReturn("10.10.22.33");
-    assertFalse(PreAuthService.validate(request, filterConfig, validators));
-  }
-
-  @Test
-  public void testCustomValidatorPositive() throws ServletException, PreAuthValidationException {
-    HeaderPreAuthFederationFilter hpaff = new HeaderPreAuthFederationFilter();
-    final HttpServletRequest request = mock(HttpServletRequest.class);
-    final FilterConfig filterConfig = mock(FilterConfig.class);
-    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn
-        (DummyValidator.NAME);
-
-    hpaff.init(filterConfig);
-    List<PreAuthValidator> validators = hpaff.getValidators();
-    assertEquals(validators.size(), 1);
-    assertEquals(validators.get(0).getName(), DummyValidator.NAME);
-    //Positive test
-    when(request.getHeader("CUSTOM_TOKEN")).thenReturn("HelloWorld");
-    assertTrue(PreAuthService.validate(request, filterConfig, validators));
-
-  }
-
-  @Test
-  public void testCustomValidatorNegative() throws ServletException, PreAuthValidationException {
-    HeaderPreAuthFederationFilter hpaff = new HeaderPreAuthFederationFilter();
-    final HttpServletRequest request = mock(HttpServletRequest.class);
-    final FilterConfig filterConfig = mock(FilterConfig.class);
-    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn
-        (DummyValidator.NAME);
-
-    hpaff.init(filterConfig);
-    List<PreAuthValidator> validators = hpaff.getValidators();
-    assertEquals(validators.size(), 1);
-    assertEquals(validators.get(0).getName(), DummyValidator.NAME);
-
-    when(request.getHeader("CUSTOM_TOKEN")).thenReturn("NOTHelloWorld");
-    assertFalse(PreAuthService.validate(request, filterConfig, validators));
-
-  }
-
-
-  public static class DummyValidator implements PreAuthValidator {
-    public static String NAME = "DummyValidator";
-
-    public DummyValidator() {
-
-    }
-
-    /**
-     * @param httpRequest
-     * @param filterConfig
-     * @return true if validated, otherwise false
-     * @throws PreAuthValidationException
-     */
-    @Override
-    public boolean validate(HttpServletRequest httpRequest, FilterConfig filterConfig) throws
-        PreAuthValidationException {
-      String token = httpRequest.getHeader("CUSTOM_TOKEN");
-      if (token.equalsIgnoreCase("HelloWorld")) {
-        return true;
-      } else {
-        return false;
-      }
-    }
-
-    /**
-     * Return unique validator name
-     *
-     * @return name of validator
-     */
-    @Override
-    public String getName() {
-      return NAME;
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/IPValidatorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/IPValidatorTest.java b/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/IPValidatorTest.java
deleted file mode 100644
index 23c0096..0000000
--- a/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/IPValidatorTest.java
+++ /dev/null
@@ -1,61 +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.hadoop.gateway.provider.federation;
-
-import junit.framework.TestCase;
-import org.apache.hadoop.gateway.preauth.filter.IPValidator;
-import org.apache.hadoop.gateway.preauth.filter.PreAuthValidationException;
-import org.junit.Test;
-
-import javax.servlet.FilterConfig;
-import javax.servlet.http.HttpServletRequest;
-
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class IPValidatorTest extends TestCase {
-
-  @Test
-  public void testName() {
-    IPValidator ipv = new IPValidator();
-    assertEquals(ipv.getName(), IPValidator.IP_VALIDATION_METHOD_VALUE);
-  }
-
-
-  @Test
-  public void testIPAddressPositive() throws PreAuthValidationException {
-    IPValidator ipv = new IPValidator();
-    final HttpServletRequest request = mock(HttpServletRequest.class);
-    when(request.getRemoteAddr()).thenReturn("10.1.23.42");
-    final FilterConfig filterConfig = mock(FilterConfig.class);
-    when(filterConfig.getInitParameter(IPValidator.IP_ADDRESSES_PARAM)).thenReturn("5.4.3.2,10.1.23.42");
-    assertTrue(ipv.validate(request, filterConfig));
-  }
-
-  @Test
-  public void testIPAddressNegative() throws PreAuthValidationException {
-    IPValidator ipv = new IPValidator();
-    final HttpServletRequest request = mock(HttpServletRequest.class);
-    when(request.getRemoteAddr()).thenReturn("10.1.23.42");
-    final FilterConfig filterConfig = mock(FilterConfig.class);
-    when(filterConfig.getInitParameter(IPValidator.IP_ADDRESSES_PARAM)).thenReturn("10.22.34.56");
-    assertFalse(ipv.validate(request, filterConfig));
-  }
-
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/PreAuthSSOTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/PreAuthSSOTest.java b/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/PreAuthSSOTest.java
deleted file mode 100644
index ec57043..0000000
--- a/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/PreAuthSSOTest.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.provider.federation;
-
-import junit.framework.TestCase;
-
-import org.apache.hadoop.gateway.services.security.token.impl.JWTToken;
-import org.junit.Test;
-
-public class PreAuthSSOTest extends TestCase {
-  @Test
-  public void testPreAuth() throws Exception {
-    assertTrue(true);
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/PreAuthServiceTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/PreAuthServiceTest.java b/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/PreAuthServiceTest.java
deleted file mode 100644
index 0332a6c..0000000
--- a/gateway-provider-security-preauth/src/test/java/org/apache/hadoop/gateway/provider/federation/PreAuthServiceTest.java
+++ /dev/null
@@ -1,109 +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.hadoop.gateway.provider.federation;
-
-import junit.framework.TestCase;
-import org.apache.hadoop.gateway.preauth.filter.*;
-import org.junit.Test;
-
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-
-import java.util.List;
-import java.util.Map;
-
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class PreAuthServiceTest extends TestCase {
-
-  @Test
-  public void testValidatorMap() {
-    Map<String, PreAuthValidator> valMap = PreAuthService.getValidatorMap();
-    assertNotNull(valMap.get(IPValidator.IP_VALIDATION_METHOD_VALUE));
-    assertEquals(valMap.get(IPValidator.IP_VALIDATION_METHOD_VALUE).getName(), IPValidator.IP_VALIDATION_METHOD_VALUE);
-    assertNotNull(valMap.get(DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE));
-    assertEquals(valMap.get(DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE).getName(), DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE);
-
-    //Negative test
-    assertNull(valMap.get("NonExists"));
-  }
-
-  @Test
-  public void testDefaultValidator() throws ServletException, PreAuthValidationException {
-    final HttpServletRequest request = mock(HttpServletRequest.class);
-    final FilterConfig filterConfig = mock(FilterConfig.class);
-    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn
-        (DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE);
-    List<PreAuthValidator> validators = PreAuthService.getValidators(filterConfig);
-    assertEquals(validators.size(), 1);
-    assertEquals(validators.get(0).getName(), DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE);
-    assertTrue(PreAuthService.validate(request, filterConfig, validators));
-  }
-
-  @Test
-  public void testIPValidator() throws ServletException, PreAuthValidationException {
-    final HttpServletRequest request = mock(HttpServletRequest.class);
-    when(request.getRemoteAddr()).thenReturn("10.1.23.42");
-    final FilterConfig filterConfig = mock(FilterConfig.class);
-    when(filterConfig.getInitParameter(IPValidator.IP_ADDRESSES_PARAM)).thenReturn("5.4.3.2,10.1.23.42");
-    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn(IPValidator
-        .IP_VALIDATION_METHOD_VALUE);
-    List<PreAuthValidator> validators = PreAuthService.getValidators(filterConfig);
-    assertEquals(validators.size(), 1);
-    assertEquals(validators.get(0).getName(), IPValidator.IP_VALIDATION_METHOD_VALUE);
-    assertTrue(PreAuthService.validate(request, filterConfig, validators));
-    //Negative testing
-    when(request.getRemoteAddr()).thenReturn("10.10.22.33");
-    assertFalse(PreAuthService.validate(request, filterConfig, validators));
-  }
-
-  @Test
-  public void testMultipleValidatorsPositive() throws ServletException, PreAuthValidationException {
-    final HttpServletRequest request = mock(HttpServletRequest.class);
-    when(request.getRemoteAddr()).thenReturn("10.1.23.42");
-    final FilterConfig filterConfig = mock(FilterConfig.class);
-    when(filterConfig.getInitParameter(IPValidator.IP_ADDRESSES_PARAM)).thenReturn("5.4.3.2,10.1.23.42");
-    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn
-        (DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE + "," + IPValidator.IP_VALIDATION_METHOD_VALUE );
-    List<PreAuthValidator> validators = PreAuthService.getValidators(filterConfig);
-    assertEquals(validators.size(), 2);
-    assertEquals(validators.get(0).getName(), DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE);
-    assertEquals(validators.get(1).getName(), IPValidator.IP_VALIDATION_METHOD_VALUE);
-
-    assertTrue(PreAuthService.validate(request, filterConfig, validators));
-    //Negative testing
-    when(request.getRemoteAddr()).thenReturn("10.10.22.33");
-    assertFalse(PreAuthService.validate(request, filterConfig, validators));
-
-  }
-
-  @Test
-  public void testMultipleValidatorsNegative() throws ServletException, PreAuthValidationException {
-    final FilterConfig filterConfig = mock(FilterConfig.class);
-    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn
-        (DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE + ",  NOT_EXISTED_VALIDATOR" );
-    try {
-      PreAuthService.getValidators(filterConfig);
-      fail("Should throw exception due to invalid validator");
-    } catch (Exception e) {
-      //Expected
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/DefaultValidatorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/DefaultValidatorTest.java b/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/DefaultValidatorTest.java
new file mode 100644
index 0000000..699f7d4
--- /dev/null
+++ b/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/DefaultValidatorTest.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.knox.gateway.provider.federation;
+
+import junit.framework.TestCase;
+import org.apache.knox.gateway.preauth.filter.DefaultValidator;
+import org.junit.Test;
+
+import static org.mockito.Mockito.mock;
+
+import javax.servlet.FilterConfig;
+import javax.servlet.http.HttpServletRequest;
+
+public class DefaultValidatorTest extends TestCase {
+  @Test
+  public void testDefault() throws Exception {
+    final FilterConfig filterConfig = mock(FilterConfig.class);
+    final HttpServletRequest request = mock(HttpServletRequest.class);
+    DefaultValidator dv = new DefaultValidator();
+    assertTrue(dv.validate(request, filterConfig));
+  }
+
+  @Test
+  public void testName() {
+    DefaultValidator dv = new DefaultValidator();
+    assertEquals(dv.getName(), DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE);
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/HeaderPreAuthFederationFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/HeaderPreAuthFederationFilterTest.java b/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/HeaderPreAuthFederationFilterTest.java
new file mode 100644
index 0000000..efa0774
--- /dev/null
+++ b/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/HeaderPreAuthFederationFilterTest.java
@@ -0,0 +1,147 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.provider.federation;
+
+import junit.framework.TestCase;
+import org.apache.hadoop.gateway.preauth.filter.*;
+import org.apache.knox.gateway.preauth.filter.DefaultValidator;
+import org.apache.knox.gateway.preauth.filter.HeaderPreAuthFederationFilter;
+import org.apache.knox.gateway.preauth.filter.IPValidator;
+import org.apache.knox.gateway.preauth.filter.PreAuthService;
+import org.apache.knox.gateway.preauth.filter.PreAuthValidationException;
+import org.apache.knox.gateway.preauth.filter.PreAuthValidator;
+import org.junit.Test;
+
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+
+import java.util.List;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class HeaderPreAuthFederationFilterTest extends TestCase {
+
+  @Test
+  public void testDefaultValidator() throws ServletException,
+      PreAuthValidationException {
+    HeaderPreAuthFederationFilter hpaff = new HeaderPreAuthFederationFilter();
+    final HttpServletRequest request = mock(HttpServletRequest.class);
+    final FilterConfig filterConfig = mock(FilterConfig.class);
+    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn
+        (DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE);
+    hpaff.init(filterConfig);
+    List<PreAuthValidator> validators = hpaff.getValidators();
+    assertEquals(validators.size(), 1);
+    assertEquals(validators.get(0).getName(), DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE);
+    assertTrue(PreAuthService.validate(request, filterConfig, validators));
+  }
+
+  @Test
+  public void testIPValidator() throws ServletException, PreAuthValidationException {
+    HeaderPreAuthFederationFilter hpaff = new HeaderPreAuthFederationFilter();
+    final HttpServletRequest request = mock(HttpServletRequest.class);
+    when(request.getRemoteAddr()).thenReturn("10.1.23.42");
+    final FilterConfig filterConfig = mock(FilterConfig.class);
+    when(filterConfig.getInitParameter(IPValidator.IP_ADDRESSES_PARAM)).thenReturn("5.4.3.2,10.1.23.42");
+    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn(IPValidator
+        .IP_VALIDATION_METHOD_VALUE);
+    hpaff.init(filterConfig);
+    List<PreAuthValidator> validators = hpaff.getValidators();
+    assertEquals(validators.size(), 1);
+    assertEquals(validators.get(0).getName(), IPValidator.IP_VALIDATION_METHOD_VALUE);
+    assertTrue(PreAuthService.validate(request, filterConfig, validators));
+    //Negative testing
+    when(request.getRemoteAddr()).thenReturn("10.10.22.33");
+    assertFalse(PreAuthService.validate(request, filterConfig, validators));
+  }
+
+  @Test
+  public void testCustomValidatorPositive() throws ServletException, PreAuthValidationException {
+    HeaderPreAuthFederationFilter hpaff = new HeaderPreAuthFederationFilter();
+    final HttpServletRequest request = mock(HttpServletRequest.class);
+    final FilterConfig filterConfig = mock(FilterConfig.class);
+    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn
+        (DummyValidator.NAME);
+
+    hpaff.init(filterConfig);
+    List<PreAuthValidator> validators = hpaff.getValidators();
+    assertEquals(validators.size(), 1);
+    assertEquals(validators.get(0).getName(), DummyValidator.NAME);
+    //Positive test
+    when(request.getHeader("CUSTOM_TOKEN")).thenReturn("HelloWorld");
+    assertTrue(PreAuthService.validate(request, filterConfig, validators));
+
+  }
+
+  @Test
+  public void testCustomValidatorNegative() throws ServletException, PreAuthValidationException {
+    HeaderPreAuthFederationFilter hpaff = new HeaderPreAuthFederationFilter();
+    final HttpServletRequest request = mock(HttpServletRequest.class);
+    final FilterConfig filterConfig = mock(FilterConfig.class);
+    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn
+        (DummyValidator.NAME);
+
+    hpaff.init(filterConfig);
+    List<PreAuthValidator> validators = hpaff.getValidators();
+    assertEquals(validators.size(), 1);
+    assertEquals(validators.get(0).getName(), DummyValidator.NAME);
+
+    when(request.getHeader("CUSTOM_TOKEN")).thenReturn("NOTHelloWorld");
+    assertFalse(PreAuthService.validate(request, filterConfig, validators));
+
+  }
+
+
+  public static class DummyValidator implements PreAuthValidator {
+    public static String NAME = "DummyValidator";
+
+    public DummyValidator() {
+
+    }
+
+    /**
+     * @param httpRequest
+     * @param filterConfig
+     * @return true if validated, otherwise false
+     * @throws PreAuthValidationException
+     */
+    @Override
+    public boolean validate(HttpServletRequest httpRequest, FilterConfig filterConfig) throws
+        PreAuthValidationException {
+      String token = httpRequest.getHeader("CUSTOM_TOKEN");
+      if (token.equalsIgnoreCase("HelloWorld")) {
+        return true;
+      } else {
+        return false;
+      }
+    }
+
+    /**
+     * Return unique validator name
+     *
+     * @return name of validator
+     */
+    @Override
+    public String getName() {
+      return NAME;
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/IPValidatorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/IPValidatorTest.java b/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/IPValidatorTest.java
new file mode 100644
index 0000000..704090c
--- /dev/null
+++ b/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/IPValidatorTest.java
@@ -0,0 +1,61 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.provider.federation;
+
+import junit.framework.TestCase;
+import org.apache.knox.gateway.preauth.filter.IPValidator;
+import org.apache.knox.gateway.preauth.filter.PreAuthValidationException;
+import org.junit.Test;
+
+import javax.servlet.FilterConfig;
+import javax.servlet.http.HttpServletRequest;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class IPValidatorTest extends TestCase {
+
+  @Test
+  public void testName() {
+    IPValidator ipv = new IPValidator();
+    assertEquals(ipv.getName(), IPValidator.IP_VALIDATION_METHOD_VALUE);
+  }
+
+
+  @Test
+  public void testIPAddressPositive() throws PreAuthValidationException {
+    IPValidator ipv = new IPValidator();
+    final HttpServletRequest request = mock(HttpServletRequest.class);
+    when(request.getRemoteAddr()).thenReturn("10.1.23.42");
+    final FilterConfig filterConfig = mock(FilterConfig.class);
+    when(filterConfig.getInitParameter(IPValidator.IP_ADDRESSES_PARAM)).thenReturn("5.4.3.2,10.1.23.42");
+    assertTrue(ipv.validate(request, filterConfig));
+  }
+
+  @Test
+  public void testIPAddressNegative() throws PreAuthValidationException {
+    IPValidator ipv = new IPValidator();
+    final HttpServletRequest request = mock(HttpServletRequest.class);
+    when(request.getRemoteAddr()).thenReturn("10.1.23.42");
+    final FilterConfig filterConfig = mock(FilterConfig.class);
+    when(filterConfig.getInitParameter(IPValidator.IP_ADDRESSES_PARAM)).thenReturn("10.22.34.56");
+    assertFalse(ipv.validate(request, filterConfig));
+  }
+
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/PreAuthSSOTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/PreAuthSSOTest.java b/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/PreAuthSSOTest.java
new file mode 100644
index 0000000..5babe90
--- /dev/null
+++ b/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/PreAuthSSOTest.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.knox.gateway.provider.federation;
+
+import junit.framework.TestCase;
+
+import org.junit.Test;
+
+public class PreAuthSSOTest extends TestCase {
+  @Test
+  public void testPreAuth() throws Exception {
+    assertTrue(true);
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/PreAuthServiceTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/PreAuthServiceTest.java b/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/PreAuthServiceTest.java
new file mode 100644
index 0000000..5a5cced
--- /dev/null
+++ b/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/PreAuthServiceTest.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.knox.gateway.provider.federation;
+
+import junit.framework.TestCase;
+import org.apache.hadoop.gateway.preauth.filter.*;
+import org.apache.knox.gateway.preauth.filter.DefaultValidator;
+import org.apache.knox.gateway.preauth.filter.IPValidator;
+import org.apache.knox.gateway.preauth.filter.PreAuthService;
+import org.apache.knox.gateway.preauth.filter.PreAuthValidationException;
+import org.apache.knox.gateway.preauth.filter.PreAuthValidator;
+import org.junit.Test;
+
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+
+import java.util.List;
+import java.util.Map;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class PreAuthServiceTest extends TestCase {
+
+  @Test
+  public void testValidatorMap() {
+    Map<String, PreAuthValidator> valMap = PreAuthService.getValidatorMap();
+    assertNotNull(valMap.get(IPValidator.IP_VALIDATION_METHOD_VALUE));
+    assertEquals(valMap.get(IPValidator.IP_VALIDATION_METHOD_VALUE).getName(), IPValidator.IP_VALIDATION_METHOD_VALUE);
+    assertNotNull(valMap.get(DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE));
+    assertEquals(valMap.get(DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE).getName(), DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE);
+
+    //Negative test
+    assertNull(valMap.get("NonExists"));
+  }
+
+  @Test
+  public void testDefaultValidator() throws ServletException,
+      PreAuthValidationException {
+    final HttpServletRequest request = mock(HttpServletRequest.class);
+    final FilterConfig filterConfig = mock(FilterConfig.class);
+    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn
+        (DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE);
+    List<PreAuthValidator> validators = PreAuthService.getValidators(filterConfig);
+    assertEquals(validators.size(), 1);
+    assertEquals(validators.get(0).getName(), DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE);
+    assertTrue(PreAuthService.validate(request, filterConfig, validators));
+  }
+
+  @Test
+  public void testIPValidator() throws ServletException, PreAuthValidationException {
+    final HttpServletRequest request = mock(HttpServletRequest.class);
+    when(request.getRemoteAddr()).thenReturn("10.1.23.42");
+    final FilterConfig filterConfig = mock(FilterConfig.class);
+    when(filterConfig.getInitParameter(IPValidator.IP_ADDRESSES_PARAM)).thenReturn("5.4.3.2,10.1.23.42");
+    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn(IPValidator
+        .IP_VALIDATION_METHOD_VALUE);
+    List<PreAuthValidator> validators = PreAuthService.getValidators(filterConfig);
+    assertEquals(validators.size(), 1);
+    assertEquals(validators.get(0).getName(), IPValidator.IP_VALIDATION_METHOD_VALUE);
+    assertTrue(PreAuthService.validate(request, filterConfig, validators));
+    //Negative testing
+    when(request.getRemoteAddr()).thenReturn("10.10.22.33");
+    assertFalse(PreAuthService.validate(request, filterConfig, validators));
+  }
+
+  @Test
+  public void testMultipleValidatorsPositive() throws ServletException, PreAuthValidationException {
+    final HttpServletRequest request = mock(HttpServletRequest.class);
+    when(request.getRemoteAddr()).thenReturn("10.1.23.42");
+    final FilterConfig filterConfig = mock(FilterConfig.class);
+    when(filterConfig.getInitParameter(IPValidator.IP_ADDRESSES_PARAM)).thenReturn("5.4.3.2,10.1.23.42");
+    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn
+        (DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE + "," + IPValidator.IP_VALIDATION_METHOD_VALUE );
+    List<PreAuthValidator> validators = PreAuthService.getValidators(filterConfig);
+    assertEquals(validators.size(), 2);
+    assertEquals(validators.get(0).getName(), DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE);
+    assertEquals(validators.get(1).getName(), IPValidator.IP_VALIDATION_METHOD_VALUE);
+
+    assertTrue(PreAuthService.validate(request, filterConfig, validators));
+    //Negative testing
+    when(request.getRemoteAddr()).thenReturn("10.10.22.33");
+    assertFalse(PreAuthService.validate(request, filterConfig, validators));
+
+  }
+
+  @Test
+  public void testMultipleValidatorsNegative() throws ServletException, PreAuthValidationException {
+    final FilterConfig filterConfig = mock(FilterConfig.class);
+    when(filterConfig.getInitParameter(PreAuthService.VALIDATION_METHOD_PARAM)).thenReturn
+        (DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE + ",  NOT_EXISTED_VALIDATOR" );
+    try {
+      PreAuthService.getValidators(filterConfig);
+      fail("Should throw exception due to invalid validator");
+    } catch (Exception e) {
+      //Expected
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/test/resources/META-INF/services/org.apache.hadoop.gateway.preauth.filter.PreAuthValidator
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/test/resources/META-INF/services/org.apache.hadoop.gateway.preauth.filter.PreAuthValidator b/gateway-provider-security-preauth/src/test/resources/META-INF/services/org.apache.hadoop.gateway.preauth.filter.PreAuthValidator
deleted file mode 100644
index 911bd0f..0000000
--- a/gateway-provider-security-preauth/src/test/resources/META-INF/services/org.apache.hadoop.gateway.preauth.filter.PreAuthValidator
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.provider.federation.HeaderPreAuthFederationFilterTest$DummyValidator
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/test/resources/META-INF/services/org.apache.knox.gateway.preauth.filter.PreAuthValidator
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/test/resources/META-INF/services/org.apache.knox.gateway.preauth.filter.PreAuthValidator b/gateway-provider-security-preauth/src/test/resources/META-INF/services/org.apache.knox.gateway.preauth.filter.PreAuthValidator
new file mode 100644
index 0000000..e6d47b1
--- /dev/null
+++ b/gateway-provider-security-preauth/src/test/resources/META-INF/services/org.apache.knox.gateway.preauth.filter.PreAuthValidator
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.provider.federation.HeaderPreAuthFederationFilterTest$DummyValidator
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/deploy/impl/ShiroConfig.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/deploy/impl/ShiroConfig.java b/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/deploy/impl/ShiroConfig.java
deleted file mode 100644
index 8659760..0000000
--- a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/deploy/impl/ShiroConfig.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.hadoop.gateway.deploy.impl;
-
-import org.apache.hadoop.gateway.topology.Provider;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-public class ShiroConfig {
-  
-  private Map<String, Map<String, String>> sections = new LinkedHashMap<String, Map<String, String>>();
- 
-  public ShiroConfig(Provider provider, String clusterName) {
-    Map<String, String> params = provider.getParams();
-    String name = null;
-    String sectionName = null;
-    String value = null;
-    for(Entry<String, String> entry : params.entrySet()) {
-      int sectionDot = entry.getKey().indexOf('.');
-      if (sectionDot > 0) {
-        sectionName = entry.getKey().substring(0, sectionDot);
-        name = entry.getKey().substring(sectionDot + 1);
-        value = entry.getValue().trim();
-        if (value.startsWith("${ALIAS=") && value.endsWith("}")) {
-          String baseName = name.substring(0, name.lastIndexOf("."));
-          addNameValueToSection(baseName + ".clusterName", clusterName, sectionName);
-          addNameValueToSection(name, "S" + value.substring(1), sectionName);
-        } else {
-          addNameValueToSection(name, value, sectionName);
-        }
-      }
-    }
-  }
-
-  private void addNameValueToSection(String name, String value, String sectionName) {
-    Map<String, String> section = sections.get(sectionName);
-    if (section == null) {
-      section = new LinkedHashMap<String, String>();
-      sections.put(sectionName, section);
-    }
-    section.put(name, value);
-  }
-  
-  public String toString() {
-    StringBuilder sb = new StringBuilder();
-    for(Entry<String, Map<String, String>> section : sections.entrySet()) {
-      sb.append("[").append(section.getKey()).append("]\n");
-      for(Entry<String, String> entry : section.getValue().entrySet()) {
-        sb.append(entry.getKey()).append("=").append(entry.getValue()).append("\n");
-      }
-    }
-    return sb.toString();
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/deploy/impl/ShiroDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/deploy/impl/ShiroDeploymentContributor.java b/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/deploy/impl/ShiroDeploymentContributor.java
deleted file mode 100644
index 2b63be6..0000000
--- a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/deploy/impl/ShiroDeploymentContributor.java
+++ /dev/null
@@ -1,140 +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.hadoop.gateway.deploy.impl;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.filter.RedirectToUrlFilter;
-import org.apache.hadoop.gateway.filter.ResponseCookieFilter;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-import org.jboss.shrinkwrap.api.asset.StringAsset;
-import org.jboss.shrinkwrap.descriptor.api.webapp30.WebAppDescriptor;
-import org.jboss.shrinkwrap.descriptor.api.webcommon30.SessionConfigType;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-public class ShiroDeploymentContributor extends ProviderDeploymentContributorBase {
-
-  private static final String LISTENER_CLASSNAME = "org.apache.shiro.web.env.EnvironmentLoaderListener";
-  private static final String SHIRO_FILTER_CLASSNAME = "org.apache.shiro.web.servlet.ShiroFilter";
-  private static final String POST_FILTER_CLASSNAME = "org.apache.hadoop.gateway.filter.ShiroSubjectIdentityAdapter";
-  private static final String COOKIE_FILTER_CLASSNAME = "org.apache.hadoop.gateway.filter.ResponseCookieFilter";
-  private static final String REDIRECT_FILTER_CLASSNAME = "org.apache.hadoop.gateway.filter.RedirectToUrlFilter";
-  private static final String SESSION_TIMEOUT = "sessionTimeout";
-  private static final String REMEMBER_ME = "rememberme";
-  private static final String SHRIO_CONFIG_FILE_NAME = "shiro.ini";
-  private static final int DEFAULT_SESSION_TIMEOUT = 30; // 30min
-
-  @Override
-  public String getRole() {
-    return "authentication";
-  }
-
-  @Override
-  public String getName() {
-    return "ShiroProvider";
-  }
-
-  @Override
-  public void contributeProvider( DeploymentContext context, Provider provider ) {
-    // Many filter based authentication mechanisms require a ServletContextListener
-    // to be added and the Knox deployment machinery provides the ability to add this
-    // through the DeploymentContext.
-
-    // Writing provider specific config out to the war for cluster specific config can be
-    // accomplished through the DeploymentContext as well. The JBoss shrinkwrap API can be
-    // used to write the asset to the war.
-
-    // add servletContextListener
-    context.getWebAppDescriptor().createListener().listenerClass( LISTENER_CLASSNAME );
-
-    // add session timeout
-    int st = DEFAULT_SESSION_TIMEOUT;
-    SessionConfigType<WebAppDescriptor> sessionConfig = context.getWebAppDescriptor().createSessionConfig();
-    Map<String, String> params = provider.getParams();
-    String sts = params.get( SESSION_TIMEOUT );
-    if( sts != null && sts.trim().length() != 0 ) {
-      st = Integer.parseInt( sts.trim() );
-    }
-    if( st <= 0 ) {
-      // user default session timeout
-      st = DEFAULT_SESSION_TIMEOUT;
-    }
-    sessionConfig.sessionTimeout( st );
-    sessionConfig.getOrCreateCookieConfig().httpOnly( true );
-    sessionConfig.getOrCreateCookieConfig().secure( true );
-
-    String clusterName = context.getTopology().getName();
-    ShiroConfig config = new ShiroConfig( provider, clusterName );
-    String configStr = config.toString();
-    if( config != null ) {
-      context.getWebArchive().addAsWebInfResource( new StringAsset( configStr ), SHRIO_CONFIG_FILE_NAME );
-    }
-  }
-
-  @Override
-  public void contributeFilter( DeploymentContext context, Provider provider,
-      Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
-    // Leveraging a third party filter is a primary usecase for Knox
-    // in order to do so, we need to make sure that the end result of the third party integration
-    // puts a standard javax.security.auth.Subject on the current thread through a doAs.
-    // As many filters do not use the standard java Subject, often times a post processing filter will
-    // need to be added in order to canonicalize the result into an expected security context.
-
-    // You may also need to do some additional processing of the response in order to not return cookies or other
-    // filter specifics that are not needed for integration with Knox. Below we do that in the pre-processing filter.
-    if (params == null) {
-      params = new ArrayList<FilterParamDescriptor>();
-    }
-    Map<String, String> providerParams = provider.getParams();
-    String redirectToUrl = providerParams.get(RedirectToUrlFilter.REDIRECT_TO_URL);
-    if (redirectToUrl != null) {
-      params.add( resource.createFilterParam()
-          .name(RedirectToUrlFilter.REDIRECT_TO_URL)
-          .value(redirectToUrl));
-      resource.addFilter().name( "Redirect" + getName() ).role(
-          getRole() ).impl( REDIRECT_FILTER_CLASSNAME ).params( params );
-      params.clear();
-    }
-
-    String cookies = providerParams.get( ResponseCookieFilter.RESTRICTED_COOKIES );
-    if (cookies == null) {
-      params.add( resource.createFilterParam()
-          .name( ResponseCookieFilter.RESTRICTED_COOKIES )
-          .value( REMEMBER_ME ) );
-    }
-    else {
-      params.add( resource.createFilterParam()
-          .name(ResponseCookieFilter.RESTRICTED_COOKIES ).value( cookies ) );
-    }
-
-    resource.addFilter().name( "Pre" + getName() ).role(
-        getRole() ).impl( COOKIE_FILTER_CLASSNAME ).params( params );
-    params.clear();
-
-    resource.addFilter().name( getName() ).role(
-        getRole() ).impl( SHIRO_FILTER_CLASSNAME ).params( params );
-    resource.addFilter().name( "Post" + getName() ).role(
-        getRole() ).impl( POST_FILTER_CLASSNAME ).params( params );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/filter/RedirectToUrlFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/filter/RedirectToUrlFilter.java b/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/filter/RedirectToUrlFilter.java
deleted file mode 100644
index 9f1aecc..0000000
--- a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/filter/RedirectToUrlFilter.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.hadoop.gateway.filter;
-
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-
-public class RedirectToUrlFilter extends AbstractGatewayFilter {
-  public static final String REDIRECT_TO_URL = "redirectToUrl";
-
-  protected String redirectUrl = null;
-
-  @Override
-  public void init(FilterConfig filterConfig) throws ServletException {
-    super.init(filterConfig);
-    redirectUrl = filterConfig.getInitParameter(REDIRECT_TO_URL);
-  }
-
-  @Override
-  protected void doFilter( HttpServletRequest request,
-      HttpServletResponse response, FilterChain chain ) throws IOException, ServletException {
-    if (redirectUrl != null && request.getHeader("Authorization") == null) {
-      response.sendRedirect(redirectUrl + getOriginalQueryString(request));
-    }
-    chain.doFilter( request, response );
-  }
-
-  private String getOriginalQueryString(HttpServletRequest request) {
-    String originalQueryString = request.getQueryString();
-    return (originalQueryString == null) ? "" : "?" + originalQueryString;
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/filter/ResponseCookieFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/filter/ResponseCookieFilter.java b/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/filter/ResponseCookieFilter.java
deleted file mode 100644
index 29d30c0..0000000
--- a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/filter/ResponseCookieFilter.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.hadoop.gateway.filter;
-
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpServletResponseWrapper;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-public class ResponseCookieFilter extends AbstractGatewayFilter {
-  public static final String RESTRICTED_COOKIES = "restrictedCookies";
-
-  protected static List<String> restrictedCookies = new ArrayList<String>();
-
-  @Override
-  public void init(FilterConfig filterConfig) throws ServletException {
-    super.init(filterConfig);
-    String cookies = filterConfig.getInitParameter(RESTRICTED_COOKIES);
-    if (cookies != null) {
-      restrictedCookies = Arrays.asList(cookies.split(","));
-    }
-  }
-
-  @Override
-  protected void doFilter( HttpServletRequest request, HttpServletResponse response, FilterChain chain ) throws IOException, ServletException {
-    ResponseWrapper responseWrapper = new ResponseWrapper( response );
-    chain.doFilter( request, responseWrapper );
-  }
-
-  // inner class wraps response to prevent adding of not allowed headers
-  private static class ResponseWrapper extends HttpServletResponseWrapper {
-    public ResponseWrapper( HttpServletResponse response ) {
-      super( response );
-    }
-
-    public void addCookie( Cookie cookie ) {
-      if( cookie != null && isAllowedHeader( cookie.getName() ) ) {
-        super.addCookie( cookie );
-      }
-    }
-
-    public void setHeader( String name, String value ) {
-      if( isAllowedHeader( name ) ) {
-        super.setHeader( name, value );
-      }
-    }
-
-    public void addHeader( String name, String value ) {
-      if( isAllowedHeader( name ) ) {
-        super.addHeader( name, value );
-      }
-    }
-
-    private boolean isAllowedHeader( String value ) {
-      if( value != null ) {
-        for( String v : restrictedCookies ) {
-          if( value.contains( v ) ) {
-            return false;
-          }
-        }
-      }
-      return true;
-    }
-  }
-}


[39/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilterTest.java b/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilterTest.java
deleted file mode 100644
index 8637f62..0000000
--- a/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilterTest.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.hadoop.gateway.identityasserter.switchcase;
-
-import java.security.Principal;
-import javax.security.auth.Subject;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-
-import org.apache.hadoop.gateway.security.GroupPrincipal;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
-
-public class SwitchCaseIdentityAssertionFilterTest {
-
-  @Test
-  public void testDefaultConfig() throws Exception {
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
-
-    Subject subject = new Subject();
-    subject.getPrincipals().add( new PrimaryPrincipal( "Member@us.apache.org" ) );
-    subject.getPrincipals().add( new GroupPrincipal( "users" ) );
-    subject.getPrincipals().add( new GroupPrincipal( "Admin" ) );
-
-    filter.init(config);
-    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    String[] groups = filter.mapGroupPrincipals(actual, subject);
-    assertThat( actual, is( "member@us.apache.org" ) );
-    assertThat( groups, is( arrayContainingInAnyOrder( "admin", "users" ) ) );
-
-  }
-
-  @Test
-  public void testUpperPrincipalAndGroups() throws Exception {
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "Upper" ).anyTimes();
-    EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( "Upper" ).anyTimes();
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
-
-    Subject subject = new Subject();
-    subject.getPrincipals().add( new PrimaryPrincipal( "Member@us.apache.org" ) );
-    subject.getPrincipals().add( new GroupPrincipal( "users" ) );
-    subject.getPrincipals().add( new GroupPrincipal( "Admin" ) );
-
-    filter.init(config);
-    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    String[] groups = filter.mapGroupPrincipals(actual, subject);
-    assertThat( actual, is( "MEMBER@US.APACHE.ORG" ) );
-    assertThat( groups, is( arrayContainingInAnyOrder( "ADMIN", "USERS" ) ) );
-
-  }
-
-  @Test
-  public void testLowerPrincipalAndGroups() throws Exception {
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "lower" ).anyTimes();
-    EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( "LOWER" ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
-
-    Subject subject = new Subject();
-    subject.getPrincipals().add(new PrimaryPrincipal( "Member@us.apache.org" ) );
-    subject.getPrincipals().add(new GroupPrincipal( "users" ) );
-    subject.getPrincipals().add( new GroupPrincipal( "Admin" ) );
-
-    filter.init(config);
-    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    String[] groups = filter.mapGroupPrincipals(actual, subject);
-    assertThat( actual, is( "member@us.apache.org" ) );
-    assertThat( groups, is( arrayContainingInAnyOrder( "admin", "users" ) ) );
-
-  }
-
-  @Test
-  public void testNonePrincipalAndGroups() throws Exception {
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "none" ).anyTimes();
-    EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( "NONE" ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
-
-    Subject subject = new Subject();
-    subject.getPrincipals().add(new PrimaryPrincipal( "Member@us.apache.org" ) );
-
-    filter.init(config);
-    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    String[] groups = filter.mapGroupPrincipals(actual, subject);
-    assertThat( actual, is( "Member@us.apache.org" ) );
-    assertThat( groups, is( nullValue() ) );
-
-  }
-
-  @Test
-  public void testDefaultGroupsConfFromUsers() throws Exception {
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "UPPER" ).anyTimes();
-    EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( null ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
-
-    Subject subject = new Subject();
-    subject.getPrincipals().add(new PrimaryPrincipal( "Member@us.apache.org" ) );
-    subject.getPrincipals().add(new GroupPrincipal( "users" ) );
-    subject.getPrincipals().add( new GroupPrincipal( "Admin" ) );
-
-    filter.init(config);
-    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    String[] groups = filter.mapGroupPrincipals(actual, subject);
-    assertThat( actual, is( "MEMBER@US.APACHE.ORG" ) );
-    assertThat( groups, is( arrayContainingInAnyOrder( "ADMIN", "USERS" ) ) );
-
-  }
-
-  @Test
-  public void testDefaultGroupsConfOverride() throws Exception {
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "UPPER" ).anyTimes();
-    EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( "none" ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
-
-    Subject subject = new Subject();
-    subject.getPrincipals().add(new PrimaryPrincipal( "Member@us.apache.org" ) );
-    subject.getPrincipals().add(new GroupPrincipal( "users" ) );
-    subject.getPrincipals().add( new GroupPrincipal( "Admin" ) );
-
-    filter.init(config);
-    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    String[] groups = filter.mapGroupPrincipals(actual, subject);
-    assertThat( actual, is( "MEMBER@US.APACHE.ORG" ) );
-    assertThat( groups, is( nullValue() ) );
-
-  }
-
-  @Test
-  public void testNone() throws Exception {
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "none" ).anyTimes();
-    EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( "none" ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
-
-    Subject subject = new Subject();
-    subject.getPrincipals().add(new PrimaryPrincipal( "Member@us.apache.org" ) );
-    subject.getPrincipals().add(new GroupPrincipal( "users" ) );
-    subject.getPrincipals().add( new GroupPrincipal( "Admin" ) );
-
-    filter.init(config);
-    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    String[] groups = filter.mapGroupPrincipals(actual, subject);
-    assertThat( actual, is( "Member@us.apache.org" ) );
-    assertThat( groups, is( nullValue() ) );
-
-  }
-
-  @Test
-  public void testNoGroups() throws Exception {
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "upper" ).anyTimes();
-    EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( "upper" ).anyTimes();
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
-
-    Subject subject = new Subject();
-    subject.getPrincipals().add(new PrimaryPrincipal( "Member@us.apache.org" ) );
-
-    filter.init(config);
-    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    String[] groups = filter.mapGroupPrincipals(actual, subject);
-    assertThat( actual, is( "MEMBER@US.APACHE.ORG" ) );
-    assertThat( groups, is( nullValue() ) );
-
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributorTest.java b/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributorTest.java
new file mode 100644
index 0000000..14a0600
--- /dev/null
+++ b/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributorTest.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.knox.gateway.identityasserter.switchcase;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributor;
+import org.junit.Test;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class SwitchCaseIdentityAsserterDeploymentContributorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader<ProviderDeploymentContributor> loader = ServiceLoader.load( ProviderDeploymentContributor.class );
+    Iterator<ProviderDeploymentContributor> iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof SwitchCaseIdentityAsserterDeploymentContributor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + SwitchCaseIdentityAsserterDeploymentContributor.class.getName() + " via service loader." );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilterTest.java b/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilterTest.java
new file mode 100644
index 0000000..d1a9462
--- /dev/null
+++ b/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilterTest.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.knox.gateway.identityasserter.switchcase;
+
+import java.security.Principal;
+import javax.security.auth.Subject;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+
+import org.apache.knox.gateway.security.GroupPrincipal;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
+
+public class SwitchCaseIdentityAssertionFilterTest {
+
+  @Test
+  public void testDefaultConfig() throws Exception {
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
+
+    Subject subject = new Subject();
+    subject.getPrincipals().add( new PrimaryPrincipal( "Member@us.apache.org" ) );
+    subject.getPrincipals().add( new GroupPrincipal( "users" ) );
+    subject.getPrincipals().add( new GroupPrincipal( "Admin" ) );
+
+    filter.init(config);
+    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    String[] groups = filter.mapGroupPrincipals(actual, subject);
+    assertThat( actual, is( "member@us.apache.org" ) );
+    assertThat( groups, is( arrayContainingInAnyOrder( "admin", "users" ) ) );
+
+  }
+
+  @Test
+  public void testUpperPrincipalAndGroups() throws Exception {
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "Upper" ).anyTimes();
+    EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( "Upper" ).anyTimes();
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
+
+    Subject subject = new Subject();
+    subject.getPrincipals().add( new PrimaryPrincipal( "Member@us.apache.org" ) );
+    subject.getPrincipals().add( new GroupPrincipal( "users" ) );
+    subject.getPrincipals().add( new GroupPrincipal( "Admin" ) );
+
+    filter.init(config);
+    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    String[] groups = filter.mapGroupPrincipals(actual, subject);
+    assertThat( actual, is( "MEMBER@US.APACHE.ORG" ) );
+    assertThat( groups, is( arrayContainingInAnyOrder( "ADMIN", "USERS" ) ) );
+
+  }
+
+  @Test
+  public void testLowerPrincipalAndGroups() throws Exception {
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "lower" ).anyTimes();
+    EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( "LOWER" ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
+
+    Subject subject = new Subject();
+    subject.getPrincipals().add(new PrimaryPrincipal( "Member@us.apache.org" ) );
+    subject.getPrincipals().add(new GroupPrincipal( "users" ) );
+    subject.getPrincipals().add( new GroupPrincipal( "Admin" ) );
+
+    filter.init(config);
+    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    String[] groups = filter.mapGroupPrincipals(actual, subject);
+    assertThat( actual, is( "member@us.apache.org" ) );
+    assertThat( groups, is( arrayContainingInAnyOrder( "admin", "users" ) ) );
+
+  }
+
+  @Test
+  public void testNonePrincipalAndGroups() throws Exception {
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "none" ).anyTimes();
+    EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( "NONE" ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
+
+    Subject subject = new Subject();
+    subject.getPrincipals().add(new PrimaryPrincipal( "Member@us.apache.org" ) );
+
+    filter.init(config);
+    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    String[] groups = filter.mapGroupPrincipals(actual, subject);
+    assertThat( actual, is( "Member@us.apache.org" ) );
+    assertThat( groups, is( nullValue() ) );
+
+  }
+
+  @Test
+  public void testDefaultGroupsConfFromUsers() throws Exception {
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "UPPER" ).anyTimes();
+    EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( null ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
+
+    Subject subject = new Subject();
+    subject.getPrincipals().add(new PrimaryPrincipal( "Member@us.apache.org" ) );
+    subject.getPrincipals().add(new GroupPrincipal( "users" ) );
+    subject.getPrincipals().add( new GroupPrincipal( "Admin" ) );
+
+    filter.init(config);
+    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    String[] groups = filter.mapGroupPrincipals(actual, subject);
+    assertThat( actual, is( "MEMBER@US.APACHE.ORG" ) );
+    assertThat( groups, is( arrayContainingInAnyOrder( "ADMIN", "USERS" ) ) );
+
+  }
+
+  @Test
+  public void testDefaultGroupsConfOverride() throws Exception {
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "UPPER" ).anyTimes();
+    EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( "none" ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
+
+    Subject subject = new Subject();
+    subject.getPrincipals().add(new PrimaryPrincipal( "Member@us.apache.org" ) );
+    subject.getPrincipals().add(new GroupPrincipal( "users" ) );
+    subject.getPrincipals().add( new GroupPrincipal( "Admin" ) );
+
+    filter.init(config);
+    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    String[] groups = filter.mapGroupPrincipals(actual, subject);
+    assertThat( actual, is( "MEMBER@US.APACHE.ORG" ) );
+    assertThat( groups, is( nullValue() ) );
+
+  }
+
+  @Test
+  public void testNone() throws Exception {
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "none" ).anyTimes();
+    EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( "none" ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
+
+    Subject subject = new Subject();
+    subject.getPrincipals().add(new PrimaryPrincipal( "Member@us.apache.org" ) );
+    subject.getPrincipals().add(new GroupPrincipal( "users" ) );
+    subject.getPrincipals().add( new GroupPrincipal( "Admin" ) );
+
+    filter.init(config);
+    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    String[] groups = filter.mapGroupPrincipals(actual, subject);
+    assertThat( actual, is( "Member@us.apache.org" ) );
+    assertThat( groups, is( nullValue() ) );
+
+  }
+
+  @Test
+  public void testNoGroups() throws Exception {
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "upper" ).anyTimes();
+    EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( "upper" ).anyTimes();
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter();
+
+    Subject subject = new Subject();
+    subject.getPrincipals().add(new PrimaryPrincipal( "Member@us.apache.org" ) );
+
+    filter.init(config);
+    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    String[] groups = filter.mapGroupPrincipals(actual, subject);
+    assertThat( actual, is( "MEMBER@US.APACHE.ORG" ) );
+    assertThat( groups, is( nullValue() ) );
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-jersey/src/main/java/org/apache/hadoop/gateway/jersey/JerseyDispatchDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-jersey/src/main/java/org/apache/hadoop/gateway/jersey/JerseyDispatchDeploymentContributor.java b/gateway-provider-jersey/src/main/java/org/apache/hadoop/gateway/jersey/JerseyDispatchDeploymentContributor.java
deleted file mode 100644
index 1f40fd7..0000000
--- a/gateway-provider-jersey/src/main/java/org/apache/hadoop/gateway/jersey/JerseyDispatchDeploymentContributor.java
+++ /dev/null
@@ -1,55 +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.hadoop.gateway.jersey;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterDescriptor;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-import org.glassfish.jersey.servlet.ServletContainer;
-
-import java.util.List;
-
-public class JerseyDispatchDeploymentContributor extends ProviderDeploymentContributorBase {
-
-  private static final String FILTER_CLASS_NAME = ServletContainer.class.getName();
-
-  @Override
-  public String getRole() {
-    return "pivot";
-  }
-
-  @Override
-  public String getName() {
-    return "jersey";
-  }
-
-  @Override
-  public void contributeFilter( DeploymentContext context, Provider provider, Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
-    FilterDescriptor filter = resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASS_NAME );
-    if( params != null ) {
-      for( FilterParamDescriptor param : params ) {
-        filter.param().name( param.name() ).value( param.value() );
-      }
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-jersey/src/main/java/org/apache/hadoop/gateway/jersey/JerseyServiceDeploymentContributorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-jersey/src/main/java/org/apache/hadoop/gateway/jersey/JerseyServiceDeploymentContributorBase.java b/gateway-provider-jersey/src/main/java/org/apache/hadoop/gateway/jersey/JerseyServiceDeploymentContributorBase.java
deleted file mode 100644
index 99c5d4b..0000000
--- a/gateway-provider-jersey/src/main/java/org/apache/hadoop/gateway/jersey/JerseyServiceDeploymentContributorBase.java
+++ /dev/null
@@ -1,67 +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.hadoop.gateway.jersey;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ServiceDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.topology.Service;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-public abstract class JerseyServiceDeploymentContributorBase extends ServiceDeploymentContributorBase {
-
-  private static final String PACKAGES_PARAM = "jersey.config.server.provider.packages";
-//  private static final String TRACE_LOGGING_PARAM = "jersey.config.server.tracing";
-
-  protected abstract String[] getPackages();
-
-  protected abstract String[] getPatterns();
-
-  public void contributeService( DeploymentContext context, Service service ) throws Exception {
-    String packages = StringUtils.join( getPackages(), ";" );
-    for( String pattern : getPatterns() ) {
-      ResourceDescriptor resource = context.getGatewayDescriptor().addResource();
-      resource.role( service.getRole() );
-      resource.pattern( pattern );
-      addWebAppSecFilters( context, service, resource );
-      addXForwardedFilter( context, service, resource );
-      addAuthenticationFilter( context, service, resource );
-      addIdentityAssertionFilter( context, service, resource );
-      addAuthorizationFilter( context, service, resource );
-      // addRewriteFilter( context, service, resource, null );
-      List<FilterParamDescriptor> params = new ArrayList<FilterParamDescriptor>();
-      FilterParamDescriptor param = resource.createFilterParam();
-      param.name( PACKAGES_PARAM );
-      param.value( packages );
-      params.add( param );
-//      FilterParamDescriptor trace = resource.createFilterParam();
-//      param.name( TRACE_LOGGING_PARAM );
-//      param.value( "ALL" );
-//      params.add( trace );
-      for ( Map.Entry<String,String> serviceParam : service.getParams().entrySet() ) {
-        context.getWebAppDescriptor().createContextParam().paramName(serviceParam.getKey()).paramValue(serviceParam.getValue());
-      }
-      context.contributeFilter( service, resource, "pivot", "jersey", params );
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-jersey/src/main/java/org/apache/knox/gateway/jersey/JerseyDispatchDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-jersey/src/main/java/org/apache/knox/gateway/jersey/JerseyDispatchDeploymentContributor.java b/gateway-provider-jersey/src/main/java/org/apache/knox/gateway/jersey/JerseyDispatchDeploymentContributor.java
new file mode 100644
index 0000000..19debc9
--- /dev/null
+++ b/gateway-provider-jersey/src/main/java/org/apache/knox/gateway/jersey/JerseyDispatchDeploymentContributor.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.knox.gateway.jersey;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterDescriptor;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+import org.glassfish.jersey.servlet.ServletContainer;
+
+import java.util.List;
+
+public class JerseyDispatchDeploymentContributor extends
+    ProviderDeploymentContributorBase {
+
+  private static final String FILTER_CLASS_NAME = ServletContainer.class.getName();
+
+  @Override
+  public String getRole() {
+    return "pivot";
+  }
+
+  @Override
+  public String getName() {
+    return "jersey";
+  }
+
+  @Override
+  public void contributeFilter( DeploymentContext context, Provider provider, Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
+    FilterDescriptor filter = resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASS_NAME );
+    if( params != null ) {
+      for( FilterParamDescriptor param : params ) {
+        filter.param().name( param.name() ).value( param.value() );
+      }
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-jersey/src/main/java/org/apache/knox/gateway/jersey/JerseyServiceDeploymentContributorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-jersey/src/main/java/org/apache/knox/gateway/jersey/JerseyServiceDeploymentContributorBase.java b/gateway-provider-jersey/src/main/java/org/apache/knox/gateway/jersey/JerseyServiceDeploymentContributorBase.java
new file mode 100644
index 0000000..95a372a
--- /dev/null
+++ b/gateway-provider-jersey/src/main/java/org/apache/knox/gateway/jersey/JerseyServiceDeploymentContributorBase.java
@@ -0,0 +1,67 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.jersey;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ServiceDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+public abstract class JerseyServiceDeploymentContributorBase extends ServiceDeploymentContributorBase {
+
+  private static final String PACKAGES_PARAM = "jersey.config.server.provider.packages";
+//  private static final String TRACE_LOGGING_PARAM = "jersey.config.server.tracing";
+
+  protected abstract String[] getPackages();
+
+  protected abstract String[] getPatterns();
+
+  public void contributeService( DeploymentContext context, Service service ) throws Exception {
+    String packages = StringUtils.join( getPackages(), ";" );
+    for( String pattern : getPatterns() ) {
+      ResourceDescriptor resource = context.getGatewayDescriptor().addResource();
+      resource.role( service.getRole() );
+      resource.pattern( pattern );
+      addWebAppSecFilters( context, service, resource );
+      addXForwardedFilter( context, service, resource );
+      addAuthenticationFilter( context, service, resource );
+      addIdentityAssertionFilter( context, service, resource );
+      addAuthorizationFilter( context, service, resource );
+      // addRewriteFilter( context, service, resource, null );
+      List<FilterParamDescriptor> params = new ArrayList<FilterParamDescriptor>();
+      FilterParamDescriptor param = resource.createFilterParam();
+      param.name( PACKAGES_PARAM );
+      param.value( packages );
+      params.add( param );
+//      FilterParamDescriptor trace = resource.createFilterParam();
+//      param.name( TRACE_LOGGING_PARAM );
+//      param.value( "ALL" );
+//      params.add( trace );
+      for ( Map.Entry<String,String> serviceParam : service.getParams().entrySet() ) {
+        context.getWebAppDescriptor().createContextParam().paramName(serviceParam.getKey()).paramValue(serviceParam.getValue());
+      }
+      context.contributeFilter( service, resource, "pivot", "jersey", params );
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-jersey/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-jersey/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-jersey/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index 70af7b4..0000000
--- a/gateway-provider-jersey/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.jersey.JerseyDispatchDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-jersey/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-jersey/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-jersey/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..27a190a
--- /dev/null
+++ b/gateway-provider-jersey/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.jersey.JerseyDispatchDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-jersey/src/test/java/org/apache/hadoop/gateway/jersey/JerseyDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-jersey/src/test/java/org/apache/hadoop/gateway/jersey/JerseyDeploymentContributorTest.java b/gateway-provider-jersey/src/test/java/org/apache/hadoop/gateway/jersey/JerseyDeploymentContributorTest.java
deleted file mode 100644
index 0721ddc..0000000
--- a/gateway-provider-jersey/src/test/java/org/apache/hadoop/gateway/jersey/JerseyDeploymentContributorTest.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.hadoop.gateway.jersey;
-
-import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor;
-import org.apache.hadoop.gateway.descriptor.FilterDescriptor;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.GatewayDescriptor;
-import org.apache.hadoop.gateway.descriptor.GatewayDescriptorFactory;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-import org.apache.hadoop.gateway.topology.Topology;
-import org.easymock.EasyMock;
-import org.jboss.shrinkwrap.api.ShrinkWrap;
-import org.jboss.shrinkwrap.api.spec.WebArchive;
-import org.jboss.shrinkwrap.descriptor.api.webapp30.WebAppDescriptor;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.List;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class JerseyDeploymentContributorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( ProviderDeploymentContributor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof JerseyDispatchDeploymentContributor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + JerseyDispatchDeploymentContributor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testDeploymentContributors() throws Exception {
-    JerseyDispatchDeploymentContributor providerContributor = new JerseyDispatchDeploymentContributor();
-    assertThat( providerContributor.getRole(), is( "pivot" ) );
-    assertThat( providerContributor.getName(), is( "jersey" ) );
-
-    MockJerseyService serviceContributor = new MockJerseyService();
-
-    WebArchive webArchive = ShrinkWrap.create( WebArchive.class, "test-archive" );
-
-    Topology topology = new Topology();
-    topology.setName( "test-topology" );
-    Provider provider = new Provider();
-    provider.setRole( "pivot" );
-    provider.setName( "jersey" );
-    provider.setEnabled( true );
-    topology.addProvider( provider );
-
-    GatewayDescriptor descriptor = GatewayDescriptorFactory.create();
-
-    DeploymentContext context = EasyMock.createNiceMock( DeploymentContext.class );
-    EasyMock.expect( context.getWebArchive() ).andReturn( webArchive ).anyTimes();
-    EasyMock.expect( context.getTopology() ).andReturn( topology ).anyTimes();
-    EasyMock.expect( context.getGatewayDescriptor() ).andReturn( descriptor ).anyTimes();
-    context.contributeFilter(
-        EasyMock.<Service> isA( Service.class ),
-        EasyMock.<ResourceDescriptor> isA( ResourceDescriptor.class ),
-        EasyMock.<String> isA( String.class ),
-        EasyMock.<String> isA( String.class ),
-        EasyMock.<List> isA( List.class ) );
-    EasyMock.expectLastCall().andDelegateTo(
-        new MockDeploymentContext( context, providerContributor, provider ) ).anyTimes();
-
-    EasyMock.replay( context );
-
-    // Just make sure they don't blow up.
-    providerContributor.initializeContribution( context );
-    serviceContributor.initializeContribution( context );
-
-    Service service = new Service();
-    service.setRole( "test-service-role" );
-    service.setName( "test-service-name" );
-    service.addUrl( "http://test-service-host:777/test-service-path" );
-
-    // This should end up calling providerContributor.contributeFilter
-    serviceContributor.contributeService( context, service );
-    ResourceDescriptor resource = context.getGatewayDescriptor().resources().get( 0 );
-
-    // Just make sure they don't blow up.
-    serviceContributor.finalizeContribution( context );
-    providerContributor.finalizeContribution( context );
-
-    /*
-    GatewayDescriptorFactory.store( descriptor, "xml", new PrintWriter( System.out ) );
-    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-    <gateway>
-      <resource>
-        <role>test-service-role</role>
-        <pattern>test-service/?**</pattern>
-        <filter>
-          <role>dispatch</role>
-          <name>jersey</name>
-          <class>org.glassfish.jersey.servlet.ServletContainer</class>
-          <param>
-            <name>jersey.config.server.provider.packages</name>
-            <value>test-package-1;test-package-2</value>
-          </param>
-        </filter>
-      </resource>
-      <resource>
-        <role>test-service-role</role>
-        <pattern>test-service/**?**</pattern>
-        <filter>
-          <role>dispatch</role>
-          <name>jersey</name>
-          <class>org.glassfish.jersey.servlet.ServletContainer</class>
-          <param>
-            <name>jersey.config.server.provider.packages</name>
-            <value>test-package-1;test-package-2</value>
-          </param>
-        </filter>
-      </resource>
-    </gateway>
-    */
-    List<ResourceDescriptor> resources = context.getGatewayDescriptor().resources();
-    assertThat( resources.size(), is( 2 ) );
-
-    resource = resources.get( 0 );
-    assertThat( resource.role(), is( "test-service-role" ) );
-    assertThat( resource.pattern(), is( "test-service/?**" ) );
-    List<FilterDescriptor> filters = resource.filters();
-    assertThat( filters.size(), is( 1 ) );
-    FilterDescriptor filter = filters.get( 0 );
-    assertThat( filter.role(), is( "pivot") );
-    assertThat( filter.name(), is( "jersey" ) );
-    assertThat( filter.impl(), is( "org.glassfish.jersey.servlet.ServletContainer" ) );
-    List<FilterParamDescriptor> params = filter.params();
-    assertThat( params.size(), is( 1 ) );
-    FilterParamDescriptor param = params.get( 0 );
-    assertThat( param.name(), is( "jersey.config.server.provider.packages" ) );
-    assertThat( param.value(), is( "test-package-1;test-package-2"  ) );
-
-    resource = resources.get( 1 );
-    assertThat( resource.role(), is( "test-service-role" ) );
-    assertThat( resource.pattern(), is( "test-service/**?**" ) );
-    filters = resource.filters();
-    assertThat( filters.size(), is( 1 ) );
-    filter = filters.get( 0 );
-    assertThat( filter.role(), is( "pivot") );
-    assertThat( filter.name(), is( "jersey" ) );
-    assertThat( filter.impl(), is( "org.glassfish.jersey.servlet.ServletContainer" ) );
-    params = filter.params();
-    assertThat( params.size(), is( 1 ) );
-    param = params.get( 0 );
-    assertThat( param.name(), is( "jersey.config.server.provider.packages" ) );
-    assertThat( param.value(), is( "test-package-1;test-package-2"  ) );
-  }
-
-  private static class MockJerseyService extends JerseyServiceDeploymentContributorBase {
-
-    @Override
-    protected String[] getPatterns() {
-      return new String[]{ "test-service/?**", "test-service/**?**" };
-    }
-
-    @Override
-    protected String[] getPackages() {
-      return new String[]{ "test-package-1", "test-package-2" };
-    }
-
-    @Override
-    public String getRole() {
-      return "test-service-role";
-    }
-
-    @Override
-    public String getName() {
-      return "test-service-name";
-    }
-
-  }
-
-  private static class MockDeploymentContext implements DeploymentContext {
-
-    DeploymentContext context;
-    ProviderDeploymentContributor providerContributor;
-    Provider provider;
-
-    public MockDeploymentContext(
-        DeploymentContext context,
-        ProviderDeploymentContributor providerContributor,
-        Provider provider ) {
-      this.context = context;
-      this.providerContributor = providerContributor;
-      this.provider = provider;
-    }
-
-    @Override
-    public GatewayConfig getGatewayConfig() {
-      return null;
-    }
-
-    @Override
-    public Topology getTopology() {
-      return null;
-    }
-
-    @Override
-    public WebArchive getWebArchive() {
-      return null;
-    }
-
-    @Override
-    public WebAppDescriptor getWebAppDescriptor() {
-      return null;
-    }
-
-    @Override
-    public GatewayDescriptor getGatewayDescriptor() {
-      return null;
-    }
-
-    @Override
-    public void contributeFilter( Service service, ResourceDescriptor resource, String role, String name, List<FilterParamDescriptor> params ) {
-      providerContributor.contributeFilter( context, provider, service, resource, params );
-    }
-
-    @Override
-    public void addDescriptor( String name, Object descriptor ) {
-    }
-
-    @Override
-    public <T> T getDescriptor( String name ) {
-      return null;
-    }
-
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-jersey/src/test/java/org/apache/knox/gateway/jersey/JerseyDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-jersey/src/test/java/org/apache/knox/gateway/jersey/JerseyDeploymentContributorTest.java b/gateway-provider-jersey/src/test/java/org/apache/knox/gateway/jersey/JerseyDeploymentContributorTest.java
new file mode 100644
index 0000000..3f48e36
--- /dev/null
+++ b/gateway-provider-jersey/src/test/java/org/apache/knox/gateway/jersey/JerseyDeploymentContributorTest.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.knox.gateway.jersey;
+
+import org.apache.knox.gateway.config.GatewayConfig;
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributor;
+import org.apache.knox.gateway.descriptor.FilterDescriptor;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.GatewayDescriptor;
+import org.apache.knox.gateway.descriptor.GatewayDescriptorFactory;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+import org.apache.knox.gateway.topology.Topology;
+import org.easymock.EasyMock;
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.spec.WebArchive;
+import org.jboss.shrinkwrap.descriptor.api.webapp30.WebAppDescriptor;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class JerseyDeploymentContributorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( ProviderDeploymentContributor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof JerseyDispatchDeploymentContributor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + JerseyDispatchDeploymentContributor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testDeploymentContributors() throws Exception {
+    JerseyDispatchDeploymentContributor providerContributor = new JerseyDispatchDeploymentContributor();
+    assertThat( providerContributor.getRole(), is( "pivot" ) );
+    assertThat( providerContributor.getName(), is( "jersey" ) );
+
+    MockJerseyService serviceContributor = new MockJerseyService();
+
+    WebArchive webArchive = ShrinkWrap.create( WebArchive.class, "test-archive" );
+
+    Topology topology = new Topology();
+    topology.setName( "test-topology" );
+    Provider provider = new Provider();
+    provider.setRole( "pivot" );
+    provider.setName( "jersey" );
+    provider.setEnabled( true );
+    topology.addProvider( provider );
+
+    GatewayDescriptor descriptor = GatewayDescriptorFactory.create();
+
+    DeploymentContext context = EasyMock.createNiceMock( DeploymentContext.class );
+    EasyMock.expect( context.getWebArchive() ).andReturn( webArchive ).anyTimes();
+    EasyMock.expect( context.getTopology() ).andReturn( topology ).anyTimes();
+    EasyMock.expect( context.getGatewayDescriptor() ).andReturn( descriptor ).anyTimes();
+    context.contributeFilter(
+        EasyMock.<Service> isA( Service.class ),
+        EasyMock.<ResourceDescriptor> isA( ResourceDescriptor.class ),
+        EasyMock.<String> isA( String.class ),
+        EasyMock.<String> isA( String.class ),
+        EasyMock.<List> isA( List.class ) );
+    EasyMock.expectLastCall().andDelegateTo(
+        new MockDeploymentContext( context, providerContributor, provider ) ).anyTimes();
+
+    EasyMock.replay( context );
+
+    // Just make sure they don't blow up.
+    providerContributor.initializeContribution( context );
+    serviceContributor.initializeContribution( context );
+
+    Service service = new Service();
+    service.setRole( "test-service-role" );
+    service.setName( "test-service-name" );
+    service.addUrl( "http://test-service-host:777/test-service-path" );
+
+    // This should end up calling providerContributor.contributeFilter
+    serviceContributor.contributeService( context, service );
+    ResourceDescriptor resource = context.getGatewayDescriptor().resources().get( 0 );
+
+    // Just make sure they don't blow up.
+    serviceContributor.finalizeContribution( context );
+    providerContributor.finalizeContribution( context );
+
+    /*
+    GatewayDescriptorFactory.store( descriptor, "xml", new PrintWriter( System.out ) );
+    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+    <gateway>
+      <resource>
+        <role>test-service-role</role>
+        <pattern>test-service/?**</pattern>
+        <filter>
+          <role>dispatch</role>
+          <name>jersey</name>
+          <class>org.glassfish.jersey.servlet.ServletContainer</class>
+          <param>
+            <name>jersey.config.server.provider.packages</name>
+            <value>test-package-1;test-package-2</value>
+          </param>
+        </filter>
+      </resource>
+      <resource>
+        <role>test-service-role</role>
+        <pattern>test-service/**?**</pattern>
+        <filter>
+          <role>dispatch</role>
+          <name>jersey</name>
+          <class>org.glassfish.jersey.servlet.ServletContainer</class>
+          <param>
+            <name>jersey.config.server.provider.packages</name>
+            <value>test-package-1;test-package-2</value>
+          </param>
+        </filter>
+      </resource>
+    </gateway>
+    */
+    List<ResourceDescriptor> resources = context.getGatewayDescriptor().resources();
+    assertThat( resources.size(), is( 2 ) );
+
+    resource = resources.get( 0 );
+    assertThat( resource.role(), is( "test-service-role" ) );
+    assertThat( resource.pattern(), is( "test-service/?**" ) );
+    List<FilterDescriptor> filters = resource.filters();
+    assertThat( filters.size(), is( 1 ) );
+    FilterDescriptor filter = filters.get( 0 );
+    assertThat( filter.role(), is( "pivot") );
+    assertThat( filter.name(), is( "jersey" ) );
+    assertThat( filter.impl(), is( "org.glassfish.jersey.servlet.ServletContainer" ) );
+    List<FilterParamDescriptor> params = filter.params();
+    assertThat( params.size(), is( 1 ) );
+    FilterParamDescriptor param = params.get( 0 );
+    assertThat( param.name(), is( "jersey.config.server.provider.packages" ) );
+    assertThat( param.value(), is( "test-package-1;test-package-2"  ) );
+
+    resource = resources.get( 1 );
+    assertThat( resource.role(), is( "test-service-role" ) );
+    assertThat( resource.pattern(), is( "test-service/**?**" ) );
+    filters = resource.filters();
+    assertThat( filters.size(), is( 1 ) );
+    filter = filters.get( 0 );
+    assertThat( filter.role(), is( "pivot") );
+    assertThat( filter.name(), is( "jersey" ) );
+    assertThat( filter.impl(), is( "org.glassfish.jersey.servlet.ServletContainer" ) );
+    params = filter.params();
+    assertThat( params.size(), is( 1 ) );
+    param = params.get( 0 );
+    assertThat( param.name(), is( "jersey.config.server.provider.packages" ) );
+    assertThat( param.value(), is( "test-package-1;test-package-2"  ) );
+  }
+
+  private static class MockJerseyService extends JerseyServiceDeploymentContributorBase {
+
+    @Override
+    protected String[] getPatterns() {
+      return new String[]{ "test-service/?**", "test-service/**?**" };
+    }
+
+    @Override
+    protected String[] getPackages() {
+      return new String[]{ "test-package-1", "test-package-2" };
+    }
+
+    @Override
+    public String getRole() {
+      return "test-service-role";
+    }
+
+    @Override
+    public String getName() {
+      return "test-service-name";
+    }
+
+  }
+
+  private static class MockDeploymentContext implements DeploymentContext {
+
+    DeploymentContext context;
+    ProviderDeploymentContributor providerContributor;
+    Provider provider;
+
+    public MockDeploymentContext(
+        DeploymentContext context,
+        ProviderDeploymentContributor providerContributor,
+        Provider provider ) {
+      this.context = context;
+      this.providerContributor = providerContributor;
+      this.provider = provider;
+    }
+
+    @Override
+    public GatewayConfig getGatewayConfig() {
+      return null;
+    }
+
+    @Override
+    public Topology getTopology() {
+      return null;
+    }
+
+    @Override
+    public WebArchive getWebArchive() {
+      return null;
+    }
+
+    @Override
+    public WebAppDescriptor getWebAppDescriptor() {
+      return null;
+    }
+
+    @Override
+    public GatewayDescriptor getGatewayDescriptor() {
+      return null;
+    }
+
+    @Override
+    public void contributeFilter( Service service, ResourceDescriptor resource, String role, String name, List<FilterParamDescriptor> params ) {
+      providerContributor.contributeFilter( context, provider, service, resource, params );
+    }
+
+    @Override
+    public void addDescriptor( String name, Object descriptor ) {
+    }
+
+    @Override
+    public <T> T getDescriptor( String name ) {
+      return null;
+    }
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/hadoop/gateway/hostmap/api/HostmapFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/hadoop/gateway/hostmap/api/HostmapFunctionDescriptor.java b/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/hadoop/gateway/hostmap/api/HostmapFunctionDescriptor.java
deleted file mode 100644
index 01d41b9..0000000
--- a/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/hadoop/gateway/hostmap/api/HostmapFunctionDescriptor.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.hadoop.gateway.hostmap.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-public class HostmapFunctionDescriptor implements UrlRewriteFunctionDescriptor<HostmapFunctionDescriptor> {
-
-  public static final String FUNCTION_NAME = "hostmap";
-
-  private String configLocation;
-
-  @Override
-  public String name() {
-    return FUNCTION_NAME;
-  }
-
-  public HostmapFunctionDescriptor config( String configLocation ) {
-    this.configLocation = configLocation;
-    return this;
-  }
-
-  public String config() {
-    return configLocation;
-  }
-
-  public String getConfig() {
-    return config();
-  }
-
-  public void setConfig( String configLocation ) {
-    config( configLocation );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/hadoop/gateway/hostmap/impl/HostmapDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/hadoop/gateway/hostmap/impl/HostmapDeploymentContributor.java b/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/hadoop/gateway/hostmap/impl/HostmapDeploymentContributor.java
deleted file mode 100644
index fdd0b03..0000000
--- a/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/hadoop/gateway/hostmap/impl/HostmapDeploymentContributor.java
+++ /dev/null
@@ -1,99 +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.hadoop.gateway.hostmap.impl;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
-import org.apache.hadoop.gateway.hostmap.api.HostmapFunctionDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-import org.jboss.shrinkwrap.api.asset.Asset;
-import org.jboss.shrinkwrap.api.asset.StringAsset;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.List;
-import java.util.Map;
-
-public class HostmapDeploymentContributor
-    extends ProviderDeploymentContributorBase
-    implements ProviderDeploymentContributor {
-
-  public static final String PROVIDER_ROLE_NAME = HostmapFunctionDescriptor.FUNCTION_NAME;
-  public static final String PROVIDER_IMPL_NAME = "static";
-  private static final String REWRITE_ROLE_NAME = "rewrite";
-
-  @Override
-  public String getRole() {
-    return PROVIDER_ROLE_NAME;
-  }
-
-  @Override
-  public String getName() {
-    return PROVIDER_IMPL_NAME;
-  }
-
-  // Write the provider init params to the hostmap.txt file.
-  // Add the function to the rewrite descriptor providing the location of the hostmap.txt file.
-  @Override
-  public void contributeProvider( DeploymentContext context, Provider provider ) {
-    if( provider.isEnabled() ) {
-      UrlRewriteRulesDescriptor rules = context.getDescriptor( REWRITE_ROLE_NAME );
-      if( rules != null ) {
-        HostmapFunctionDescriptor func = rules.addFunction( HostmapFunctionDescriptor.FUNCTION_NAME );
-        if( func != null ) {
-          Asset asset = createAsset( provider );
-          context.getWebArchive().addAsWebInfResource(
-              asset, HostmapFunctionProcessor.DESCRIPTOR_DEFAULT_FILE_NAME );
-          func.config( HostmapFunctionProcessor.DESCRIPTOR_DEFAULT_LOCATION );
-        }
-      }
-    }
-  }
-
-  private Asset createAsset( Provider provider ) {
-    StringWriter buffer = new StringWriter();
-    PrintWriter writer = new PrintWriter( buffer );
-    for( Map.Entry<String, String> entry : provider.getParams().entrySet() ) {
-      String externalHosts = entry.getKey();
-      String internalHosts = entry.getValue();
-      writer.print( externalHosts );
-      writer.print( "=" );
-      writer.println( internalHosts );
-    }
-    writer.close();
-    String string = buffer.toString();
-    Asset asset = new StringAsset( string );
-    return asset;
-  }
-
-  @Override
-  public void contributeFilter(
-      DeploymentContext context,
-      Provider provider,
-      Service service,
-      ResourceDescriptor resource,
-      List<FilterParamDescriptor> params ) {
-    // NoOp.
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessor.java b/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessor.java
deleted file mode 100644
index ca55c16..0000000
--- a/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessor.java
+++ /dev/null
@@ -1,91 +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.hadoop.gateway.hostmap.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.hostmap.api.HostmapFunctionDescriptor;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.hostmap.FileBasedHostMapper;
-import org.apache.hadoop.gateway.services.hostmap.HostMapper;
-import org.apache.hadoop.gateway.services.hostmap.HostMapperService;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-
-public class HostmapFunctionProcessor
-    implements UrlRewriteFunctionProcessor<HostmapFunctionDescriptor> {
-
-  public static final String DESCRIPTOR_DEFAULT_FILE_NAME = "hostmap.txt";
-  public static final String DESCRIPTOR_DEFAULT_LOCATION = "/WEB-INF/" + DESCRIPTOR_DEFAULT_FILE_NAME;
-
-  private HostMapperService hostMapperService;
-  private HostMapper hostMapper = null;
-  private String clusterName;
-
-  @Override
-  public String name() {
-    return HostmapFunctionDescriptor.FUNCTION_NAME;
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, HostmapFunctionDescriptor descriptor ) throws Exception {
-    URL url = environment.getResource( DESCRIPTOR_DEFAULT_LOCATION );
-    hostMapper = new FileBasedHostMapper( url );
-    clusterName = environment.getAttribute(  GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE );
-    GatewayServices services = environment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE );
-    if( clusterName != null && services != null ) {
-      hostMapperService = services.getService( GatewayServices.HOST_MAPPING_SERVICE );
-      if( hostMapperService != null ) {
-        hostMapperService.registerHostMapperForCluster( clusterName, hostMapper );
-      }
-    }
-  }
-
-  @Override
-  public void destroy() throws Exception {
-    if( hostMapperService != null && clusterName != null ) {
-      hostMapperService.removeHostMapperForCluster( clusterName );
-    }
-  }
-
-  @Override
-  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
-    List<String> result = null;
-    if( parameters != null ) {
-      result = new ArrayList<String>( parameters.size() );
-      for( String parameter : parameters ) {
-        switch( context.getDirection() ) {
-          case IN:
-            parameter = hostMapper.resolveInboundHostName( parameter );
-            break;
-          case OUT:
-            parameter = hostMapper.resolveOutboundHostName( parameter );
-            break;
-        }
-        result.add( parameter );
-      }
-//    System.out.println( "HOSTMAP: " + parameter + "->" + value );
-    }
-    return result;
-  }
-
-}
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/api/HostmapFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/api/HostmapFunctionDescriptor.java b/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/api/HostmapFunctionDescriptor.java
new file mode 100644
index 0000000..1071bc6
--- /dev/null
+++ b/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/api/HostmapFunctionDescriptor.java
@@ -0,0 +1,51 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.hostmap.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+public class HostmapFunctionDescriptor implements
+    UrlRewriteFunctionDescriptor<HostmapFunctionDescriptor> {
+
+  public static final String FUNCTION_NAME = "hostmap";
+
+  private String configLocation;
+
+  @Override
+  public String name() {
+    return FUNCTION_NAME;
+  }
+
+  public HostmapFunctionDescriptor config( String configLocation ) {
+    this.configLocation = configLocation;
+    return this;
+  }
+
+  public String config() {
+    return configLocation;
+  }
+
+  public String getConfig() {
+    return config();
+  }
+
+  public void setConfig( String configLocation ) {
+    config( configLocation );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/impl/HostmapDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/impl/HostmapDeploymentContributor.java b/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/impl/HostmapDeploymentContributor.java
new file mode 100644
index 0000000..d39090e
--- /dev/null
+++ b/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/impl/HostmapDeploymentContributor.java
@@ -0,0 +1,99 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.hostmap.impl;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributor;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+import org.apache.knox.gateway.hostmap.api.HostmapFunctionDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+import org.jboss.shrinkwrap.api.asset.Asset;
+import org.jboss.shrinkwrap.api.asset.StringAsset;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.List;
+import java.util.Map;
+
+public class HostmapDeploymentContributor
+    extends ProviderDeploymentContributorBase
+    implements ProviderDeploymentContributor {
+
+  public static final String PROVIDER_ROLE_NAME = HostmapFunctionDescriptor.FUNCTION_NAME;
+  public static final String PROVIDER_IMPL_NAME = "static";
+  private static final String REWRITE_ROLE_NAME = "rewrite";
+
+  @Override
+  public String getRole() {
+    return PROVIDER_ROLE_NAME;
+  }
+
+  @Override
+  public String getName() {
+    return PROVIDER_IMPL_NAME;
+  }
+
+  // Write the provider init params to the hostmap.txt file.
+  // Add the function to the rewrite descriptor providing the location of the hostmap.txt file.
+  @Override
+  public void contributeProvider( DeploymentContext context, Provider provider ) {
+    if( provider.isEnabled() ) {
+      UrlRewriteRulesDescriptor rules = context.getDescriptor( REWRITE_ROLE_NAME );
+      if( rules != null ) {
+        HostmapFunctionDescriptor func = rules.addFunction( HostmapFunctionDescriptor.FUNCTION_NAME );
+        if( func != null ) {
+          Asset asset = createAsset( provider );
+          context.getWebArchive().addAsWebInfResource(
+              asset, HostmapFunctionProcessor.DESCRIPTOR_DEFAULT_FILE_NAME );
+          func.config( HostmapFunctionProcessor.DESCRIPTOR_DEFAULT_LOCATION );
+        }
+      }
+    }
+  }
+
+  private Asset createAsset( Provider provider ) {
+    StringWriter buffer = new StringWriter();
+    PrintWriter writer = new PrintWriter( buffer );
+    for( Map.Entry<String, String> entry : provider.getParams().entrySet() ) {
+      String externalHosts = entry.getKey();
+      String internalHosts = entry.getValue();
+      writer.print( externalHosts );
+      writer.print( "=" );
+      writer.println( internalHosts );
+    }
+    writer.close();
+    String string = buffer.toString();
+    Asset asset = new StringAsset( string );
+    return asset;
+  }
+
+  @Override
+  public void contributeFilter(
+      DeploymentContext context,
+      Provider provider,
+      Service service,
+      ResourceDescriptor resource,
+      List<FilterParamDescriptor> params ) {
+    // NoOp.
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessor.java b/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessor.java
new file mode 100644
index 0000000..5b16b47
--- /dev/null
+++ b/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessor.java
@@ -0,0 +1,92 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.hostmap.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.hostmap.api.HostmapFunctionDescriptor;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.hostmap.FileBasedHostMapper;
+import org.apache.knox.gateway.services.hostmap.HostMapper;
+import org.apache.knox.gateway.services.hostmap.HostMapperService;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+
+public class HostmapFunctionProcessor
+    implements UrlRewriteFunctionProcessor<HostmapFunctionDescriptor> {
+
+  public static final String DESCRIPTOR_DEFAULT_FILE_NAME = "hostmap.txt";
+  public static final String DESCRIPTOR_DEFAULT_LOCATION = "/WEB-INF/" + DESCRIPTOR_DEFAULT_FILE_NAME;
+
+  private HostMapperService hostMapperService;
+  private HostMapper hostMapper = null;
+  private String clusterName;
+
+  @Override
+  public String name() {
+    return HostmapFunctionDescriptor.FUNCTION_NAME;
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, HostmapFunctionDescriptor descriptor ) throws Exception {
+    URL url = environment.getResource( DESCRIPTOR_DEFAULT_LOCATION );
+    hostMapper = new FileBasedHostMapper( url );
+    clusterName = environment.getAttribute(  GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE );
+    GatewayServices services = environment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE );
+    if( clusterName != null && services != null ) {
+      hostMapperService = services.getService( GatewayServices.HOST_MAPPING_SERVICE );
+      if( hostMapperService != null ) {
+        hostMapperService.registerHostMapperForCluster( clusterName, hostMapper );
+      }
+    }
+  }
+
+  @Override
+  public void destroy() throws Exception {
+    if( hostMapperService != null && clusterName != null ) {
+      hostMapperService.removeHostMapperForCluster( clusterName );
+    }
+  }
+
+  @Override
+  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
+    List<String> result = null;
+    if( parameters != null ) {
+      result = new ArrayList<String>( parameters.size() );
+      for( String parameter : parameters ) {
+        switch( context.getDirection() ) {
+          case UrlRewriter.Direction.IN:
+            parameter = hostMapper.resolveInboundHostName( parameter );
+            break;
+          case UrlRewriter.Direction.OUT:
+            parameter = hostMapper.resolveOutboundHostName( parameter );
+            break;
+        }
+        result.add( parameter );
+      }
+//    System.out.println( "HOSTMAP: " + parameter + "->" + value );
+    }
+    return result;
+  }
+
+}
+


[54/64] knox git commit: KNOX-978 - Add a test for the SOLR REST API

Posted by mo...@apache.org.
KNOX-978 - Add a test for the SOLR REST API


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

Branch: refs/heads/KNOX-998-Package_Restructuring
Commit: d2f0fc0e5ec07d0e8d4633ce8bc0f0723a34efbe
Parents: ac532bd
Author: Colm O hEigeartaigh <co...@apache.org>
Authored: Tue Jun 27 11:13:56 2017 +0100
Committer: Colm O hEigeartaigh <co...@apache.org>
Committed: Tue Aug 29 14:50:24 2017 +0100

----------------------------------------------------------------------
 .../hadoop/gateway/GatewayBasicFuncTest.java    | 39 +++++++++++++++++++-
 .../solr/query_response.xml                     | 20 ++++++++++
 2 files changed, 58 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/knox/blob/d2f0fc0e/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayBasicFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayBasicFuncTest.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayBasicFuncTest.java
index 2cc1573..d8f1352 100644
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayBasicFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayBasicFuncTest.java
@@ -92,6 +92,7 @@ import static org.hamcrest.Matchers.containsString;
 import static org.hamcrest.Matchers.greaterThan;
 import static org.hamcrest.text.IsEmptyString.isEmptyString;
 import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
 import static org.xmlmatchers.XmlMatchers.isEquivalentTo;
 import static org.xmlmatchers.transform.XmlConverters.the;
 import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs;
@@ -161,6 +162,7 @@ public class GatewayBasicFuncTest {
     driver.setupService( "FALCON", "http://" + TEST_HOST + ":15000", "/cluster/falcon", USE_MOCK_SERVICES );
     driver.setupService( "STORM", "http://" + TEST_HOST + ":8477", "/cluster/storm", USE_MOCK_SERVICES );
     driver.setupService( "STORM-LOGVIEWER", "http://" + TEST_HOST + ":8477", "/cluster/storm", USE_MOCK_SERVICES );
+    driver.setupService( "SOLR", "http://" + TEST_HOST + ":8983", "/cluster/solr", USE_MOCK_SERVICES );
     driver.setupGateway( config, "cluster", createTopology(), USE_GATEWAY );
     LOG_EXIT();
   }
@@ -263,6 +265,9 @@ public class GatewayBasicFuncTest {
             .addTag("role").addText("STORM-LOGVIEWER")
             .addTag("url").addText(driver.getRealUrl("STORM-LOGVIEWER")).gotoParent()
         .addTag("service")
+            .addTag("role").addText("SOLR")
+            .addTag("url").addText(driver.getRealUrl("SOLR")).gotoParent()
+        .addTag("service")
         .addTag("role").addText("SERVICE-TEST")
         .gotoRoot();
 //     System.out.println( "GATEWAY=" + xml.toString() );
@@ -3703,6 +3708,38 @@ public class GatewayBasicFuncTest {
     LOG_EXIT();
   }
 
+  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
+  public void testSolrRESTAPI() throws Exception {
+    LOG_ENTER();
+    String resourceName = "solr/query_response.xml";
+    String username = "hdfs";
+    String password = "hdfs-password";
+
+    String gatewayPath = driver.getUrl( "SOLR" ) + "/gettingstarted/select?q=author_s:William+Shakespeare";
+    driver.getMock("SOLR")
+        .expect()
+        .method("GET")
+        .pathInfo("/gettingstarted/select")
+        .queryParam("q", "author_s:William+Shakespeare")
+        .respond()
+        .status(HttpStatus.SC_OK)
+        .content(driver.getResourceBytes(resourceName))
+        .contentType(ContentType.XML.toString());
+
+    Response response = given()
+        .auth().preemptive().basic(username, password)
+        .header("X-XSRF-Header", "jksdhfkhdsf")
+        .header("Accept", ContentType.XML.toString())
+        .expect()
+        .statusCode(HttpStatus.SC_OK)
+        .contentType( ContentType.XML.toString() )
+        .when().get( gatewayPath );
+
+    assertTrue(response.getBody().asString().contains("The Merchant of Venice"));
+
+    driver.assertComplete();
+    LOG_EXIT();
+  }
 
   void setupResource(String serviceRole, String path){
     driver.getMock(serviceRole)
@@ -3750,7 +3787,7 @@ public class GatewayBasicFuncTest {
       System.out.println(e.getMessage());
     }
   }
-  
+
   private String createFileNN( String user, String password, String file, String permsOctal, int status ) throws IOException {
     if( status == HttpStatus.SC_TEMPORARY_REDIRECT ) {
       driver.getMock( "WEBHDFS" )

http://git-wip-us.apache.org/repos/asf/knox/blob/d2f0fc0e/gateway-test/src/test/resources/org/apache/hadoop/gateway/GatewayBasicFuncTest/solr/query_response.xml
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/resources/org/apache/hadoop/gateway/GatewayBasicFuncTest/solr/query_response.xml b/gateway-test/src/test/resources/org/apache/hadoop/gateway/GatewayBasicFuncTest/solr/query_response.xml
new file mode 100644
index 0000000..dd79042
--- /dev/null
+++ b/gateway-test/src/test/resources/org/apache/hadoop/gateway/GatewayBasicFuncTest/solr/query_response.xml
@@ -0,0 +1,20 @@
+<!--
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+-->
+<?xml version="1.0" encoding="UTF-8"?>
+<response>
+<lst name="responseHeader"><bool name="zkConnected">true</bool><int name="status">0</int><int name="QTime">9</int><lst name="params"><str name="q">author_s:William Shakespeare</str></lst></lst><result name="response" numFound="2" start="0" maxScore="0.62191015"><doc><str name="id">book2</str><arr name="title_t"><str>The Merchant of Venice</str></arr><str name="author_s">William Shakespeare</str><long name="_version_">1571258160735322112</long></doc><doc><str name="id">book1</str><arr name="title_t"><str>The Merchant of Venice</str></arr><str name="author_s">William Shakespeare</str><long name="_version_">1571258154399825920</long></doc></result>
+</response>
\ No newline at end of file


[35/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessorTest.java
deleted file mode 100644
index 7da18c9..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessorTest.java
+++ /dev/null
@@ -1,153 +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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.ha.provider.HaProvider;
-import org.apache.hadoop.gateway.ha.provider.HaServletContextListener;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.hostmap.HostMapper;
-import org.apache.hadoop.gateway.services.hostmap.HostMapperService;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-import org.apache.hadoop.gateway.svcregfunc.api.ServiceMappedAddressFunctionDescriptor;
-import org.easymock.EasyMock;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
-import static org.junit.Assert.fail;
-
-public class ServiceMappedAddressFunctionProcessorTest {
-
-  HostMapperService hms;
-  HostMapper hm;
-  ServiceRegistry reg;
-  GatewayServices svc;
-  UrlRewriteEnvironment env;
-  UrlRewriteContext ctx;
-  ServiceMappedAddressFunctionDescriptor desc;
-
-  @Before
-  public void setUp() {
-    hm = EasyMock.createNiceMock( HostMapper.class );
-    EasyMock.expect( hm.resolveInboundHostName( "test-host" ) ).andReturn( "test-internal-host" ).anyTimes();
-
-    hms = EasyMock.createNiceMock( HostMapperService.class );
-    EasyMock.expect( hms.getHostMapper( "test-cluster" ) ).andReturn( hm ).anyTimes();
-
-    reg = EasyMock.createNiceMock( ServiceRegistry.class );
-    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
-
-    svc = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
-    EasyMock.expect( svc.getService( GatewayServices.HOST_MAPPING_SERVICE ) ).andReturn( hms ).anyTimes();
-
-    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
-
-    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
-    EasyMock.expect( ctx.getDirection() ).andReturn( UrlRewriter.Direction.IN ).anyTimes();
-
-    desc = EasyMock.createNiceMock( ServiceMappedAddressFunctionDescriptor.class );
-
-     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
-
-     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
-
-     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
-
-     EasyMock.replay( hm, hms, reg, svc, env, desc, ctx, haProvider );
-  }
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ServiceMappedAddressFunctionProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ServiceMappedAddressFunctionProcessor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    ServiceMappedAddressFunctionProcessor func = new ServiceMappedAddressFunctionProcessor();
-    assertThat( func.name(), is( "serviceMappedAddr" ) );
-  }
-
-  @Test
-  public void testInitialize() throws Exception {
-    ServiceMappedAddressFunctionProcessor func = new ServiceMappedAddressFunctionProcessor();
-    try {
-      func.initialize( null, desc );
-      fail( "Should have thrown an IllegalArgumentException" );
-    } catch( IllegalArgumentException e ) {
-      assertThat( e.getMessage(), containsString( "environment" ) );
-    }
-
-    func = new ServiceMappedAddressFunctionProcessor();
-    try {
-      func.initialize( env, null );
-    } catch( Exception e ) {
-      e.printStackTrace();
-      fail( "Should not have thrown an exception" );
-    }
-
-    func.initialize( env, desc );
-
-    assertThat( func.cluster(), is( "test-cluster" ) );
-    assertThat( func.registry(), sameInstance( reg ) );
-  }
-
-  @Test
-  public void testDestroy() throws Exception {
-    ServiceMappedAddressFunctionProcessor func = new ServiceMappedAddressFunctionProcessor();
-    func.initialize( env, desc );
-    func.destroy();
-
-    assertThat( func.cluster(), nullValue() );
-    assertThat( func.registry(), nullValue() );
-  }
-
-  @Test
-  public void testResolve() throws Exception {
-    ServiceMappedAddressFunctionProcessor func = new ServiceMappedAddressFunctionProcessor();
-    func.initialize( env, desc );
-
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-internal-host:777" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
-    assertThat( func.resolve( ctx, null ), nullValue() );
-
-    func.destroy();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessorTest.java
deleted file mode 100644
index 6e9df55..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessorTest.java
+++ /dev/null
@@ -1,153 +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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.ha.provider.HaProvider;
-import org.apache.hadoop.gateway.ha.provider.HaServletContextListener;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.hostmap.HostMapper;
-import org.apache.hadoop.gateway.services.hostmap.HostMapperService;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-import org.apache.hadoop.gateway.svcregfunc.api.ServiceMappedHostFunctionDescriptor;
-import org.easymock.EasyMock;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
-import static org.junit.Assert.fail;
-
-public class ServiceMappedHostFunctionProcessorTest {
-
-  HostMapperService hms;
-  HostMapper hm;
-  ServiceRegistry reg;
-  GatewayServices svc;
-  UrlRewriteEnvironment env;
-  UrlRewriteContext ctx;
-  ServiceMappedHostFunctionDescriptor desc;
-
-  @Before
-  public void setUp() {
-    hm = EasyMock.createNiceMock( HostMapper.class );
-    EasyMock.expect( hm.resolveInboundHostName( "test-host" ) ).andReturn( "test-internal-host" ).anyTimes();
-
-    hms = EasyMock.createNiceMock( HostMapperService.class );
-    EasyMock.expect( hms.getHostMapper( "test-cluster" ) ).andReturn( hm ).anyTimes();
-
-    reg = EasyMock.createNiceMock( ServiceRegistry.class );
-    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
-
-    svc = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
-    EasyMock.expect( svc.getService( GatewayServices.HOST_MAPPING_SERVICE ) ).andReturn( hms ).anyTimes();
-
-    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
-
-    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
-    EasyMock.expect( ctx.getDirection() ).andReturn( UrlRewriter.Direction.IN ).anyTimes();
-
-    desc = EasyMock.createNiceMock( ServiceMappedHostFunctionDescriptor.class );
-
-     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
-
-     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
-
-     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
-
-     EasyMock.replay( hm, hms, reg, svc, env, desc, ctx, haProvider );
-  }
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ServiceMappedHostFunctionProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ServiceMappedHostFunctionProcessor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    ServiceMappedHostFunctionProcessor func = new ServiceMappedHostFunctionProcessor();
-    assertThat( func.name(), is( "serviceMappedHost" ) );
-  }
-
-  @Test
-  public void testInitialize() throws Exception {
-    ServiceMappedHostFunctionProcessor func = new ServiceMappedHostFunctionProcessor();
-    try {
-      func.initialize( null, desc );
-      fail( "Should have thrown an IllegalArgumentException" );
-    } catch( IllegalArgumentException e ) {
-      assertThat( e.getMessage(), containsString( "environment" ) );
-    }
-
-    func = new ServiceMappedHostFunctionProcessor();
-    try {
-      func.initialize( env, null );
-    } catch( Exception e ) {
-      e.printStackTrace();
-      fail( "Should not have thrown an exception" );
-    }
-
-    func.initialize( env, desc );
-
-    assertThat( func.cluster(), is( "test-cluster" ) );
-    assertThat( func.registry(), sameInstance( reg ) );
-  }
-
-  @Test
-  public void testDestroy() throws Exception {
-    ServiceMappedHostFunctionProcessor func = new ServiceMappedHostFunctionProcessor();
-    func.initialize( env, desc );
-    func.destroy();
-
-    assertThat( func.cluster(), nullValue() );
-    assertThat( func.registry(), nullValue() );
-  }
-
-  @Test
-  public void testResolve() throws Exception {
-    ServiceMappedHostFunctionProcessor func = new ServiceMappedHostFunctionProcessor();
-    func.initialize( env, desc );
-
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-internal-host" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
-    assertThat( func.resolve( ctx, null ), nullValue() );
-
-    func.destroy();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessorTest.java
deleted file mode 100644
index 4ce0c5d..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessorTest.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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.ha.provider.HaProvider;
-import org.apache.hadoop.gateway.ha.provider.HaServletContextListener;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.hostmap.HostMapper;
-import org.apache.hadoop.gateway.services.hostmap.HostMapperService;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-import org.apache.hadoop.gateway.svcregfunc.api.ServiceMappedUrlFunctionDescriptor;
-import org.easymock.EasyMock;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
-import static org.junit.Assert.fail;
-
-public class ServiceMappedUrlFunctionProcessorTest {
-
-  HostMapperService hms;
-  HostMapper hm;
-  ServiceRegistry reg;
-  GatewayServices svc;
-  UrlRewriteEnvironment env;
-  UrlRewriteContext ctx;
-  ServiceMappedUrlFunctionDescriptor desc;
-
-  @Before
-  public void setUp() {
-    hm = EasyMock.createNiceMock( HostMapper.class );
-    EasyMock.expect( hm.resolveInboundHostName( "test-host" ) ).andReturn( "test-internal-host" ).anyTimes();
-
-    hms = EasyMock.createNiceMock( HostMapperService.class );
-    EasyMock.expect( hms.getHostMapper( "test-cluster" ) ).andReturn( hm ).anyTimes();
-
-    reg = EasyMock.createNiceMock( ServiceRegistry.class );
-    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
-
-    svc = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
-    EasyMock.expect( svc.getService( GatewayServices.HOST_MAPPING_SERVICE ) ).andReturn( hms ).anyTimes();
-
-    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
-
-    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
-    EasyMock.expect( ctx.getDirection() ).andReturn( UrlRewriter.Direction.IN ).anyTimes();
-
-    desc = EasyMock.createNiceMock( ServiceMappedUrlFunctionDescriptor.class );
-
-
-     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
-
-     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
-
-     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
-
-     EasyMock.replay( hm, hms, reg, svc, env, desc, ctx, haProvider );
-  }
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ServiceMappedUrlFunctionProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ServiceMappedUrlFunctionProcessor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    ServiceMappedUrlFunctionProcessor func = new ServiceMappedUrlFunctionProcessor();
-    assertThat( func.name(), is( "serviceMappedUrl" ) );
-  }
-
-  @Test
-  public void testInitialize() throws Exception {
-    ServiceMappedUrlFunctionProcessor func = new ServiceMappedUrlFunctionProcessor();
-    try {
-      func.initialize( null, desc );
-      fail( "Should have thrown an IllegalArgumentException" );
-    } catch( IllegalArgumentException e ) {
-      assertThat( e.getMessage(), containsString( "environment" ) );
-    }
-
-    func = new ServiceMappedUrlFunctionProcessor();
-    try {
-      func.initialize( env, null );
-    } catch( Exception e ) {
-      e.printStackTrace(); //NOTE: OK to use e.printStackTrace for a test failure.
-      fail( "Should not have thrown an exception" );
-    }
-
-    func.initialize( env, desc );
-
-    assertThat( func.cluster(), is( "test-cluster" ) );
-    assertThat( func.registry(), sameInstance( reg ) );
-  }
-
-  @Test
-  public void testDestroy() throws Exception {
-    ServiceMappedUrlFunctionProcessor func = new ServiceMappedUrlFunctionProcessor();
-    func.initialize( env, desc );
-    func.destroy();
-
-    assertThat( func.cluster(), nullValue() );
-    assertThat( func.registry(), nullValue() );
-  }
-
-  @Test
-  public void testResolve() throws Exception {
-    ServiceMappedUrlFunctionProcessor func = new ServiceMappedUrlFunctionProcessor();
-    func.initialize( env, desc );
-
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-scheme://test-internal-host:777/test-path" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
-    assertThat( func.resolve( ctx, null ), nullValue() );
-
-    func.destroy();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePathFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePathFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePathFunctionProcessorTest.java
deleted file mode 100644
index fb44b2e..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePathFunctionProcessorTest.java
+++ /dev/null
@@ -1,140 +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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.ha.provider.HaProvider;
-import org.apache.hadoop.gateway.ha.provider.HaServletContextListener;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-import org.apache.hadoop.gateway.svcregfunc.api.ServicePathFunctionDescriptor;
-import org.easymock.EasyMock;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
-import static org.junit.Assert.fail;
-
-public class ServicePathFunctionProcessorTest {
-
-  ServiceRegistry reg;
-  GatewayServices svc;
-  UrlRewriteEnvironment env;
-  UrlRewriteContext ctx;
-  ServicePathFunctionDescriptor desc;
-
-  @Before
-  public void setUp() {
-    reg = EasyMock.createNiceMock( ServiceRegistry.class );
-    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
-
-    svc = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
-
-    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
-
-    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
-
-    desc = EasyMock.createNiceMock( ServicePathFunctionDescriptor.class );
-
-     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
-
-     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
-
-     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
-
-     EasyMock.replay( reg, svc, env, desc, ctx, haProvider );
-  }
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ServicePathFunctionProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ServicePathFunctionProcessor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    ServicePathFunctionProcessor func = new ServicePathFunctionProcessor();
-    assertThat( func.name(), is( "servicePath" ) );
-  }
-
-  @Test
-  public void testInitialize() throws Exception {
-    ServicePathFunctionProcessor func = new ServicePathFunctionProcessor();
-    try {
-      func.initialize( null, desc );
-      fail( "Should have thrown an IllegalArgumentException" );
-    } catch( IllegalArgumentException e ) {
-      assertThat( e.getMessage(), containsString( "environment" ) );
-    }
-
-    func = new ServicePathFunctionProcessor();
-    try {
-      func.initialize( env, null );
-    } catch( Exception e ) {
-      e.printStackTrace();
-      fail( "Should not have thrown an exception" );
-    }
-
-    func.initialize( env, desc );
-
-    assertThat( func.cluster(), is( "test-cluster" ) );
-    assertThat( func.registry(), sameInstance( reg ) );
-  }
-
-  @Test
-  public void testDestroy() throws Exception {
-    ServicePathFunctionProcessor func = new ServicePathFunctionProcessor();
-    func.initialize( env, desc );
-    func.destroy();
-
-    assertThat( func.cluster(), nullValue() );
-    assertThat( func.registry(), nullValue() );
-  }
-
-  @Test
-  public void testResolve() throws Exception {
-    ServicePathFunctionProcessor func = new ServicePathFunctionProcessor();
-    func.initialize( env, desc );
-
-//    assertThat( func.resolve( ctx, "test-service" ), is( "/test-path" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
-//    assertThat( func.resolve( ctx, null ), nullValue() );
-
-    func.destroy();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePortFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePortFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePortFunctionProcessorTest.java
deleted file mode 100644
index d14a8de..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePortFunctionProcessorTest.java
+++ /dev/null
@@ -1,140 +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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.ha.provider.HaProvider;
-import org.apache.hadoop.gateway.ha.provider.HaServletContextListener;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-import org.apache.hadoop.gateway.svcregfunc.api.ServicePortFunctionDescriptor;
-import org.easymock.EasyMock;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
-import static org.junit.Assert.fail;
-
-public class ServicePortFunctionProcessorTest {
-
-  ServiceRegistry reg;
-  GatewayServices svc;
-  UrlRewriteEnvironment env;
-  UrlRewriteContext ctx;
-  ServicePortFunctionDescriptor desc;
-
-  @Before
-  public void setUp() {
-    reg = EasyMock.createNiceMock( ServiceRegistry.class );
-    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
-
-    svc = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
-
-    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
-
-    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
-
-    desc = EasyMock.createNiceMock( ServicePortFunctionDescriptor.class );
-
-     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
-
-     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
-
-     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
-
-     EasyMock.replay( reg, svc, env, desc, ctx, haProvider );
-  }
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ServicePortFunctionProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ServicePortFunctionProcessor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    ServicePortFunctionProcessor func = new ServicePortFunctionProcessor();
-    assertThat( func.name(), is( "servicePort" ) );
-  }
-
-  @Test
-  public void testInitialize() throws Exception {
-    ServicePortFunctionProcessor func = new ServicePortFunctionProcessor();
-    try {
-      func.initialize( null, desc );
-      fail( "Should have thrown an IllegalArgumentException" );
-    } catch( IllegalArgumentException e ) {
-      assertThat( e.getMessage(), containsString( "environment" ) );
-    }
-
-    func = new ServicePortFunctionProcessor();
-    try {
-      func.initialize( env, null );
-    } catch( Exception e ) {
-      e.printStackTrace();
-      fail( "Should not have thrown an exception" );
-    }
-
-    func.initialize( env, desc );
-
-    assertThat( func.cluster(), is( "test-cluster" ) );
-    assertThat( func.registry(), sameInstance( reg ) );
-  }
-
-  @Test
-  public void testDestroy() throws Exception {
-    ServicePortFunctionProcessor func = new ServicePortFunctionProcessor();
-    func.initialize( env, desc );
-    func.destroy();
-
-    assertThat( func.cluster(), nullValue() );
-    assertThat( func.registry(), nullValue() );
-  }
-
-  @Test
-  public void testResolve() throws Exception {
-    ServicePortFunctionProcessor func = new ServicePortFunctionProcessor();
-    func.initialize( env, desc );
-
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "777" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
-    assertThat( func.resolve( ctx, null ), nullValue() );
-
-    func.destroy();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest.java
deleted file mode 100644
index c4a41d5..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest.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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletFilter;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.test.TestUtils;
-import org.apache.hadoop.test.log.NoOpLogger;
-import org.apache.hadoop.test.mock.MockInteraction;
-import org.apache.hadoop.test.mock.MockServlet;
-import org.apache.http.auth.BasicUserPrincipal;
-import org.easymock.EasyMock;
-import org.eclipse.jetty.servlet.FilterHolder;
-import org.eclipse.jetty.servlet.ServletHolder;
-import org.eclipse.jetty.http.HttpTester;
-import org.eclipse.jetty.servlet.ServletTester;
-import org.eclipse.jetty.util.ArrayQueue;
-import org.eclipse.jetty.util.log.Log;
-import org.hamcrest.core.Is;
-import org.junit.Test;
-
-import javax.security.auth.Subject;
-import javax.servlet.*;
-import javax.servlet.http.HttpServletRequest;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.nio.ByteBuffer;
-import java.nio.charset.Charset;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-
-
-public class ServiceRegistryFunctionsTest {
-
-  private ServletTester server;
-  private HttpTester.Request request;
-  private HttpTester.Response response;
-  private ArrayQueue<MockInteraction> interactions;
-  private MockInteraction interaction;
-
-  private static URL getTestResource( String name ) {
-    name = ServiceRegistryFunctionsTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
-    URL url = ClassLoader.getSystemResource( name );
-    return url;
-  }
-
-  public void setUp( String username, Map<String,String> initParams ) throws Exception {
-    ServiceRegistry mockServiceRegistry = EasyMock.createNiceMock( ServiceRegistry.class );
-    EasyMock.expect( mockServiceRegistry.lookupServiceURL( "test-cluster", "NAMENODE" ) ).andReturn( "test-nn-scheme://test-nn-host:411" ).anyTimes();
-    EasyMock.expect( mockServiceRegistry.lookupServiceURL( "test-cluster", "JOBTRACKER" ) ).andReturn( "test-jt-scheme://test-jt-host:511" ).anyTimes();
-
-    GatewayServices mockGatewayServices = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( mockGatewayServices.getService(GatewayServices.SERVICE_REGISTRY_SERVICE) ).andReturn( mockServiceRegistry ).anyTimes();
-
-    EasyMock.replay( mockServiceRegistry, mockGatewayServices );
-
-    String descriptorUrl = getTestResource( "rewrite.xml" ).toExternalForm();
-
-    Log.setLog( new NoOpLogger() );
-
-    server = new ServletTester();
-    server.setContextPath( "/" );
-    server.getContext().addEventListener( new UrlRewriteServletContextListener() );
-    server.getContext().setInitParameter(
-        UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );
-    server.getContext().setAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE, "test-cluster" );
-    server.getContext().setAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE, mockGatewayServices );
-
-    FilterHolder setupFilter = server.addFilter( SetupFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
-    setupFilter.setFilter( new SetupFilter( username ) );
-    FilterHolder rewriteFilter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
-    if( initParams != null ) {
-      for( Map.Entry<String,String> entry : initParams.entrySet() ) {
-        rewriteFilter.setInitParameter( entry.getKey(), entry.getValue() );
-      }
-    }
-    rewriteFilter.setFilter( new UrlRewriteServletFilter() );
-
-    interactions = new ArrayQueue<MockInteraction>();
-
-    ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
-    servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );
-
-    server.start();
-
-    interaction = new MockInteraction();
-    request = HttpTester.newRequest();
-    response = null;
-  }
-
-  @Test
-  public void testServiceRegistryFunctionsOnXmlRequestBody() throws Exception {
-    Map<String,String> initParams = new HashMap<>();
-    initParams.put( "request.body", "oozie-conf" );
-    setUp( "test-user", initParams );
-
-    String input = TestUtils.getResourceString( ServiceRegistryFunctionsTest.class, "test-input-body.xml", "UTF-8" );
-    String expect = TestUtils.getResourceString( ServiceRegistryFunctionsTest.class, "test-expect-body.xml", "UTF-8" );
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "PUT" )
-        .requestUrl( "http://test-host:42/test-path" )
-        .contentType( "text/xml" )
-        .characterEncoding( "UTF-8" )
-        .content( expect, Charset.forName( "UTF-8" ) );
-    interaction.respond()
-        .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "PUT" );
-    request.setURI( "/test-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "test-host:42" );
-    request.setHeader( "Content-Type", "text/xml; charset=UTF-8" );
-    request.setContent( input );
-
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), Is.is( 200 ) );
-  }
-
-  @Test
-  public void testServiceRegistryFunctionsOnJsonRequestBody() throws Exception {
-    Map<String,String> initParams = new HashMap<>();
-    initParams.put( "request.body", "oozie-conf" );
-    setUp( "test-user", initParams );
-
-    String input = TestUtils.getResourceString( ServiceRegistryFunctionsTest.class, "test-input-body.json", "UTF-8" );
-    String expect = TestUtils.getResourceString( ServiceRegistryFunctionsTest.class, "test-expect-body.json", "UTF-8" );
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "PUT" )
-        .requestUrl( "http://test-host:42/test-path" )
-        .contentType( "application/json" )
-        .characterEncoding( "UTF-8" )
-        .content( expect, Charset.forName( "UTF-8" ) );
-    interaction.respond()
-        .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "PUT" );
-    request.setURI( "/test-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "test-host:42" );
-    request.setHeader( "Content-Type", "application/json; charset=UTF-8" );
-    request.setContent( input );
-
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), Is.is( 200 ) );
-  }
-
-  private static class SetupFilter implements Filter {
-    private Subject subject;
-
-    public SetupFilter( String userName ) {
-      subject = new Subject();
-      subject.getPrincipals().add( new BasicUserPrincipal( userName ) );
-    }
-
-    @Override
-    public void init( FilterConfig filterConfig ) throws ServletException {
-    }
-
-    @Override
-    public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException {
-      HttpServletRequest httpRequest = ((HttpServletRequest)request);
-      StringBuffer sourceUrl = httpRequest.getRequestURL();
-      String queryString = httpRequest.getQueryString();
-      if( queryString != null ) {
-        sourceUrl.append( "?" );
-        sourceUrl.append( queryString );
-      }
-      try {
-        request.setAttribute(
-            AbstractGatewayFilter.SOURCE_REQUEST_URL_ATTRIBUTE_NAME,
-            Parser.parseLiteral( sourceUrl.toString() ) );
-      } catch( URISyntaxException e ) {
-        throw new ServletException( e );
-      }
-      try {
-        Subject.doAs( subject, new PrivilegedExceptionAction<Void>() {
-          @Override
-          public Void run() throws Exception {
-            chain.doFilter( request, response );
-            return null;
-          }
-        } );
-      } catch( PrivilegedActionException e ) {
-        throw new ServletException( e );
-      }
-    }
-
-    @Override
-    public void destroy() {
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessorTest.java
deleted file mode 100644
index 02919c5..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessorTest.java
+++ /dev/null
@@ -1,140 +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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.ha.provider.HaProvider;
-import org.apache.hadoop.gateway.ha.provider.HaServletContextListener;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-import org.apache.hadoop.gateway.svcregfunc.api.ServiceSchemeFunctionDescriptor;
-import org.easymock.EasyMock;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
-import static org.junit.Assert.fail;
-
-public class ServiceSchemeFunctionProcessorTest {
-
-  ServiceRegistry reg;
-  GatewayServices svc;
-  UrlRewriteEnvironment env;
-  UrlRewriteContext ctx;
-  ServiceSchemeFunctionDescriptor desc;
-
-  @Before
-  public void setUp() {
-    reg = EasyMock.createNiceMock( ServiceRegistry.class );
-    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
-
-    svc = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
-
-    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
-
-    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
-
-    desc = EasyMock.createNiceMock( ServiceSchemeFunctionDescriptor.class );
-
-     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
-
-     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
-
-     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
-
-     EasyMock.replay( reg, svc, env, desc, ctx, haProvider );
-  }
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ServiceSchemeFunctionProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ServiceSchemeFunctionProcessor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    ServiceSchemeFunctionProcessor func = new ServiceSchemeFunctionProcessor();
-    assertThat( func.name(), is( "serviceScheme" ) );
-  }
-
-  @Test
-  public void testInitialize() throws Exception {
-    ServiceSchemeFunctionProcessor func = new ServiceSchemeFunctionProcessor();
-    try {
-      func.initialize( null, desc );
-      fail( "Should have thrown an IllegalArgumentException" );
-    } catch( IllegalArgumentException e ) {
-      assertThat( e.getMessage(), containsString( "environment" ) );
-    }
-
-    func = new ServiceSchemeFunctionProcessor();
-    try {
-      func.initialize( env, null );
-    } catch( Exception e ) {
-      e.printStackTrace(); //NOTE: This is an OK use of e.printStackTrace in a test.
-      fail( "Should not have thrown an exception" );
-    }
-
-    func.initialize( env, desc );
-
-    assertThat( func.cluster(), is( "test-cluster" ) );
-    assertThat( func.registry(), sameInstance( reg ) );
-  }
-
-  @Test
-  public void testDestroy() throws Exception {
-    ServiceSchemeFunctionProcessor func = new ServiceSchemeFunctionProcessor();
-    func.initialize( env, desc );
-    func.destroy();
-
-    assertThat( func.cluster(), nullValue() );
-    assertThat( func.registry(), nullValue() );
-  }
-
-  @Test
-  public void testResolve() throws Exception {
-    ServiceSchemeFunctionProcessor func = new ServiceSchemeFunctionProcessor();
-    func.initialize( env, desc );
-
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-scheme" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
-    assertThat( func.resolve( ctx, null ), nullValue() );
-
-    func.destroy();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceUrlFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceUrlFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceUrlFunctionProcessorTest.java
deleted file mode 100644
index 2b94df6..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceUrlFunctionProcessorTest.java
+++ /dev/null
@@ -1,153 +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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.ha.provider.HaProvider;
-import org.apache.hadoop.gateway.ha.provider.HaServletContextListener;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.hostmap.HostMapper;
-import org.apache.hadoop.gateway.services.hostmap.HostMapperService;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-import org.apache.hadoop.gateway.svcregfunc.api.ServiceUrlFunctionDescriptor;
-import org.easymock.EasyMock;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
-import static org.junit.Assert.fail;
-
-public class ServiceUrlFunctionProcessorTest {
-
-  HostMapperService hms;
-  HostMapper hm;
-  ServiceRegistry reg;
-  GatewayServices svc;
-  UrlRewriteEnvironment env;
-  UrlRewriteContext ctx;
-  ServiceUrlFunctionDescriptor desc;
-
-  @Before
-  public void setUp() {
-    hm = EasyMock.createNiceMock( HostMapper.class );
-    EasyMock.expect( hm.resolveInboundHostName( "test-host" ) ).andReturn( "test-internal-host" ).anyTimes();
-
-    hms = EasyMock.createNiceMock( HostMapperService.class );
-    EasyMock.expect( hms.getHostMapper( "test-cluster" ) ).andReturn( hm ).anyTimes();
-
-    reg = EasyMock.createNiceMock( ServiceRegistry.class );
-    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
-
-    svc = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
-    EasyMock.expect( svc.getService( GatewayServices.HOST_MAPPING_SERVICE ) ).andReturn( hms ).anyTimes();
-
-    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
-
-    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
-    EasyMock.expect( ctx.getDirection() ).andReturn( UrlRewriter.Direction.IN ).anyTimes();
-
-    desc = EasyMock.createNiceMock( ServiceUrlFunctionDescriptor.class );
-
-     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
-
-     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
-
-     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
-
-    EasyMock.replay( hm, hms, reg, svc, env, desc, ctx, haProvider);
-  }
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ServiceUrlFunctionProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ServiceUrlFunctionProcessor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    ServiceUrlFunctionProcessor func = new ServiceUrlFunctionProcessor();
-    assertThat( func.name(), is( "serviceUrl" ) );
-  }
-
-  @Test
-  public void testInitialize() throws Exception {
-    ServiceUrlFunctionProcessor func = new ServiceUrlFunctionProcessor();
-    try {
-      func.initialize( null, desc );
-      fail( "Should have thrown an IllegalArgumentException" );
-    } catch( IllegalArgumentException e ) {
-      assertThat( e.getMessage(), containsString( "environment" ) );
-    }
-
-    func = new ServiceUrlFunctionProcessor();
-    try {
-      func.initialize( env, null );
-    } catch( Exception e ) {
-      e.printStackTrace(); //NOTE: OK to use e.printStackTrace for a test failure.
-      fail( "Should not have thrown an exception" );
-    }
-
-    func.initialize( env, desc );
-
-    assertThat( func.cluster(), is( "test-cluster" ) );
-    assertThat( func.registry(), sameInstance( reg ) );
-  }
-
-  @Test
-  public void testDestroy() throws Exception {
-    ServiceUrlFunctionProcessor func = new ServiceUrlFunctionProcessor();
-    func.initialize( env, desc );
-    func.destroy();
-
-    assertThat( func.cluster(), nullValue() );
-    assertThat( func.registry(), nullValue() );
-  }
-
-  @Test
-  public void testResolve() throws Exception {
-    ServiceUrlFunctionProcessor func = new ServiceUrlFunctionProcessor();
-    func.initialize( env, desc );
-
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-scheme://test-host:777/test-path" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
-    assertThat( func.resolve( ctx, null ), nullValue() );
-
-    func.destroy();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceAddressFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceAddressFunctionDescriptorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceAddressFunctionDescriptorTest.java
new file mode 100644
index 0000000..3586b05
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceAddressFunctionDescriptorTest.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.knox.gateway.svcregfunc.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class ServiceAddressFunctionDescriptorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ServiceAddressFunctionDescriptor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ServiceAddressFunctionDescriptor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    ServiceAddressFunctionDescriptor descriptor = new ServiceAddressFunctionDescriptor();
+    assertThat( descriptor.name(), is( "serviceAddr" ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceHostFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceHostFunctionDescriptorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceHostFunctionDescriptorTest.java
new file mode 100644
index 0000000..736934d
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceHostFunctionDescriptorTest.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.knox.gateway.svcregfunc.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class ServiceHostFunctionDescriptorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ServiceHostFunctionDescriptor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ServiceHostFunctionDescriptor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    ServiceHostFunctionDescriptor descriptor = new ServiceHostFunctionDescriptor();
+    assertThat( descriptor.name(), is( "serviceHost" ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServicePathFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServicePathFunctionDescriptorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServicePathFunctionDescriptorTest.java
new file mode 100644
index 0000000..9fceb17
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServicePathFunctionDescriptorTest.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.knox.gateway.svcregfunc.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class ServicePathFunctionDescriptorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ServicePathFunctionDescriptor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ServicePathFunctionDescriptor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    ServicePathFunctionDescriptor descriptor = new ServicePathFunctionDescriptor();
+    assertThat( descriptor.name(), is( "servicePath" ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServicePortFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServicePortFunctionDescriptorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServicePortFunctionDescriptorTest.java
new file mode 100644
index 0000000..7df59a4
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServicePortFunctionDescriptorTest.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.knox.gateway.svcregfunc.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class ServicePortFunctionDescriptorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ServicePortFunctionDescriptor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ServicePortFunctionDescriptor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    ServicePortFunctionDescriptor descriptor = new ServicePortFunctionDescriptor();
+    assertThat( descriptor.name(), is( "servicePort" ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptorTest.java
new file mode 100644
index 0000000..bb14b7a
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptorTest.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.knox.gateway.svcregfunc.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class ServiceSchemeFunctionDescriptorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ServiceSchemeFunctionDescriptor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ServiceSchemeFunctionDescriptor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    ServiceSchemeFunctionDescriptor descriptor = new ServiceSchemeFunctionDescriptor();
+    assertThat( descriptor.name(), is( "serviceScheme" ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceUrlFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceUrlFunctionDescriptorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceUrlFunctionDescriptorTest.java
new file mode 100644
index 0000000..06e256b
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/api/ServiceUrlFunctionDescriptorTest.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.knox.gateway.svcregfunc.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class ServiceUrlFunctionDescriptorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ServiceUrlFunctionDescriptor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ServiceUrlFunctionDescriptor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    ServiceUrlFunctionDescriptor descriptor = new ServiceUrlFunctionDescriptor();
+    assertThat( descriptor.name(), is( "serviceUrl" ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceAddressFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceAddressFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceAddressFunctionProcessorTest.java
new file mode 100644
index 0000000..7de9ff8
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceAddressFunctionProcessorTest.java
@@ -0,0 +1,140 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.ha.provider.HaProvider;
+import org.apache.knox.gateway.ha.provider.HaServletContextListener;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+import org.apache.knox.gateway.svcregfunc.api.ServiceAddressFunctionDescriptor;
+import org.easymock.EasyMock;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
+import static org.junit.Assert.fail;
+
+public class ServiceAddressFunctionProcessorTest {
+
+  ServiceRegistry reg;
+  GatewayServices svc;
+  UrlRewriteEnvironment env;
+  UrlRewriteContext ctx;
+  ServiceAddressFunctionDescriptor desc;
+
+  @Before
+  public void setUp() {
+    reg = EasyMock.createNiceMock( ServiceRegistry.class );
+    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
+
+    svc = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
+
+    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
+
+    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
+
+    desc = EasyMock.createNiceMock( ServiceAddressFunctionDescriptor.class );
+
+    HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
+
+    EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
+
+    EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
+
+    EasyMock.replay( reg, svc, env, desc, ctx, haProvider );
+  }
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ServiceAddressFunctionProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ServiceAddressFunctionProcessor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    ServiceAddressFunctionProcessor func = new ServiceAddressFunctionProcessor();
+    assertThat( func.name(), is( "serviceAddr" ) );
+  }
+
+  @Test
+  public void testInitialize() throws Exception {
+    ServiceAddressFunctionProcessor func = new ServiceAddressFunctionProcessor();
+    try {
+      func.initialize( null, desc );
+      fail( "Should have thrown an IllegalArgumentException" );
+    } catch( IllegalArgumentException e ) {
+      assertThat( e.getMessage(), containsString( "environment" ) );
+    }
+
+    func = new ServiceAddressFunctionProcessor();
+    try {
+      func.initialize( env, null );
+    } catch( Exception e ) {
+      e.printStackTrace();
+      fail( "Should not have thrown an exception" );
+    }
+
+    func.initialize( env, desc );
+
+    assertThat( func.cluster(), is( "test-cluster" ) );
+    assertThat( func.registry(), sameInstance( reg ) );
+  }
+
+  @Test
+  public void testDestroy() throws Exception {
+    ServiceAddressFunctionProcessor func = new ServiceAddressFunctionProcessor();
+    func.initialize( env, desc );
+    func.destroy();
+
+    assertThat( func.cluster(), nullValue() );
+    assertThat( func.registry(), nullValue() );
+  }
+
+  @Test
+  public void testResolve() throws Exception {
+    ServiceAddressFunctionProcessor func = new ServiceAddressFunctionProcessor();
+    func.initialize( env, desc );
+
+    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-host:777" ) );
+    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, null ), nullValue() );
+
+    func.destroy();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceHostFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceHostFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceHostFunctionProcessorTest.java
new file mode 100644
index 0000000..5a95620
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceHostFunctionProcessorTest.java
@@ -0,0 +1,141 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.ha.provider.HaProvider;
+import org.apache.knox.gateway.ha.provider.HaServletContextListener;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+import org.apache.knox.gateway.svcregfunc.api.ServiceHostFunctionDescriptor;
+import org.easymock.EasyMock;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
+import static org.junit.Assert.fail;
+
+public class ServiceHostFunctionProcessorTest {
+
+  ServiceRegistry reg;
+  GatewayServices svc;
+  UrlRewriteEnvironment env;
+  UrlRewriteContext ctx;
+  ServiceHostFunctionDescriptor desc;
+
+  @Before
+  public void setUp() {
+    reg = EasyMock.createNiceMock( ServiceRegistry.class );
+    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
+
+    svc = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
+
+    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
+
+    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
+
+    desc = EasyMock.createNiceMock( ServiceHostFunctionDescriptor.class );
+
+     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
+
+     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
+
+     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
+
+     EasyMock.replay( reg, svc, env, desc, ctx, haProvider );
+
+  }
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ServiceHostFunctionProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ServiceHostFunctionProcessor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    ServiceHostFunctionProcessor func = new ServiceHostFunctionProcessor();
+    assertThat( func.name(), is( "serviceHost" ) );
+  }
+
+  @Test
+  public void testInitialize() throws Exception {
+    ServiceHostFunctionProcessor func = new ServiceHostFunctionProcessor();
+    try {
+      func.initialize( null, desc );
+      fail( "Should have thrown an IllegalArgumentException" );
+    } catch( IllegalArgumentException e ) {
+      assertThat( e.getMessage(), containsString( "environment" ) );
+    }
+
+    func = new ServiceHostFunctionProcessor();
+    try {
+      func.initialize( env, null );
+    } catch( Exception e ) {
+      e.printStackTrace();
+      fail( "Should not have thrown an exception" );
+    }
+
+    func.initialize( env, desc );
+
+    assertThat( func.cluster(), is( "test-cluster" ) );
+    assertThat( func.registry(), sameInstance( reg ) );
+  }
+
+  @Test
+  public void testDestroy() throws Exception {
+    ServiceHostFunctionProcessor func = new ServiceHostFunctionProcessor();
+    func.initialize( env, desc );
+    func.destroy();
+
+    assertThat( func.cluster(), nullValue() );
+    assertThat( func.registry(), nullValue() );
+  }
+
+  @Test
+  public void testResolve() throws Exception {
+    ServiceHostFunctionProcessor func = new ServiceHostFunctionProcessor();
+    func.initialize( env, desc );
+
+    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-host" ) );
+    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, null ), nullValue() );
+
+    func.destroy();
+  }
+
+}


[38/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index eda74c1..0000000
--- a/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.hostmap.impl.HostmapDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor b/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
deleted file mode 100644
index 3e80487..0000000
--- a/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.hostmap.api.HostmapFunctionDescriptor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor b/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
deleted file mode 100644
index 7c6619c..0000000
--- a/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.hostmap.impl.HostmapFunctionProcessor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..76328d9
--- /dev/null
+++ b/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.hostmap.impl.HostmapDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor b/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
new file mode 100644
index 0000000..82a1329
--- /dev/null
+++ b/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.hostmap.api.HostmapFunctionDescriptor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor b/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
new file mode 100644
index 0000000..c4c6a4d
--- /dev/null
+++ b/gateway-provider-rewrite-func-hostmap-static/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.hostmap.impl.HostmapFunctionProcessor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/hadoop/gateway/hostmap/api/HostmapFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/hadoop/gateway/hostmap/api/HostmapFunctionDescriptorTest.java b/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/hadoop/gateway/hostmap/api/HostmapFunctionDescriptorTest.java
deleted file mode 100644
index f3e8c0a..0000000
--- a/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/hadoop/gateway/hostmap/api/HostmapFunctionDescriptorTest.java
+++ /dev/null
@@ -1,65 +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.hadoop.gateway.hostmap.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class HostmapFunctionDescriptorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof HostmapFunctionDescriptor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + UrlRewriteFunctionDescriptor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testGetAndSet() {
-    HostmapFunctionDescriptor descriptor = new HostmapFunctionDescriptor();
-
-    assertThat( descriptor.name(), is( "hostmap" ) );
-    assertThat( descriptor.config(), nullValue() );
-
-    // Test Fluent API
-    descriptor.config( "test-config-location-fluent" );
-    assertThat( descriptor.config(), is( "test-config-location-fluent" ) );
-    assertThat( descriptor.getConfig(), is( "test-config-location-fluent" ) );
-
-    // Test Bean API
-    descriptor.setConfig( "test-config-location-bean" );
-    assertThat( descriptor.config(), is( "test-config-location-bean" ) );
-    assertThat( descriptor.getConfig(), is( "test-config-location-bean" ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/hadoop/gateway/hostmap/impl/HostmapDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/hadoop/gateway/hostmap/impl/HostmapDeploymentContributorTest.java b/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/hadoop/gateway/hostmap/impl/HostmapDeploymentContributorTest.java
deleted file mode 100644
index ef43735..0000000
--- a/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/hadoop/gateway/hostmap/impl/HostmapDeploymentContributorTest.java
+++ /dev/null
@@ -1,102 +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.hadoop.gateway.hostmap.impl;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteRulesDescriptorImpl;
-import org.apache.hadoop.gateway.hostmap.api.HostmapFunctionDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.easymock.EasyMock;
-import org.jboss.shrinkwrap.api.Node;
-import org.jboss.shrinkwrap.api.ShrinkWrap;
-import org.jboss.shrinkwrap.api.spec.WebArchive;
-import org.junit.Test;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class HostmapDeploymentContributorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( ProviderDeploymentContributor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof HostmapDeploymentContributor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + HostmapDeploymentContributor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testDeployment() throws IOException {
-    WebArchive webArchive = ShrinkWrap.create( WebArchive.class, "test-acrhive" );
-
-    UrlRewriteRulesDescriptorImpl rewriteRules = new UrlRewriteRulesDescriptorImpl();
-
-    Map<String,String> providerParams = new HashMap<>();
-    providerParams.put( "test-host-external", "test-host-internal" );
-    Provider provider = new Provider();
-    provider.setEnabled( true );
-    provider.setName( "hostmap" );
-    provider.setParams(  providerParams );
-
-    DeploymentContext context = EasyMock.createNiceMock( DeploymentContext.class );
-    EasyMock.expect( context.getDescriptor( "rewrite" ) ).andReturn( rewriteRules ).anyTimes();
-    EasyMock.expect( context.getWebArchive() ).andReturn( webArchive ).anyTimes();
-    EasyMock.replay( context );
-
-    HostmapDeploymentContributor contributor = new HostmapDeploymentContributor();
-
-    assertThat( contributor.getRole(), is("hostmap") );
-    assertThat( contributor.getName(), is( "static" ) );
-
-    // Just make sure it doesn't blow up.
-    contributor.contributeFilter( null, null, null, null, null );
-
-    // Just make sure it doesn't blow up.
-    contributor.initializeContribution( context );
-
-    contributor.contributeProvider( context, provider );
-
-    HostmapFunctionDescriptor funcDesc = rewriteRules.getFunction( "hostmap" );
-    assertThat( funcDesc.config(), is( "/WEB-INF/hostmap.txt" ) );
-
-    Node node = webArchive.get( "/WEB-INF/hostmap.txt" );
-    String asset = IOUtils.toString( node.getAsset().openStream() );
-    assertThat( asset, containsString( "test-host-external=test-host-internal" ) );
-
-    // Just make sure it doesn't blow up.
-    contributor.finalizeContribution( context );
-
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest.java b/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest.java
deleted file mode 100644
index 67290fb..0000000
--- a/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest.java
+++ /dev/null
@@ -1,274 +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.hadoop.gateway.hostmap.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteActionRewriteDescriptorExt;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.hostmap.HostMapper;
-import org.apache.hadoop.gateway.services.hostmap.HostMapperService;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-import org.apache.hadoop.test.TestUtils;
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-import java.net.URL;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class HostmapFunctionProcessorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof HostmapFunctionProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + HostmapFunctionProcessor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testBasicUseCase() throws Exception {
-    URL configUrl = TestUtils.getResourceUrl( this.getClass(), "hostmap.txt" );
-
-    HostMapper hm = EasyMock.createNiceMock(HostMapper.class);
-    EasyMock.expect( hm.resolveInboundHostName("test-inbound-host")).andReturn( "test-inbound-rewritten-host" ).anyTimes();
-    
-    HostMapperService hms = EasyMock.createNiceMock( HostMapperService.class );
-
-    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( gatewayServices.getService( GatewayServices.HOST_MAPPING_SERVICE ) ).andReturn( hms ).anyTimes();
-
-
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( environment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();    
-    EasyMock.expect( environment.resolve( "cluster.name" ) ).andReturn( Arrays.asList( "test-cluster-name" ) ).anyTimes();
-    EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
-    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-inbound-host" ) ).anyTimes();
-    EasyMock.replay( gatewayServices, hm, hms, environment, resolver );
-
-    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-rule" );
-    rule.pattern( "{*}://{host}:{*}/{**}?{**}" );
-    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
-    rewrite.template( "{*}://{$hostmap(host)}:{*}/{**}?{**}" );
-
-    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
-    rewriter.initialize( environment, descriptor );
-
-    Template input = Parser.parseLiteral( "test-scheme://test-inbound-host:42/test-path/test-file?test-name=test-value" );
-    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.IN, null );
-    //System.out.println( output );
-    assertThat( output, notNullValue() );
-    assertThat( output.getHost().getFirstValue().getPattern(), is( "test-inbound-rewritten-host" ) );
-  }
-
-  @Test
-  public void testHdfsUseCase() throws Exception {
-    URL configUrl = TestUtils.getResourceUrl( this.getClass(), "hdfs-hostmap.txt" );
-
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
-    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-internal-host" ) ).anyTimes();
-    EasyMock.replay( environment, resolver );
-
-    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-rule" );
-    rule.pattern( "{*}://{host}:{*}/{**}?{**}" );
-    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
-    rewrite.template( "{*}://test-static-host:{*}/{**}?server={$hostmap(host)}&{**}" );
-
-    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
-    rewriter.initialize( environment, descriptor );
-
-    Template input = Parser.parseLiteral(
-        "test-scheme://test-external-host:42/test-path/test-file?test-name-1=test-value-1&test-name-2=test-value-2" );
-    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.OUT, "test-rule" );
-    //System.out.println( output );
-    assertThat( output, notNullValue() );
-    assertThat( output.getHost().getFirstValue().getPattern(), is( "test-static-host" ) );
-    assertThat( output.getQuery().get( "server" ).getFirstValue().getPattern(), is( "test-external-host" ) );
-    assertThat( output.getQuery().get( "server" ).getValues().size(), is( 1 ) );
-    assertThat( output.getQuery().get( "test-name-1" ).getFirstValue().getPattern(), is( "test-value-1" ) );
-    assertThat( output.getQuery().get( "test-name-1" ).getValues().size(), is( 1 ) );
-    assertThat( output.getQuery().get( "test-name-2" ).getFirstValue().getPattern(), is( "test-value-2" ) );
-    assertThat( output.getQuery().get( "test-name-2" ).getValues().size(), is( 1 ) );
-    assertThat( output.getQuery().size(), is( 3 ) );
-  }
-
-  @Test
-  public void testQueryToPathRewriteWithFunction() throws Exception {
-    URL configUrl = TestUtils.getResourceUrl( this.getClass(), "hdfs-hostmap.txt" );
-
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
-    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-internal-host" ) ).anyTimes();
-    EasyMock.replay( environment, resolver );
-
-    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-rule" );
-    rule.pattern( "{*}://{host}:{*}/{**}?{qp1}&{qp2}&{**}" );
-    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
-    rewrite.template( "{*}://test-static-host:{*}/{qp1}/{qp2}/{**}?server={$hostmap(host)}&{**}" );
-
-    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
-    rewriter.initialize( environment, descriptor );
-
-    Template input = Parser.parseLiteral(
-        "test-scheme://test-external-host:42/test-path/test-file?qp1=qp1-val&qp2=qp2-val&test-name-1=test-value-1&test-name-2=test-value-2" );
-    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.OUT, "test-rule" );
-    //System.out.println( output );
-    assertThat( output, notNullValue() );
-    assertThat( output.getHost().getFirstValue().getPattern(), is( "test-static-host" ) );
-    assertThat( output.getQuery().get( "server" ).getFirstValue().getPattern(), is( "test-external-host" ) );
-    assertThat( output.getQuery().get( "server" ).getValues().size(), is( 1 ) );
-    assertThat( output.getQuery().get( "test-name-1" ).getFirstValue().getPattern(), is( "test-value-1" ) );
-    assertThat( output.getQuery().get( "test-name-1" ).getValues().size(), is( 1 ) );
-    assertThat( output.getQuery().get( "test-name-2" ).getFirstValue().getPattern(), is( "test-value-2" ) );
-    assertThat( output.getQuery().get( "test-name-2" ).getValues().size(), is( 1 ) );
-    assertThat( output.getQuery().size(), is( 3 ) );
-  }
-
-  @Test
-  public void testUnmappedUseCase() throws Exception {
-    URL configUrl = TestUtils.getResourceUrl( this.getClass(), "hostmap.txt" );
-
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
-    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-inbound-unmapped-host" ) ).anyTimes();
-    EasyMock.replay( environment, resolver );
-
-    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-rule" );
-    rule.pattern( "{*}://{host}:{*}/{**}?{**}" );
-    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
-    rewrite.template( "{*}://{$hostmap(host)}:{*}/{**}?{**}" );
-
-    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
-    rewriter.initialize( environment, descriptor );
-
-    Template input = Parser.parseLiteral(
-        "test-scheme://test-inbound-unmapped-host:42/test-path/test-file?test-name-1=test-value-1&test-name-2=test-value-2" );
-    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.IN, null );
-    //System.out.println( output );
-    assertThat( output, notNullValue() );
-    assertThat( output.getHost().getFirstValue().getPattern(), is( "test-inbound-unmapped-host" ) );
-  }
-
-  @Test
-  public void testInvalidFunctionNameUseCase() throws Exception {
-    URL configUrl = TestUtils.getResourceUrl( this.getClass(), "hostmap.txt" );
-
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
-    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-inbound-host" ) ).anyTimes();
-    EasyMock.replay( environment, resolver );
-
-    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-rule" );
-    rule.pattern( "{*}://{host}:{*}/{**}?{**}" );
-    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
-    rewrite.template( "{*}://{$invalid-function(host)}:{*}/{**}?{**}" );
-
-    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
-    rewriter.initialize( environment, descriptor );
-
-    Template input = Parser.parseLiteral( "test-scheme://test-inbound-host:42/test-path/test-file?test-name=test-value" );
-    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.IN, null );
-    //System.out.println( output );
-    assertThat( output, notNullValue() );
-    assertThat( output.getHost().getFirstValue().getPattern(), is( "$invalid-function(host)" ) );
-  }
-
-  @Test
-  public void testInvalidFunctionNameAndEmptyHostmapUseCase() throws Exception {
-    URL configUrl = TestUtils.getResourceUrl( this.getClass(), "empty-hostmap.txt" );
-
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
-    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-inbound-host" ) ).anyTimes();
-    EasyMock.replay( environment, resolver );
-
-    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-rule" );
-    rule.pattern( "{*}://{host}:{*}/{**}?{**}" );
-    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
-    rewrite.template( "{*}://{$invalid-function(host)}:{*}/{**}?{**}" );
-
-    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
-    rewriter.initialize( environment, descriptor );
-
-    Template input = Parser.parseLiteral( "test-scheme://test-inbound-host:42/test-path/test-file?test-name=test-value" );
-    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.IN, null );
-    //System.out.println( output );
-    assertThat( output, notNullValue() );
-    assertThat( output.getHost().getFirstValue().getPattern(), is( "$invalid-function(host)" ) );
-  }
-
-  @Test
-  public void testEmptyHostmapUseCase() throws Exception {
-    URL configUrl = TestUtils.getResourceUrl( this.getClass(), "empty-hostmap.txt" );
-
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
-    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-inbound-host" ) ).anyTimes();
-    EasyMock.replay( environment, resolver );
-
-    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-rule" );
-    rule.pattern( "{*}://{host}:{*}/{**}?{**}" );
-    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
-    rewrite.template( "{*}://{$hostmap(host)}:{*}/{**}?{**}" );
-
-    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
-    rewriter.initialize( environment, descriptor );
-
-    Template input = Parser.parseLiteral( "test-scheme://test-inbound-host:42/test-path/test-file?test-name=test-value" );
-    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.IN, null );
-    //System.out.println( output );
-    assertThat( output, notNullValue() );
-    assertThat( output.getHost().getFirstValue().getPattern(), is( "test-inbound-host" ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/knox/gateway/hostmap/api/HostmapFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/knox/gateway/hostmap/api/HostmapFunctionDescriptorTest.java b/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/knox/gateway/hostmap/api/HostmapFunctionDescriptorTest.java
new file mode 100644
index 0000000..f5b8b82
--- /dev/null
+++ b/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/knox/gateway/hostmap/api/HostmapFunctionDescriptorTest.java
@@ -0,0 +1,65 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.hostmap.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class HostmapFunctionDescriptorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof HostmapFunctionDescriptor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + UrlRewriteFunctionDescriptor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testGetAndSet() {
+    HostmapFunctionDescriptor descriptor = new HostmapFunctionDescriptor();
+
+    assertThat( descriptor.name(), is( "hostmap" ) );
+    assertThat( descriptor.config(), nullValue() );
+
+    // Test Fluent API
+    descriptor.config( "test-config-location-fluent" );
+    assertThat( descriptor.config(), is( "test-config-location-fluent" ) );
+    assertThat( descriptor.getConfig(), is( "test-config-location-fluent" ) );
+
+    // Test Bean API
+    descriptor.setConfig( "test-config-location-bean" );
+    assertThat( descriptor.config(), is( "test-config-location-bean" ) );
+    assertThat( descriptor.getConfig(), is( "test-config-location-bean" ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/knox/gateway/hostmap/impl/HostmapDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/knox/gateway/hostmap/impl/HostmapDeploymentContributorTest.java b/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/knox/gateway/hostmap/impl/HostmapDeploymentContributorTest.java
new file mode 100644
index 0000000..fc391b9
--- /dev/null
+++ b/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/knox/gateway/hostmap/impl/HostmapDeploymentContributorTest.java
@@ -0,0 +1,102 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.hostmap.impl;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributor;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteRulesDescriptorImpl;
+import org.apache.knox.gateway.hostmap.api.HostmapFunctionDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.easymock.EasyMock;
+import org.jboss.shrinkwrap.api.Node;
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.spec.WebArchive;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class HostmapDeploymentContributorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( ProviderDeploymentContributor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof HostmapDeploymentContributor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + HostmapDeploymentContributor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testDeployment() throws IOException {
+    WebArchive webArchive = ShrinkWrap.create( WebArchive.class, "test-acrhive" );
+
+    UrlRewriteRulesDescriptorImpl rewriteRules = new UrlRewriteRulesDescriptorImpl();
+
+    Map<String,String> providerParams = new HashMap<>();
+    providerParams.put( "test-host-external", "test-host-internal" );
+    Provider provider = new Provider();
+    provider.setEnabled( true );
+    provider.setName( "hostmap" );
+    provider.setParams(  providerParams );
+
+    DeploymentContext context = EasyMock.createNiceMock( DeploymentContext.class );
+    EasyMock.expect( context.getDescriptor( "rewrite" ) ).andReturn( rewriteRules ).anyTimes();
+    EasyMock.expect( context.getWebArchive() ).andReturn( webArchive ).anyTimes();
+    EasyMock.replay( context );
+
+    HostmapDeploymentContributor contributor = new HostmapDeploymentContributor();
+
+    assertThat( contributor.getRole(), is("hostmap") );
+    assertThat( contributor.getName(), is( "static" ) );
+
+    // Just make sure it doesn't blow up.
+    contributor.contributeFilter( null, null, null, null, null );
+
+    // Just make sure it doesn't blow up.
+    contributor.initializeContribution( context );
+
+    contributor.contributeProvider( context, provider );
+
+    HostmapFunctionDescriptor funcDesc = rewriteRules.getFunction( "hostmap" );
+    assertThat( funcDesc.config(), is( "/WEB-INF/hostmap.txt" ) );
+
+    Node node = webArchive.get( "/WEB-INF/hostmap.txt" );
+    String asset = IOUtils.toString( node.getAsset().openStream() );
+    assertThat( asset, containsString( "test-host-external=test-host-internal" ) );
+
+    // Just make sure it doesn't blow up.
+    contributor.finalizeContribution( context );
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest.java b/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest.java
new file mode 100644
index 0000000..92ec957
--- /dev/null
+++ b/gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest.java
@@ -0,0 +1,274 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.hostmap.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteProcessor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptorFactory;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteActionRewriteDescriptorExt;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.hostmap.HostMapper;
+import org.apache.knox.gateway.services.hostmap.HostMapperService;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+import org.apache.knox.gateway.util.urltemplate.Template;
+import org.apache.hadoop.test.TestUtils;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+import java.net.URL;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class HostmapFunctionProcessorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof HostmapFunctionProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + HostmapFunctionProcessor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testBasicUseCase() throws Exception {
+    URL configUrl = TestUtils.getResourceUrl( this.getClass(), "hostmap.txt" );
+
+    HostMapper hm = EasyMock.createNiceMock(HostMapper.class);
+    EasyMock.expect( hm.resolveInboundHostName("test-inbound-host")).andReturn( "test-inbound-rewritten-host" ).anyTimes();
+    
+    HostMapperService hms = EasyMock.createNiceMock( HostMapperService.class );
+
+    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( gatewayServices.getService( GatewayServices.HOST_MAPPING_SERVICE ) ).andReturn( hms ).anyTimes();
+
+
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( environment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();    
+    EasyMock.expect( environment.resolve( "cluster.name" ) ).andReturn( Arrays.asList( "test-cluster-name" ) ).anyTimes();
+    EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
+    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
+    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-inbound-host" ) ).anyTimes();
+    EasyMock.replay( gatewayServices, hm, hms, environment, resolver );
+
+    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-rule" );
+    rule.pattern( "{*}://{host}:{*}/{**}?{**}" );
+    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
+    rewrite.template( "{*}://{$hostmap(host)}:{*}/{**}?{**}" );
+
+    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
+    rewriter.initialize( environment, descriptor );
+
+    Template input = Parser.parseLiteral( "test-scheme://test-inbound-host:42/test-path/test-file?test-name=test-value" );
+    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.IN, null );
+    //System.out.println( output );
+    assertThat( output, notNullValue() );
+    assertThat( output.getHost().getFirstValue().getPattern(), is( "test-inbound-rewritten-host" ) );
+  }
+
+  @Test
+  public void testHdfsUseCase() throws Exception {
+    URL configUrl = TestUtils.getResourceUrl( this.getClass(), "hdfs-hostmap.txt" );
+
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
+    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
+    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-internal-host" ) ).anyTimes();
+    EasyMock.replay( environment, resolver );
+
+    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-rule" );
+    rule.pattern( "{*}://{host}:{*}/{**}?{**}" );
+    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
+    rewrite.template( "{*}://test-static-host:{*}/{**}?server={$hostmap(host)}&{**}" );
+
+    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
+    rewriter.initialize( environment, descriptor );
+
+    Template input = Parser.parseLiteral(
+        "test-scheme://test-external-host:42/test-path/test-file?test-name-1=test-value-1&test-name-2=test-value-2" );
+    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.OUT, "test-rule" );
+    //System.out.println( output );
+    assertThat( output, notNullValue() );
+    assertThat( output.getHost().getFirstValue().getPattern(), is( "test-static-host" ) );
+    assertThat( output.getQuery().get( "server" ).getFirstValue().getPattern(), is( "test-external-host" ) );
+    assertThat( output.getQuery().get( "server" ).getValues().size(), is( 1 ) );
+    assertThat( output.getQuery().get( "test-name-1" ).getFirstValue().getPattern(), is( "test-value-1" ) );
+    assertThat( output.getQuery().get( "test-name-1" ).getValues().size(), is( 1 ) );
+    assertThat( output.getQuery().get( "test-name-2" ).getFirstValue().getPattern(), is( "test-value-2" ) );
+    assertThat( output.getQuery().get( "test-name-2" ).getValues().size(), is( 1 ) );
+    assertThat( output.getQuery().size(), is( 3 ) );
+  }
+
+  @Test
+  public void testQueryToPathRewriteWithFunction() throws Exception {
+    URL configUrl = TestUtils.getResourceUrl( this.getClass(), "hdfs-hostmap.txt" );
+
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
+    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
+    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-internal-host" ) ).anyTimes();
+    EasyMock.replay( environment, resolver );
+
+    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-rule" );
+    rule.pattern( "{*}://{host}:{*}/{**}?{qp1}&{qp2}&{**}" );
+    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
+    rewrite.template( "{*}://test-static-host:{*}/{qp1}/{qp2}/{**}?server={$hostmap(host)}&{**}" );
+
+    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
+    rewriter.initialize( environment, descriptor );
+
+    Template input = Parser.parseLiteral(
+        "test-scheme://test-external-host:42/test-path/test-file?qp1=qp1-val&qp2=qp2-val&test-name-1=test-value-1&test-name-2=test-value-2" );
+    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.OUT, "test-rule" );
+    //System.out.println( output );
+    assertThat( output, notNullValue() );
+    assertThat( output.getHost().getFirstValue().getPattern(), is( "test-static-host" ) );
+    assertThat( output.getQuery().get( "server" ).getFirstValue().getPattern(), is( "test-external-host" ) );
+    assertThat( output.getQuery().get( "server" ).getValues().size(), is( 1 ) );
+    assertThat( output.getQuery().get( "test-name-1" ).getFirstValue().getPattern(), is( "test-value-1" ) );
+    assertThat( output.getQuery().get( "test-name-1" ).getValues().size(), is( 1 ) );
+    assertThat( output.getQuery().get( "test-name-2" ).getFirstValue().getPattern(), is( "test-value-2" ) );
+    assertThat( output.getQuery().get( "test-name-2" ).getValues().size(), is( 1 ) );
+    assertThat( output.getQuery().size(), is( 3 ) );
+  }
+
+  @Test
+  public void testUnmappedUseCase() throws Exception {
+    URL configUrl = TestUtils.getResourceUrl( this.getClass(), "hostmap.txt" );
+
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
+    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
+    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-inbound-unmapped-host" ) ).anyTimes();
+    EasyMock.replay( environment, resolver );
+
+    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-rule" );
+    rule.pattern( "{*}://{host}:{*}/{**}?{**}" );
+    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
+    rewrite.template( "{*}://{$hostmap(host)}:{*}/{**}?{**}" );
+
+    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
+    rewriter.initialize( environment, descriptor );
+
+    Template input = Parser.parseLiteral(
+        "test-scheme://test-inbound-unmapped-host:42/test-path/test-file?test-name-1=test-value-1&test-name-2=test-value-2" );
+    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.IN, null );
+    //System.out.println( output );
+    assertThat( output, notNullValue() );
+    assertThat( output.getHost().getFirstValue().getPattern(), is( "test-inbound-unmapped-host" ) );
+  }
+
+  @Test
+  public void testInvalidFunctionNameUseCase() throws Exception {
+    URL configUrl = TestUtils.getResourceUrl( this.getClass(), "hostmap.txt" );
+
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
+    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
+    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-inbound-host" ) ).anyTimes();
+    EasyMock.replay( environment, resolver );
+
+    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-rule" );
+    rule.pattern( "{*}://{host}:{*}/{**}?{**}" );
+    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
+    rewrite.template( "{*}://{$invalid-function(host)}:{*}/{**}?{**}" );
+
+    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
+    rewriter.initialize( environment, descriptor );
+
+    Template input = Parser.parseLiteral( "test-scheme://test-inbound-host:42/test-path/test-file?test-name=test-value" );
+    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.IN, null );
+    //System.out.println( output );
+    assertThat( output, notNullValue() );
+    assertThat( output.getHost().getFirstValue().getPattern(), is( "$invalid-function(host)" ) );
+  }
+
+  @Test
+  public void testInvalidFunctionNameAndEmptyHostmapUseCase() throws Exception {
+    URL configUrl = TestUtils.getResourceUrl( this.getClass(), "empty-hostmap.txt" );
+
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
+    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
+    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-inbound-host" ) ).anyTimes();
+    EasyMock.replay( environment, resolver );
+
+    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-rule" );
+    rule.pattern( "{*}://{host}:{*}/{**}?{**}" );
+    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
+    rewrite.template( "{*}://{$invalid-function(host)}:{*}/{**}?{**}" );
+
+    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
+    rewriter.initialize( environment, descriptor );
+
+    Template input = Parser.parseLiteral( "test-scheme://test-inbound-host:42/test-path/test-file?test-name=test-value" );
+    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.IN, null );
+    //System.out.println( output );
+    assertThat( output, notNullValue() );
+    assertThat( output.getHost().getFirstValue().getPattern(), is( "$invalid-function(host)" ) );
+  }
+
+  @Test
+  public void testEmptyHostmapUseCase() throws Exception {
+    URL configUrl = TestUtils.getResourceUrl( this.getClass(), "empty-hostmap.txt" );
+
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
+    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
+    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-inbound-host" ) ).anyTimes();
+    EasyMock.replay( environment, resolver );
+
+    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-rule" );
+    rule.pattern( "{*}://{host}:{*}/{**}?{**}" );
+    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
+    rewrite.template( "{*}://{$hostmap(host)}:{*}/{**}?{**}" );
+
+    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
+    rewriter.initialize( environment, descriptor );
+
+    Template input = Parser.parseLiteral( "test-scheme://test-inbound-host:42/test-path/test-file?test-name=test-value" );
+    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.IN, null );
+    //System.out.println( output );
+    assertThat( output, notNullValue() );
+    assertThat( output.getHost().getFirstValue().getPattern(), is( "test-inbound-host" ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest/empty-hostmap.txt
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest/empty-hostmap.txt b/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest/empty-hostmap.txt
deleted file mode 100644
index 635f0d9..0000000
--- a/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest/empty-hostmap.txt
+++ /dev/null
@@ -1,15 +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.

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest/hdfs-hostmap.txt
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest/hdfs-hostmap.txt b/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest/hdfs-hostmap.txt
deleted file mode 100644
index 38eb607..0000000
--- a/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest/hdfs-hostmap.txt
+++ /dev/null
@@ -1,17 +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.
-
-test-external-host=test-inbound-internal-host
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest/hostmap.txt
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest/hostmap.txt b/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest/hostmap.txt
deleted file mode 100644
index 576cac4..0000000
--- a/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/hadoop/gateway/hostmap/impl/HostmapFunctionProcessorTest/hostmap.txt
+++ /dev/null
@@ -1,17 +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.
-
-test-inbound-host=test-inbound-rewritten-host
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest/empty-hostmap.txt
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest/empty-hostmap.txt b/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest/empty-hostmap.txt
new file mode 100644
index 0000000..635f0d9
--- /dev/null
+++ b/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest/empty-hostmap.txt
@@ -0,0 +1,15 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest/hdfs-hostmap.txt
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest/hdfs-hostmap.txt b/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest/hdfs-hostmap.txt
new file mode 100644
index 0000000..38eb607
--- /dev/null
+++ b/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest/hdfs-hostmap.txt
@@ -0,0 +1,17 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+test-external-host=test-inbound-internal-host
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest/hostmap.txt
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest/hostmap.txt b/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest/hostmap.txt
new file mode 100644
index 0000000..576cac4
--- /dev/null
+++ b/gateway-provider-rewrite-func-hostmap-static/src/test/resources/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest/hostmap.txt
@@ -0,0 +1,17 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+test-inbound-host=test-inbound-rewritten-host
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/hadoop/gateway/inboundurl/api/InboundUrlFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/hadoop/gateway/inboundurl/api/InboundUrlFunctionDescriptor.java b/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/hadoop/gateway/inboundurl/api/InboundUrlFunctionDescriptor.java
deleted file mode 100644
index 5ba2e11..0000000
--- a/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/hadoop/gateway/inboundurl/api/InboundUrlFunctionDescriptor.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.inboundurl.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-public class InboundUrlFunctionDescriptor implements UrlRewriteFunctionDescriptor<InboundUrlFunctionDescriptor> {
-
-  public static final String FUNCTION_NAME = "inboundurl";
-
-  @Override
-  public String name() {
-    return FUNCTION_NAME;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/hadoop/gateway/inboundurl/impl/InboundUrlFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/hadoop/gateway/inboundurl/impl/InboundUrlFunctionProcessor.java b/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/hadoop/gateway/inboundurl/impl/InboundUrlFunctionProcessor.java
deleted file mode 100644
index e26d81e..0000000
--- a/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/hadoop/gateway/inboundurl/impl/InboundUrlFunctionProcessor.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.hadoop.gateway.inboundurl.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.inboundurl.api.InboundUrlFunctionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteResponse;
-
-import java.util.Collections;
-import java.util.List;
-
-public class InboundUrlFunctionProcessor
-    implements UrlRewriteFunctionProcessor<InboundUrlFunctionDescriptor> {
-
-  @Override
-  public String name() {
-    return InboundUrlFunctionDescriptor.FUNCTION_NAME;
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, InboundUrlFunctionDescriptor descriptor ) throws Exception {
-  }
-
-  @Override
-  public void destroy() throws Exception {
-  }
-
-  @Override
-  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
-      if( parameters == null || parameters.size() == 0 ) {
-        return Collections.emptyList();
-      } else {
-        switch( context.getDirection() ) {
-          case IN:
-            return Collections.emptyList();
-          case OUT:
-            return context.getParameters().resolve( UrlRewriteResponse.INBOUND_QUERY_PARAM_PREFIX + parameters.get( 0 ));
-          default:
-            return Collections.emptyList();
-        }
-      }
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/knox/gateway/inboundurl/api/InboundUrlFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/knox/gateway/inboundurl/api/InboundUrlFunctionDescriptor.java b/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/knox/gateway/inboundurl/api/InboundUrlFunctionDescriptor.java
new file mode 100644
index 0000000..a05e3ab
--- /dev/null
+++ b/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/knox/gateway/inboundurl/api/InboundUrlFunctionDescriptor.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.inboundurl.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+public class InboundUrlFunctionDescriptor implements UrlRewriteFunctionDescriptor<InboundUrlFunctionDescriptor> {
+
+  public static final String FUNCTION_NAME = "inboundurl";
+
+  @Override
+  public String name() {
+    return FUNCTION_NAME;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/knox/gateway/inboundurl/impl/InboundUrlFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/knox/gateway/inboundurl/impl/InboundUrlFunctionProcessor.java b/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/knox/gateway/inboundurl/impl/InboundUrlFunctionProcessor.java
new file mode 100644
index 0000000..a15d36c
--- /dev/null
+++ b/gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/knox/gateway/inboundurl/impl/InboundUrlFunctionProcessor.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.knox.gateway.inboundurl.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.inboundurl.api.InboundUrlFunctionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteResponse;
+
+import java.util.Collections;
+import java.util.List;
+
+public class InboundUrlFunctionProcessor
+    implements UrlRewriteFunctionProcessor<InboundUrlFunctionDescriptor> {
+
+  @Override
+  public String name() {
+    return InboundUrlFunctionDescriptor.FUNCTION_NAME;
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, InboundUrlFunctionDescriptor descriptor ) throws Exception {
+  }
+
+  @Override
+  public void destroy() throws Exception {
+  }
+
+  @Override
+  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
+      if( parameters == null || parameters.size() == 0 ) {
+        return Collections.emptyList();
+      } else {
+        switch( context.getDirection() ) {
+          case IN:
+            return Collections.emptyList();
+          case OUT:
+            return context.getParameters().resolve( UrlRewriteResponse.INBOUND_QUERY_PARAM_PREFIX + parameters.get( 0 ));
+          default:
+            return Collections.emptyList();
+        }
+      }
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor b/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
deleted file mode 100644
index 42aa9f6..0000000
--- a/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.inboundurl.api.InboundUrlFunctionDescriptor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor b/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
deleted file mode 100644
index c9f09b6..0000000
--- a/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.inboundurl.impl.InboundUrlFunctionProcessor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor b/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
new file mode 100644
index 0000000..b5ce6ed
--- /dev/null
+++ b/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.inboundurl.api.InboundUrlFunctionDescriptor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor b/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
new file mode 100644
index 0000000..87d3db8
--- /dev/null
+++ b/gateway-provider-rewrite-func-inbound-query-param/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.inboundurl.impl.InboundUrlFunctionProcessor


[51/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
KNOX-998 - Refactoring save 1


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

Branch: refs/heads/KNOX-998-Package_Restructuring
Commit: af9b0c3d1ce18f787ccf5c5d2055c2da98e70711
Parents: 1159135
Author: Sandeep More <mo...@apache.org>
Authored: Thu Aug 24 10:56:35 2017 -0400
Committer: Sandeep More <mo...@apache.org>
Committed: Thu Aug 24 10:56:35 2017 -0400

----------------------------------------------------------------------
 .../applications/knoxauth/app/redirecting.jsp   |     6 +-
 gateway-demo-ldap-launcher/pom.xml              |     2 +-
 .../security/ldap/BaseDirectoryService.java     |  2323 ----
 .../ldap/BaseDirectoryServiceFactory.java       |   290 -
 .../security/ldap/SimpleDirectoryService.java   |    29 -
 .../ldap/SimpleDirectoryServiceFactory.java     |    34 -
 .../ldap/SimpleLdapDirectoryServer.java         |   124 -
 .../security/ldap/BaseDirectoryService.java     |  2323 ++++
 .../ldap/BaseDirectoryServiceFactory.java       |   290 +
 .../security/ldap/SimpleDirectoryService.java   |    29 +
 .../ldap/SimpleDirectoryServiceFactory.java     |    34 +
 .../ldap/SimpleLdapDirectoryServer.java         |   124 +
 .../security/ldap/SimpleLdapServerTest.java     |    93 -
 .../security/ldap/SimpleLdapServerTest.java     |    91 +
 .../loggers/log4j/Log4jMessageLogger.java       |    87 -
 .../log4j/Log4jMessageLoggerFactory.java        |    31 -
 .../loggers/log4j/Log4jMessageLogger.java       |    87 +
 .../log4j/Log4jMessageLoggerFactory.java        |    31 +
 ...p.gateway.i18n.messages.MessageLoggerFactory |    19 -
 ...x.gateway.i18n.messages.MessageLoggerFactory |    19 +
 .../log4j/Log4jMessageLoggerFactoryTest.java    |    45 -
 .../log4j/Log4jMessageLoggerFactoryTest.java    |    45 +
 .../loggers/sl4j/Sl4jMessageLogger.java         |    82 -
 .../loggers/sl4j/Sl4jMessageLoggerFactory.java  |    31 -
 .../loggers/sl4j/Sl4jMessageLogger.java         |    82 +
 .../loggers/sl4j/Sl4jMessageLoggerFactory.java  |    31 +
 ...p.gateway.i18n.messages.MessageLoggerFactory |    19 -
 ...x.gateway.i18n.messages.MessageLoggerFactory |    19 +
 .../sl4j/Sl4jMessageLoggerFactoryTest.java      |    45 -
 .../sl4j/Sl4jMessageLoggerFactoryTest.java      |    45 +
 .../hadoop/gateway/i18n/messages/Message.java   |    36 -
 .../gateway/i18n/messages/MessageLevel.java     |    25 -
 .../gateway/i18n/messages/MessageLogger.java    |    29 -
 .../i18n/messages/MessageLoggerFactory.java     |    27 -
 .../hadoop/gateway/i18n/messages/Messages.java  |    37 -
 .../gateway/i18n/messages/MessagesFactory.java  |    65 -
 .../gateway/i18n/messages/MessagesInvoker.java  |   173 -
 .../gateway/i18n/messages/StackTrace.java       |    32 -
 .../messages/loggers/jdk/JdkMessageLogger.java  |    67 -
 .../loggers/jdk/JdkMessageLoggerFactory.java    |    35 -
 .../loggers/sout/SoutMessageLogger.java         |    56 -
 .../loggers/sout/SoutMessageLoggerFactory.java  |    56 -
 .../loggers/test/TestMessageLogger.java         |    55 -
 .../loggers/test/TestMessageLoggerFactory.java  |    55 -
 .../loggers/test/TestMessageRecord.java         |    67 -
 .../hadoop/gateway/i18n/resources/Resource.java |    33 -
 .../gateway/i18n/resources/Resources.java       |    33 -
 .../i18n/resources/ResourcesFactory.java        |    46 -
 .../i18n/resources/ResourcesInvoker.java        |   162 -
 .../knox/gateway/i18n/messages/Message.java     |    36 +
 .../gateway/i18n/messages/MessageLevel.java     |    25 +
 .../gateway/i18n/messages/MessageLogger.java    |    29 +
 .../i18n/messages/MessageLoggerFactory.java     |    27 +
 .../knox/gateway/i18n/messages/Messages.java    |    37 +
 .../gateway/i18n/messages/MessagesFactory.java  |    63 +
 .../gateway/i18n/messages/MessagesInvoker.java  |   173 +
 .../knox/gateway/i18n/messages/StackTrace.java  |    32 +
 .../messages/loggers/jdk/JdkMessageLogger.java  |    67 +
 .../loggers/jdk/JdkMessageLoggerFactory.java    |    35 +
 .../loggers/sout/SoutMessageLogger.java         |    56 +
 .../loggers/sout/SoutMessageLoggerFactory.java  |    55 +
 .../loggers/test/TestMessageLogger.java         |    55 +
 .../loggers/test/TestMessageLoggerFactory.java  |    55 +
 .../loggers/test/TestMessageRecord.java         |    67 +
 .../knox/gateway/i18n/resources/Resource.java   |    33 +
 .../knox/gateway/i18n/resources/Resources.java  |    33 +
 .../i18n/resources/ResourcesFactory.java        |    46 +
 .../i18n/resources/ResourcesInvoker.java        |   162 +
 .../gateway/i18n/messages/MessagesTest.java     |    54 -
 .../i18n/messages/MessagesTestSubject.java      |    46 -
 .../gateway/i18n/resources/ResourcesTest.java   |   121 -
 .../ResourcesTestFormattingSubject.java         |    47 -
 .../resources/ResourcesTestLocaleSubject.java   |    29 -
 .../resources/ResourcesTestNamedSubject.java    |    29 -
 .../gateway/i18n/messages/MessagesTest.java     |    54 +
 .../i18n/messages/MessagesTestSubject.java      |    43 +
 .../gateway/i18n/resources/ResourcesTest.java   |   121 +
 .../ResourcesTestFormattingSubject.java         |    47 +
 .../resources/ResourcesTestLocaleSubject.java   |    29 +
 .../resources/ResourcesTestNamedSubject.java    |    29 +
 ...p.gateway.i18n.messages.MessageLoggerFactory |    17 -
 ...x.gateway.i18n.messages.MessageLoggerFactory |    17 +
 .../i18n/resources/NamedBundle_en_CA.properties |    19 -
 .../ResourcesTestLocaleSubject.properties       |    14 -
 .../ResourcesTestLocaleSubject_en.properties    |    19 -
 .../ResourcesTestLocaleSubject_en_GB.properties |    19 -
 .../ResourcesTestLocaleSubject_en_US.properties |    19 -
 .../i18n/resources/NamedBundle_en_CA.properties |    19 +
 .../ResourcesTestLocaleSubject.properties       |    14 +
 .../ResourcesTestLocaleSubject_en.properties    |    19 +
 .../ResourcesTestLocaleSubject_en_GB.properties |    19 +
 .../ResourcesTestLocaleSubject_en_US.properties |    19 +
 .../deploy/HaProviderDeploymentContributor.java |    98 -
 .../gateway/ha/dispatch/DefaultHaDispatch.java  |   130 -
 .../ha/dispatch/i18n/HaDispatchMessages.java    |    41 -
 .../gateway/ha/provider/HaDescriptor.java       |    34 -
 .../hadoop/gateway/ha/provider/HaProvider.java  |    67 -
 .../gateway/ha/provider/HaServiceConfig.java    |    53 -
 .../ha/provider/HaServletContextListener.java   |   116 -
 .../hadoop/gateway/ha/provider/URLManager.java  |    37 -
 .../gateway/ha/provider/URLManagerLoader.java   |    43 -
 .../ha/provider/impl/DefaultHaDescriptor.java   |    71 -
 .../ha/provider/impl/DefaultHaProvider.java     |    96 -
 .../provider/impl/DefaultHaServiceConfig.java   |   124 -
 .../ha/provider/impl/DefaultURLManager.java     |   101 -
 .../provider/impl/HS2ZookeeperURLManager.java   |   145 -
 .../ha/provider/impl/HaDescriptorConstants.java |    49 -
 .../ha/provider/impl/HaDescriptorFactory.java   |    94 -
 .../ha/provider/impl/HaDescriptorManager.java   |   109 -
 .../provider/impl/HaServiceConfigConstants.java |    50 -
 .../ha/provider/impl/i18n/HaMessages.java       |    45 -
 .../deploy/HaProviderDeploymentContributor.java |    98 +
 .../gateway/ha/dispatch/DefaultHaDispatch.java  |   130 +
 .../ha/dispatch/i18n/HaDispatchMessages.java    |    41 +
 .../knox/gateway/ha/provider/HaDescriptor.java  |    34 +
 .../knox/gateway/ha/provider/HaProvider.java    |    67 +
 .../gateway/ha/provider/HaServiceConfig.java    |    53 +
 .../ha/provider/HaServletContextListener.java   |   116 +
 .../knox/gateway/ha/provider/URLManager.java    |    37 +
 .../gateway/ha/provider/URLManagerLoader.java   |    43 +
 .../ha/provider/impl/DefaultHaDescriptor.java   |    71 +
 .../ha/provider/impl/DefaultHaProvider.java     |    96 +
 .../provider/impl/DefaultHaServiceConfig.java   |   124 +
 .../ha/provider/impl/DefaultURLManager.java     |   100 +
 .../provider/impl/HS2ZookeeperURLManager.java   |   145 +
 .../ha/provider/impl/HaDescriptorConstants.java |    49 +
 .../ha/provider/impl/HaDescriptorFactory.java   |    94 +
 .../ha/provider/impl/HaDescriptorManager.java   |   109 +
 .../provider/impl/HaServiceConfigConstants.java |    50 +
 .../ha/provider/impl/i18n/HaMessages.java       |    45 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ...apache.hadoop.gateway.ha.provider.URLManager |    19 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 ...g.apache.knox.gateway.ha.provider.URLManager |    19 +
 .../HaProviderDeploymentContributorTest.java    |    46 -
 .../ha/dispatch/DefaultHaDispatchTest.java      |   106 -
 .../ha/provider/impl/DefaultHaProviderTest.java |    85 -
 .../ha/provider/impl/DefaultURLManagerTest.java |    73 -
 .../impl/HS2ZookeeperURLManagerTest.java        |   134 -
 .../provider/impl/HaDescriptorFactoryTest.java  |    53 -
 .../provider/impl/HaDescriptorManagerTest.java  |    89 -
 .../ha/provider/impl/MockURLManager.java        |    40 -
 .../ha/provider/impl/URLManagerLoaderTest.java  |    48 -
 .../HaProviderDeploymentContributorTest.java    |    46 +
 .../ha/dispatch/DefaultHaDispatchTest.java      |   106 +
 .../ha/provider/impl/DefaultHaProviderTest.java |    85 +
 .../ha/provider/impl/DefaultURLManagerTest.java |    73 +
 .../impl/HS2ZookeeperURLManagerTest.java        |   133 +
 .../provider/impl/HaDescriptorFactoryTest.java  |    53 +
 .../provider/impl/HaDescriptorManagerTest.java  |    89 +
 .../ha/provider/impl/MockURLManager.java        |    40 +
 .../ha/provider/impl/URLManagerLoaderTest.java  |    48 +
 ...apache.hadoop.gateway.ha.provider.URLManager |    19 -
 ...g.apache.knox.gateway.ha.provider.URLManager |    19 +
 .../gateway/IdentityAsserterMessages.java       |    31 -
 ...ctIdentityAsserterDeploymentContributor.java |    60 -
 .../filter/AbstractIdentityAssertionFilter.java |   198 -
 .../filter/CommonIdentityAssertionFilter.java   |   144 -
 ...entityAsserterHttpServletRequestWrapper.java |   294 -
 .../function/UsernameFunctionDescriptor.java    |    31 -
 .../function/UsernameFunctionProcessor.java     |    74 -
 .../knox/gateway/IdentityAsserterMessages.java  |    31 +
 ...ctIdentityAsserterDeploymentContributor.java |    61 +
 .../filter/AbstractIdentityAssertionFilter.java |   198 +
 .../filter/CommonIdentityAssertionFilter.java   |   143 +
 ...entityAsserterHttpServletRequestWrapper.java |   295 +
 .../function/UsernameFunctionDescriptor.java    |    32 +
 .../function/UsernameFunctionProcessor.java     |    72 +
 ...gateway.deploy.ProviderDeploymentContributor |    18 -
 ...ter.rewrite.api.UrlRewriteFunctionDescriptor |    19 -
 ...lter.rewrite.spi.UrlRewriteFunctionProcessor |    19 -
 ...gateway.deploy.ProviderDeploymentContributor |    18 +
 ...ter.rewrite.api.UrlRewriteFunctionDescriptor |    19 +
 ...lter.rewrite.spi.UrlRewriteFunctionProcessor |    19 +
 .../CommonIdentityAssertionFilterTest.java      |   130 -
 ...yAssertionHttpServletRequestWrapperTest.java |   279 -
 .../UsernameFunctionDescriptorTest.java         |    52 -
 .../function/UsernameFunctionProcessorTest.java |   248 -
 .../CommonIdentityAssertionFilterTest.java      |   130 +
 ...yAssertionHttpServletRequestWrapperTest.java |   279 +
 .../UsernameFunctionDescriptorTest.java         |    52 +
 .../function/UsernameFunctionProcessorTest.java |   247 +
 .../UsernameFunctionProcessorTest/rewrite.xml   |    24 -
 .../UsernameFunctionProcessorTest/rewrite.xml   |    24 +
 .../gateway/ConcatIdentityAsserterMessages.java |    31 -
 ...atIdentityAsserterDeploymentContributor.java |    32 -
 .../filter/ConcatIdentityAssertionFilter.java   |    61 -
 .../gateway/ConcatIdentityAsserterMessages.java |    31 +
 ...atIdentityAsserterDeploymentContributor.java |    32 +
 .../filter/ConcatIdentityAssertionFilter.java   |    61 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 ...entityAsserterDeploymentContributorTest.java |    45 -
 .../ConcatIdentityAssertionFilterTest.java      |    97 -
 ...entityAsserterDeploymentContributorTest.java |    44 +
 .../ConcatIdentityAssertionFilterTest.java      |    97 +
 ...adoopGroupProviderDeploymentContributor.java |    64 -
 .../filter/HadoopGroupProviderFilter.java       |   121 -
 .../filter/HadoopGroupProviderMessages.java     |    43 -
 ...adoopGroupProviderDeploymentContributor.java |    64 +
 .../filter/HadoopGroupProviderFilter.java       |   121 +
 .../filter/HadoopGroupProviderMessages.java     |    43 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 ...pGroupProviderDeploymentContributorTest.java |    54 -
 .../filter/HadoopGroupProviderFilterTest.java   |   218 -
 .../hadoop/groups/filter/HadoopGroupsTest.java  |    85 -
 ...pGroupProviderDeploymentContributorTest.java |    54 +
 .../filter/HadoopGroupProviderFilterTest.java   |   218 +
 .../hadoop/groups/filter/HadoopGroupsTest.java  |    85 +
 .../gateway/IdentityAsserterMessages.java       |    31 -
 ...ltIdentityAsserterDeploymentContributor.java |    32 -
 .../IdentityAsserterDeploymentContributor.java  |    58 -
 .../filter/IdentityAsserterFilter.java          |    42 -
 .../knox/gateway/IdentityAsserterMessages.java  |    31 +
 ...ltIdentityAsserterDeploymentContributor.java |    32 +
 .../IdentityAsserterDeploymentContributor.java  |    52 +
 .../filter/IdentityAsserterFilter.java          |    42 +
 ...gateway.deploy.ProviderDeploymentContributor |    20 -
 ...gateway.deploy.ProviderDeploymentContributor |    20 +
 .../DefaultIdentityAssertionFilterTest.java     |   173 -
 .../DefaultIdentityAssertionFilterTest.java     |   173 +
 .../UsernameFunctionProcessorTest/rewrite.xml   |    24 -
 .../UsernameFunctionProcessorTest/rewrite.xml   |    24 +
 ...exIdentityAsserterDeploymentContributor.java |    33 -
 .../filter/RegexIdentityAssertionFilter.java    |    87 -
 .../regex/filter/RegexTemplate.java             |    75 -
 ...exIdentityAsserterDeploymentContributor.java |    34 +
 .../filter/RegexIdentityAssertionFilter.java    |    88 +
 .../regex/filter/RegexTemplate.java             |    75 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 ...entityAsserterDeploymentContributorTest.java |    44 -
 .../RegexIdentityAssertionFilterTest.java       |   130 -
 .../regex/filter/RegexTemplateTest.java         |    72 -
 ...entityAsserterDeploymentContributorTest.java |    44 +
 .../RegexIdentityAssertionFilterTest.java       |   130 +
 .../regex/filter/RegexTemplateTest.java         |    72 +
 ...seIdentityAsserterDeploymentContributor.java |    32 -
 .../SwitchCaseIdentityAssertionFilter.java      |    97 -
 ...seIdentityAsserterDeploymentContributor.java |    33 +
 .../SwitchCaseIdentityAssertionFilter.java      |    98 +
 ...gateway.deploy.ProviderDeploymentContributor |    18 -
 ...gateway.deploy.ProviderDeploymentContributor |    18 +
 ...entityAsserterDeploymentContributorTest.java |    44 -
 .../SwitchCaseIdentityAssertionFilterTest.java  |   242 -
 ...entityAsserterDeploymentContributorTest.java |    44 +
 .../SwitchCaseIdentityAssertionFilterTest.java  |   242 +
 .../JerseyDispatchDeploymentContributor.java    |    55 -
 .../JerseyServiceDeploymentContributorBase.java |    67 -
 .../JerseyDispatchDeploymentContributor.java    |    56 +
 .../JerseyServiceDeploymentContributorBase.java |    67 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 .../jersey/JerseyDeploymentContributorTest.java |   259 -
 .../jersey/JerseyDeploymentContributorTest.java |   259 +
 .../hostmap/api/HostmapFunctionDescriptor.java  |    50 -
 .../impl/HostmapDeploymentContributor.java      |    99 -
 .../hostmap/impl/HostmapFunctionProcessor.java  |    91 -
 .../hostmap/api/HostmapFunctionDescriptor.java  |    51 +
 .../impl/HostmapDeploymentContributor.java      |    99 +
 .../hostmap/impl/HostmapFunctionProcessor.java  |    92 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ...ter.rewrite.api.UrlRewriteFunctionDescriptor |    19 -
 ...lter.rewrite.spi.UrlRewriteFunctionProcessor |    19 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 ...ter.rewrite.api.UrlRewriteFunctionDescriptor |    19 +
 ...lter.rewrite.spi.UrlRewriteFunctionProcessor |    19 +
 .../api/HostmapFunctionDescriptorTest.java      |    65 -
 .../impl/HostmapDeploymentContributorTest.java  |   102 -
 .../impl/HostmapFunctionProcessorTest.java      |   274 -
 .../api/HostmapFunctionDescriptorTest.java      |    65 +
 .../impl/HostmapDeploymentContributorTest.java  |   102 +
 .../impl/HostmapFunctionProcessorTest.java      |   274 +
 .../empty-hostmap.txt                           |    15 -
 .../hdfs-hostmap.txt                            |    17 -
 .../HostmapFunctionProcessorTest/hostmap.txt    |    17 -
 .../empty-hostmap.txt                           |    15 +
 .../hdfs-hostmap.txt                            |    17 +
 .../HostmapFunctionProcessorTest/hostmap.txt    |    17 +
 .../api/InboundUrlFunctionDescriptor.java       |    31 -
 .../impl/InboundUrlFunctionProcessor.java       |    60 -
 .../api/InboundUrlFunctionDescriptor.java       |    31 +
 .../impl/InboundUrlFunctionProcessor.java       |    60 +
 ...ter.rewrite.api.UrlRewriteFunctionDescriptor |    19 -
 ...lter.rewrite.spi.UrlRewriteFunctionProcessor |    19 -
 ...ter.rewrite.api.UrlRewriteFunctionDescriptor |    19 +
 ...lter.rewrite.spi.UrlRewriteFunctionProcessor |    19 +
 .../api/InboundUrlFunctionDescriptorTest.java   |    48 -
 .../impl/InboundUrlFunctionProcessorTest.java   |   140 -
 .../api/InboundUrlFunctionDescriptorTest.java   |    48 +
 .../impl/InboundUrlFunctionProcessorTest.java   |   140 +
 .../api/ServiceAddressFunctionDescriptor.java   |    31 -
 .../api/ServiceHostFunctionDescriptor.java      |    31 -
 .../ServiceMappedAddressFunctionDescriptor.java |    31 -
 .../ServiceMappedHostFunctionDescriptor.java    |    31 -
 .../api/ServiceMappedUrlFunctionDescriptor.java |    31 -
 .../api/ServicePathFunctionDescriptor.java      |    31 -
 .../api/ServicePortFunctionDescriptor.java      |    31 -
 .../api/ServiceSchemeFunctionDescriptor.java    |    31 -
 .../api/ServiceUrlFunctionDescriptor.java       |    31 -
 .../impl/ServiceAddressFunctionProcessor.java   |    84 -
 .../impl/ServiceHostFunctionProcessor.java      |    60 -
 .../ServiceMappedAddressFunctionProcessor.java  |   110 -
 .../ServiceMappedHostFunctionProcessor.java     |    87 -
 .../impl/ServiceMappedUrlFunctionProcessor.java |    90 -
 .../impl/ServicePathFunctionProcessor.java      |    72 -
 .../impl/ServicePortFunctionProcessor.java      |    60 -
 .../ServiceRegistryFunctionProcessorBase.java   |    81 -
 .../impl/ServiceSchemeFunctionProcessor.java    |    60 -
 .../impl/ServiceUrlFunctionProcessor.java       |    64 -
 .../api/ServiceAddressFunctionDescriptor.java   |    32 +
 .../api/ServiceHostFunctionDescriptor.java      |    32 +
 .../ServiceMappedAddressFunctionDescriptor.java |    31 +
 .../ServiceMappedHostFunctionDescriptor.java    |    32 +
 .../api/ServiceMappedUrlFunctionDescriptor.java |    32 +
 .../api/ServicePathFunctionDescriptor.java      |    31 +
 .../api/ServicePortFunctionDescriptor.java      |    32 +
 .../api/ServiceSchemeFunctionDescriptor.java    |    32 +
 .../api/ServiceUrlFunctionDescriptor.java       |    32 +
 .../impl/ServiceAddressFunctionProcessor.java   |    84 +
 .../impl/ServiceHostFunctionProcessor.java      |    60 +
 .../ServiceMappedAddressFunctionProcessor.java  |   109 +
 .../ServiceMappedHostFunctionProcessor.java     |    88 +
 .../impl/ServiceMappedUrlFunctionProcessor.java |    90 +
 .../impl/ServicePathFunctionProcessor.java      |    72 +
 .../impl/ServicePortFunctionProcessor.java      |    60 +
 .../ServiceRegistryFunctionProcessorBase.java   |    81 +
 .../impl/ServiceSchemeFunctionProcessor.java    |    60 +
 .../impl/ServiceUrlFunctionProcessor.java       |    64 +
 ...ter.rewrite.api.UrlRewriteFunctionDescriptor |    27 -
 ...lter.rewrite.spi.UrlRewriteFunctionProcessor |    27 -
 ...ter.rewrite.api.UrlRewriteFunctionDescriptor |    27 +
 ...lter.rewrite.spi.UrlRewriteFunctionProcessor |    27 +
 .../ServiceAddressFunctionDescriptorTest.java   |    52 -
 .../api/ServiceHostFunctionDescriptorTest.java  |    52 -
 .../api/ServicePathFunctionDescriptorTest.java  |    52 -
 .../api/ServicePortFunctionDescriptorTest.java  |    52 -
 .../ServiceSchemeFunctionDescriptorTest.java    |    52 -
 .../api/ServiceUrlFunctionDescriptorTest.java   |    52 -
 .../ServiceAddressFunctionProcessorTest.java    |   140 -
 .../impl/ServiceHostFunctionProcessorTest.java  |   141 -
 ...rviceMappedAddressFunctionProcessorTest.java |   153 -
 .../ServiceMappedHostFunctionProcessorTest.java |   153 -
 .../ServiceMappedUrlFunctionProcessorTest.java  |   154 -
 .../impl/ServicePathFunctionProcessorTest.java  |   140 -
 .../impl/ServicePortFunctionProcessorTest.java  |   140 -
 .../impl/ServiceRegistryFunctionsTest.java      |   226 -
 .../ServiceSchemeFunctionProcessorTest.java     |   140 -
 .../impl/ServiceUrlFunctionProcessorTest.java   |   153 -
 .../ServiceAddressFunctionDescriptorTest.java   |    52 +
 .../api/ServiceHostFunctionDescriptorTest.java  |    52 +
 .../api/ServicePathFunctionDescriptorTest.java  |    52 +
 .../api/ServicePortFunctionDescriptorTest.java  |    52 +
 .../ServiceSchemeFunctionDescriptorTest.java    |    52 +
 .../api/ServiceUrlFunctionDescriptorTest.java   |    52 +
 .../ServiceAddressFunctionProcessorTest.java    |   140 +
 .../impl/ServiceHostFunctionProcessorTest.java  |   141 +
 ...rviceMappedAddressFunctionProcessorTest.java |   153 +
 .../ServiceMappedHostFunctionProcessorTest.java |   153 +
 .../ServiceMappedUrlFunctionProcessorTest.java  |   154 +
 .../impl/ServicePathFunctionProcessorTest.java  |   140 +
 .../impl/ServicePortFunctionProcessorTest.java  |   140 +
 .../impl/ServiceRegistryFunctionsTest.java      |   225 +
 .../ServiceSchemeFunctionProcessorTest.java     |   140 +
 .../impl/ServiceUrlFunctionProcessorTest.java   |   153 +
 .../ServiceRegistryFunctionsTest/rewrite.xml    |   101 -
 .../test-expect-body.json                       |    11 -
 .../test-expect-body.xml                        |    40 -
 .../test-input-body.json                        |    11 -
 .../test-input-body.xml                         |    40 -
 .../ServiceRegistryFunctionsTest/rewrite.xml    |   101 +
 .../test-expect-body.json                       |    11 +
 .../test-expect-body.xml                        |    40 +
 .../test-input-body.json                        |    11 +
 .../test-input-body.xml                         |    40 +
 .../encrypturi/EncryptStepContextParams.java    |    47 -
 .../gateway/encrypturi/EncryptUriMessages.java  |    31 -
 .../encrypturi/api/DecryptUriDescriptor.java    |    39 -
 .../encrypturi/api/EncryptUriDescriptor.java    |    49 -
 .../encrypturi/impl/DecryptUriProcessor.java    |    89 -
 .../impl/EncryptUriDeploymentContributor.java   |    87 -
 .../encrypturi/impl/EncryptUriProcessor.java    |    85 -
 .../encrypturi/EncryptStepContextParams.java    |    47 +
 .../gateway/encrypturi/EncryptUriMessages.java  |    31 +
 .../encrypturi/api/DecryptUriDescriptor.java    |    39 +
 .../encrypturi/api/EncryptUriDescriptor.java    |    49 +
 .../encrypturi/impl/DecryptUriProcessor.java    |    90 +
 .../impl/EncryptUriDeploymentContributor.java   |    87 +
 .../encrypturi/impl/EncryptUriProcessor.java    |    86 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ....filter.rewrite.api.UrlRewriteStepDescriptor |    20 -
 ...y.filter.rewrite.spi.UrlRewriteStepProcessor |    20 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 ....filter.rewrite.api.UrlRewriteStepDescriptor |    20 +
 ...y.filter.rewrite.spi.UrlRewriteStepProcessor |    20 +
 .../api/DecryptUriDescriptorTest.java           |    55 -
 .../api/EncryptUriDescriptorTest.java           |    55 -
 .../impl/EncryptDecryptUriProcessorTest.java    |   157 -
 .../EncryptUriDeploymentContributorTest.java    |   105 -
 .../api/DecryptUriDescriptorTest.java           |    55 +
 .../api/EncryptUriDescriptorTest.java           |    55 +
 .../impl/EncryptDecryptUriProcessorTest.java    |   157 +
 .../EncryptUriDeploymentContributorTest.java    |   105 +
 .../SecureQueryDecodeDescriptor.java            |    38 -
 .../securequery/SecureQueryDecodeProcessor.java |    86 -
 .../SecureQueryDecryptDescriptor.java           |    38 -
 .../SecureQueryDecryptProcessor.java            |   119 -
 .../SecureQueryDeploymentContributor.java       |   113 -
 .../SecureQueryEncodeDescriptor.java            |    38 -
 .../securequery/SecureQueryEncodeProcessor.java |    77 -
 .../SecureQueryEncryptDescriptor.java           |    38 -
 .../SecureQueryEncryptProcessor.java            |    84 -
 .../securequery/SecureQueryMessages.java        |    31 -
 .../SecureQueryDecodeDescriptor.java            |    38 +
 .../securequery/SecureQueryDecodeProcessor.java |    87 +
 .../SecureQueryDecryptDescriptor.java           |    38 +
 .../SecureQueryDecryptProcessor.java            |   120 +
 .../SecureQueryDeploymentContributor.java       |   113 +
 .../SecureQueryEncodeDescriptor.java            |    38 +
 .../securequery/SecureQueryEncodeProcessor.java |    77 +
 .../SecureQueryEncryptDescriptor.java           |    38 +
 .../SecureQueryEncryptProcessor.java            |    84 +
 .../securequery/SecureQueryMessages.java        |    31 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ....filter.rewrite.api.UrlRewriteStepDescriptor |    22 -
 ...y.filter.rewrite.spi.UrlRewriteStepProcessor |    22 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 ....filter.rewrite.api.UrlRewriteStepDescriptor |    22 +
 ...y.filter.rewrite.spi.UrlRewriteStepProcessor |    22 +
 .../SecureQueryDecodeDescriptorTest.java        |    35 -
 .../SecureQueryDecodeProcessorTest.java         |   125 -
 .../SecureQueryDeploymentContributorTest.java   |   102 -
 .../SecureQueryEncodeDescriptorTest.java        |    35 -
 .../SecureQueryEncodeProcessorTest.java         |    75 -
 .../SecureQueryEncryptDecryptProcessorTest.java |   179 -
 .../SecureQueryDecodeDescriptorTest.java        |    35 +
 .../SecureQueryDecodeProcessorTest.java         |   125 +
 .../SecureQueryDeploymentContributorTest.java   |   100 +
 .../SecureQueryEncodeDescriptorTest.java        |    35 +
 .../SecureQueryEncodeProcessorTest.java         |    75 +
 .../SecureQueryEncryptDecryptProcessorTest.java |   179 +
 .../rewrite/api/CookieScopeServletFilter.java   |    48 -
 .../rewrite/api/FrontendFunctionDescriptor.java |    31 -
 .../rewrite/api/UrlRewriteEnvironment.java      |    31 -
 .../api/UrlRewriteFilterApplyDescriptor.java    |    27 -
 .../api/UrlRewriteFilterBufferDescriptor.java   |    25 -
 .../api/UrlRewriteFilterContentDescriptor.java  |    32 -
 .../rewrite/api/UrlRewriteFilterDescriptor.java |    37 -
 .../api/UrlRewriteFilterDetectDescriptor.java   |    33 -
 .../api/UrlRewriteFilterGroupDescriptor.java    |    30 -
 .../api/UrlRewriteFilterPathDescriptor.java     |    39 -
 .../api/UrlRewriteFilterScopeDescriptor.java    |    22 -
 .../rewrite/api/UrlRewriteFlowDescriptor.java   |    42 -
 .../api/UrlRewriteFunctionDescriptor.java       |    24 -
 .../UrlRewriteFunctionDescriptorFactory.java    |    61 -
 .../filter/rewrite/api/UrlRewriteProcessor.java |   182 -
 .../rewrite/api/UrlRewriteRuleDescriptor.java   |    52 -
 .../rewrite/api/UrlRewriteRulesDescriptor.java  |    57 -
 .../api/UrlRewriteRulesDescriptorFactory.java   |    77 -
 .../api/UrlRewriteServletContextListener.java   |   106 -
 .../api/UrlRewriteServletEnvironment.java       |    56 -
 .../rewrite/api/UrlRewriteServletFilter.java    |    63 -
 .../rewrite/api/UrlRewriteStepDescriptor.java   |    26 -
 .../api/UrlRewriteStepDescriptorFactory.java    |    60 -
 .../filter/rewrite/api/UrlRewriteStepFlow.java  |    20 -
 .../api/UrlRewriteStreamFilterFactory.java      |   115 -
 .../gateway/filter/rewrite/api/UrlRewriter.java |    31 -
 .../filter/rewrite/ext/ScopedMatcher.java       |   129 -
 .../rewrite/ext/UrlRewriteActionDescriptor.java |    32 -
 .../UrlRewriteActionRewriteDescriptorExt.java   |    52 -
 .../UrlRewriteActionRewriteProcessorExt.java    |    60 -
 .../rewrite/ext/UrlRewriteCheckDescriptor.java  |    36 -
 .../ext/UrlRewriteCheckDescriptorExt.java       |    99 -
 .../ext/UrlRewriteCheckProcessorExt.java        |    44 -
 .../ext/UrlRewriteControlDescriptor.java        |    23 -
 .../ext/UrlRewriteControlDescriptorExt.java     |    30 -
 .../ext/UrlRewriteControlProcessorExt.java      |    44 -
 .../rewrite/ext/UrlRewriteMatchDescriptor.java  |    39 -
 .../ext/UrlRewriteMatchDescriptorExt.java       |   110 -
 .../ext/UrlRewriteMatchProcessorExt.java        |    66 -
 .../filter/rewrite/i18n/UrlRewriteMessages.java |    87 -
 .../rewrite/i18n/UrlRewriteResources.java       |    41 -
 .../impl/CookieScopeResponseWrapper.java        |    59 -
 .../rewrite/impl/FrontendFunctionProcessor.java |   125 -
 .../rewrite/impl/UrlRewriteContextImpl.java     |   152 -
 .../impl/UrlRewriteDeploymentContributor.java   |   100 -
 .../UrlRewriteFilterApplyDescriptorImpl.java    |    47 -
 .../UrlRewriteFilterBufferDescriptorImpl.java   |    37 -
 .../UrlRewriteFilterContentDescriptorImpl.java  |    80 -
 .../impl/UrlRewriteFilterDescriptorImpl.java    |    87 -
 .../UrlRewriteFilterDetectDescriptorImpl.java   |    65 -
 .../UrlRewriteFilterGroupDescriptorBase.java    |    52 -
 .../rewrite/impl/UrlRewriteFilterReader.java    |    39 -
 .../UrlRewriteFilterScopeDescriptorImpl.java    |    25 -
 .../UrlRewriteFilterSelectorDescriptorBase.java |    64 -
 .../UrlRewriteFunctionProcessorFactory.java     |   113 -
 .../filter/rewrite/impl/UrlRewriteRequest.java  |   265 -
 .../rewrite/impl/UrlRewriteRequestStream.java   |    39 -
 .../filter/rewrite/impl/UrlRewriteResponse.java |   330 -
 .../rewrite/impl/UrlRewriteResponseStream.java  |    53 -
 .../impl/UrlRewriteRuleDescriptorImpl.java      |   194 -
 .../impl/UrlRewriteRuleProcessorHolder.java     |    65 -
 .../impl/UrlRewriteRuleProcessorImpl.java       |    58 -
 .../impl/UrlRewriteRulesDescriptorImpl.java     |   143 -
 .../impl/UrlRewriteStepProcessorFactory.java    |   106 -
 .../impl/UrlRewriteStepProcessorHolder.java     |   233 -
 .../impl/UrlRewriteStepProcessorState.java      |    88 -
 .../filter/rewrite/impl/UrlRewriteUtil.java     |    92 -
 .../rewrite/impl/form/FormFilterReader.java     |   105 -
 .../filter/rewrite/impl/form/FormPair.java      |    51 -
 .../filter/rewrite/impl/form/FormReader.java    |    96 -
 .../impl/form/FormUrlRewriteFilterReader.java   |    60 -
 .../impl/form/FormUrlRewriteStreamFilter.java   |    59 -
 .../filter/rewrite/impl/form/FormWriter.java    |    47 -
 .../rewrite/impl/html/HtmlFilterReader.java     |    61 -
 .../rewrite/impl/html/HtmlFilterReaderBase.java |   326 -
 .../impl/html/HtmlImportFunctionDescriptor.java |    30 -
 .../impl/html/HtmlImportFunctionProcessor.java  |    89 -
 .../rewrite/impl/html/HtmlPrefixDescriptor.java |    48 -
 .../rewrite/impl/html/HtmlPrefixProcessor.java  |   104 -
 .../impl/html/HtmlUrlRewriteFilterReader.java   |    74 -
 .../impl/html/HtmlUrlRewriteStreamFilter.java   |    64 -
 .../impl/javascript/JavaScriptFilterReader.java |    91 -
 .../JavaScriptUrlRewriteFilterReader.java       |    62 -
 .../JavaScriptUrlRewriteStreamFilter.java       |    64 -
 .../rewrite/impl/json/JsonFilterReader.java     |   644 -
 .../impl/json/JsonUrlRewriteFilterReader.java   |    64 -
 .../impl/json/JsonUrlRewriteStreamFilter.java   |    59 -
 .../impl/noop/NoOpUrlRewriteStreamFilter.java   |    55 -
 .../rewrite/impl/xml/XmlFilterReader.java       |   643 -
 .../impl/xml/XmlRewriteRulesDigester.java       |   239 -
 .../rewrite/impl/xml/XmlRewriteRulesTags.java   |    54 -
 .../impl/xml/XmlUrlRewriteFilterReader.java     |    82 -
 .../impl/xml/XmlUrlRewriteRulesExporter.java    |   188 -
 .../impl/xml/XmlUrlRewriteRulesImporter.java    |    52 -
 .../impl/xml/XmlUrlRewriteStreamFilter.java     |    67 -
 .../spi/UrlRewriteActionDescriptorBase.java     |    83 -
 .../filter/rewrite/spi/UrlRewriteContext.java   |    45 -
 .../spi/UrlRewriteFlowDescriptorBase.java       |   114 -
 .../spi/UrlRewriteFunctionProcessor.java        |    31 -
 .../spi/UrlRewriteFunctionProcessorBase.java    |    31 -
 .../filter/rewrite/spi/UrlRewriteResolver.java  |    26 -
 .../rewrite/spi/UrlRewriteRulesExporter.java    |    31 -
 .../rewrite/spi/UrlRewriteRulesImporter.java    |    31 -
 .../spi/UrlRewriteStepDescriptorBase.java       |    46 -
 .../rewrite/spi/UrlRewriteStepProcessor.java    |    33 -
 .../rewrite/spi/UrlRewriteStepStatus.java       |    20 -
 .../rewrite/spi/UrlRewriteStreamFilter.java     |    45 -
 .../rewrite/api/CookieScopeServletFilter.java   |    47 +
 .../rewrite/api/FrontendFunctionDescriptor.java |    31 +
 .../rewrite/api/UrlRewriteEnvironment.java      |    31 +
 .../api/UrlRewriteFilterApplyDescriptor.java    |    27 +
 .../api/UrlRewriteFilterBufferDescriptor.java   |    25 +
 .../api/UrlRewriteFilterContentDescriptor.java  |    32 +
 .../rewrite/api/UrlRewriteFilterDescriptor.java |    37 +
 .../api/UrlRewriteFilterDetectDescriptor.java   |    33 +
 .../api/UrlRewriteFilterGroupDescriptor.java    |    30 +
 .../api/UrlRewriteFilterPathDescriptor.java     |    39 +
 .../api/UrlRewriteFilterScopeDescriptor.java    |    22 +
 .../rewrite/api/UrlRewriteFlowDescriptor.java   |    42 +
 .../api/UrlRewriteFunctionDescriptor.java       |    24 +
 .../UrlRewriteFunctionDescriptorFactory.java    |    61 +
 .../filter/rewrite/api/UrlRewriteProcessor.java |   179 +
 .../rewrite/api/UrlRewriteRuleDescriptor.java   |    52 +
 .../rewrite/api/UrlRewriteRulesDescriptor.java  |    57 +
 .../api/UrlRewriteRulesDescriptorFactory.java   |    76 +
 .../api/UrlRewriteServletContextListener.java   |   106 +
 .../api/UrlRewriteServletEnvironment.java       |    56 +
 .../rewrite/api/UrlRewriteServletFilter.java    |    63 +
 .../rewrite/api/UrlRewriteStepDescriptor.java   |    26 +
 .../api/UrlRewriteStepDescriptorFactory.java    |    60 +
 .../filter/rewrite/api/UrlRewriteStepFlow.java  |    20 +
 .../api/UrlRewriteStreamFilterFactory.java      |   115 +
 .../gateway/filter/rewrite/api/UrlRewriter.java |    31 +
 .../filter/rewrite/ext/ScopedMatcher.java       |   129 +
 .../rewrite/ext/UrlRewriteActionDescriptor.java |    32 +
 .../UrlRewriteActionRewriteDescriptorExt.java   |    52 +
 .../UrlRewriteActionRewriteProcessorExt.java    |    60 +
 .../rewrite/ext/UrlRewriteCheckDescriptor.java  |    36 +
 .../ext/UrlRewriteCheckDescriptorExt.java       |    99 +
 .../ext/UrlRewriteCheckProcessorExt.java        |    45 +
 .../ext/UrlRewriteControlDescriptor.java        |    23 +
 .../ext/UrlRewriteControlDescriptorExt.java     |    30 +
 .../ext/UrlRewriteControlProcessorExt.java      |    45 +
 .../rewrite/ext/UrlRewriteMatchDescriptor.java  |    40 +
 .../ext/UrlRewriteMatchDescriptorExt.java       |   110 +
 .../ext/UrlRewriteMatchProcessorExt.java        |    67 +
 .../filter/rewrite/i18n/UrlRewriteMessages.java |    87 +
 .../rewrite/i18n/UrlRewriteResources.java       |    41 +
 .../impl/CookieScopeResponseWrapper.java        |    59 +
 .../rewrite/impl/FrontendFunctionProcessor.java |   125 +
 .../rewrite/impl/UrlRewriteContextImpl.java     |   152 +
 .../impl/UrlRewriteDeploymentContributor.java   |   101 +
 .../UrlRewriteFilterApplyDescriptorImpl.java    |    47 +
 .../UrlRewriteFilterBufferDescriptorImpl.java   |    36 +
 .../UrlRewriteFilterContentDescriptorImpl.java  |    80 +
 .../impl/UrlRewriteFilterDescriptorImpl.java    |    86 +
 .../UrlRewriteFilterDetectDescriptorImpl.java   |    65 +
 .../UrlRewriteFilterGroupDescriptorBase.java    |    52 +
 .../rewrite/impl/UrlRewriteFilterReader.java    |    39 +
 .../UrlRewriteFilterScopeDescriptorImpl.java    |    25 +
 .../UrlRewriteFilterSelectorDescriptorBase.java |    64 +
 .../UrlRewriteFunctionProcessorFactory.java     |   113 +
 .../filter/rewrite/impl/UrlRewriteRequest.java  |   265 +
 .../rewrite/impl/UrlRewriteRequestStream.java   |    40 +
 .../filter/rewrite/impl/UrlRewriteResponse.java |   331 +
 .../rewrite/impl/UrlRewriteResponseStream.java  |    54 +
 .../impl/UrlRewriteRuleDescriptorImpl.java      |   195 +
 .../impl/UrlRewriteRuleProcessorHolder.java     |    65 +
 .../impl/UrlRewriteRuleProcessorImpl.java       |    59 +
 .../impl/UrlRewriteRulesDescriptorImpl.java     |   143 +
 .../impl/UrlRewriteStepProcessorFactory.java    |   106 +
 .../impl/UrlRewriteStepProcessorHolder.java     |   233 +
 .../impl/UrlRewriteStepProcessorState.java      |    88 +
 .../filter/rewrite/impl/UrlRewriteUtil.java     |    92 +
 .../rewrite/impl/form/FormFilterReader.java     |   105 +
 .../filter/rewrite/impl/form/FormPair.java      |    51 +
 .../filter/rewrite/impl/form/FormReader.java    |    96 +
 .../impl/form/FormUrlRewriteFilterReader.java   |    60 +
 .../impl/form/FormUrlRewriteStreamFilter.java   |    59 +
 .../filter/rewrite/impl/form/FormWriter.java    |    47 +
 .../rewrite/impl/html/HtmlFilterReader.java     |    61 +
 .../rewrite/impl/html/HtmlFilterReaderBase.java |   327 +
 .../impl/html/HtmlImportFunctionDescriptor.java |    31 +
 .../impl/html/HtmlImportFunctionProcessor.java  |    90 +
 .../rewrite/impl/html/HtmlPrefixDescriptor.java |    48 +
 .../rewrite/impl/html/HtmlPrefixProcessor.java  |   104 +
 .../impl/html/HtmlUrlRewriteFilterReader.java   |    74 +
 .../impl/html/HtmlUrlRewriteStreamFilter.java   |    64 +
 .../impl/javascript/JavaScriptFilterReader.java |    91 +
 .../JavaScriptUrlRewriteFilterReader.java       |    62 +
 .../JavaScriptUrlRewriteStreamFilter.java       |    65 +
 .../rewrite/impl/json/JsonFilterReader.java     |   644 +
 .../impl/json/JsonUrlRewriteFilterReader.java   |    64 +
 .../impl/json/JsonUrlRewriteStreamFilter.java   |    59 +
 .../impl/noop/NoOpUrlRewriteStreamFilter.java   |    55 +
 .../rewrite/impl/xml/XmlFilterReader.java       |   643 +
 .../impl/xml/XmlRewriteRulesDigester.java       |   239 +
 .../rewrite/impl/xml/XmlRewriteRulesTags.java   |    54 +
 .../impl/xml/XmlUrlRewriteFilterReader.java     |    80 +
 .../impl/xml/XmlUrlRewriteRulesExporter.java    |   200 +
 .../impl/xml/XmlUrlRewriteRulesImporter.java    |    52 +
 .../impl/xml/XmlUrlRewriteStreamFilter.java     |    67 +
 .../spi/UrlRewriteActionDescriptorBase.java     |    83 +
 .../filter/rewrite/spi/UrlRewriteContext.java   |    45 +
 .../spi/UrlRewriteFlowDescriptorBase.java       |   115 +
 .../spi/UrlRewriteFunctionProcessor.java        |    31 +
 .../spi/UrlRewriteFunctionProcessorBase.java    |    31 +
 .../filter/rewrite/spi/UrlRewriteResolver.java  |    26 +
 .../rewrite/spi/UrlRewriteRulesExporter.java    |    31 +
 .../rewrite/spi/UrlRewriteRulesImporter.java    |    31 +
 .../spi/UrlRewriteStepDescriptorBase.java       |    46 +
 .../rewrite/spi/UrlRewriteStepProcessor.java    |    33 +
 .../rewrite/spi/UrlRewriteStepStatus.java       |    20 +
 .../rewrite/spi/UrlRewriteStreamFilter.java     |    43 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ...ter.rewrite.api.UrlRewriteFunctionDescriptor |    21 -
 ....filter.rewrite.api.UrlRewriteStepDescriptor |    22 -
 ...lter.rewrite.spi.UrlRewriteFunctionProcessor |    21 -
 ...y.filter.rewrite.spi.UrlRewriteStepProcessor |    23 -
 ...ay.filter.rewrite.spi.UrlRewriteStreamFilter |    24 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 ...ter.rewrite.api.UrlRewriteFunctionDescriptor |    21 +
 ....filter.rewrite.api.UrlRewriteStepDescriptor |    22 +
 ...lter.rewrite.spi.UrlRewriteFunctionProcessor |    21 +
 ...y.filter.rewrite.spi.UrlRewriteStepProcessor |    23 +
 ...ay.filter.rewrite.spi.UrlRewriteStreamFilter |    24 +
 .../api/FrontendFunctionDescriptorTest.java     |    52 -
 .../rewrite/api/UrlRewriteProcessorTest.java    |   412 -
 .../UrlRewriteRulesDescriptorFactoryTest.java   |   253 -
 .../UrlRewriteServletContextListenerTest.java   |    91 -
 .../api/UrlRewriteServletEnvironmentTest.java   |    60 -
 .../api/UrlRewriteServletFilterTest.java        |   921 --
 .../impl/CookieScopeResponseWrapperTest.java    |    91 -
 .../impl/FrontendFunctionProcessorTest.java     |   303 -
 .../rewrite/impl/UrlRewriteContextImplTest.java |    71 -
 .../rewrite/impl/UrlRewriteResponseTest.java    |   171 -
 .../impl/UrlRewriteStepProcessorStateTest.java  |   251 -
 .../gateway/filter/rewrite/impl/gateway.xml     |    33 -
 .../impl/html/HtmlFilterReaderBaseTest.java     |   765 --
 .../html/HtmlImportFunctionProcessorTest.java   |    52 -
 .../impl/html/HtmlPrefixProcessorTest.java      |    57 -
 .../javascript/JavaScriptFilterReaderTest.java  |   118 -
 .../rewrite/impl/json/JsonFilterReaderTest.java |   364 -
 .../rewrite/impl/json/NoopJsonFilterReader.java |    39 -
 .../rewrite/impl/json/TestJsonFilterReader.java |    39 -
 .../gateway/filter/rewrite/impl/rewrite.xml     |   106 -
 .../rewrite/impl/xml/XmlFilterReaderTest.java   |  1003 --
 .../xml/XmlUrlRewriteRulesExporterTest.java     |   215 -
 .../api/FrontendFunctionDescriptorTest.java     |    52 +
 .../rewrite/api/UrlRewriteProcessorTest.java    |   412 +
 .../UrlRewriteRulesDescriptorFactoryTest.java   |   253 +
 .../UrlRewriteServletContextListenerTest.java   |    89 +
 .../api/UrlRewriteServletEnvironmentTest.java   |    60 +
 .../api/UrlRewriteServletFilterTest.java        |   920 ++
 .../impl/CookieScopeResponseWrapperTest.java    |    91 +
 .../impl/FrontendFunctionProcessorTest.java     |   303 +
 .../rewrite/impl/UrlRewriteContextImplTest.java |    71 +
 .../rewrite/impl/UrlRewriteResponseTest.java    |   171 +
 .../impl/UrlRewriteStepProcessorStateTest.java  |   255 +
 .../gateway/filter/rewrite/impl/gateway.xml     |    33 +
 .../impl/html/HtmlFilterReaderBaseTest.java     |   765 ++
 .../html/HtmlImportFunctionProcessorTest.java   |    52 +
 .../impl/html/HtmlPrefixProcessorTest.java      |    57 +
 .../javascript/JavaScriptFilterReaderTest.java  |   118 +
 .../rewrite/impl/json/JsonFilterReaderTest.java |   363 +
 .../rewrite/impl/json/NoopJsonFilterReader.java |    39 +
 .../rewrite/impl/json/TestJsonFilterReader.java |    39 +
 .../gateway/filter/rewrite/impl/rewrite.xml     |   106 +
 .../rewrite/impl/xml/XmlFilterReaderTest.java   |  1003 ++
 .../xml/XmlUrlRewriteRulesExporterTest.java     |   215 +
 .../rewrite-with-same-rules-different-scope.xml |    54 -
 .../rewrite-with-same-rules.xml                 |    39 -
 .../api/UrlRewriteProcessorTest/rewrite.xml     |    36 -
 .../empty.xml                                   |    16 -
 .../filter-complete.xml                         |    33 -
 .../filter-sample.xml                           |    37 -
 .../filter-simple.xml                           |    24 -
 .../invalid.xml                                 |    18 -
 .../noop.xml                                    |    18 -
 .../simple.xml                                  |    19 -
 .../rewrite.xml                                 |    18 -
 .../api/UrlRewriteServletFilterTest/rewrite.xml |   109 -
 .../FrontendFunctionProcessorTest/rewrite.xml   |    64 -
 .../test-input-body.json                        |    10 -
 .../impl/json/JsonFilterReaderTest/array.json   |     4 -
 .../impl/json/JsonFilterReaderTest/complex.json |    16 -
 .../JsonFilterReaderTest/dotted-field-name.json |     6 -
 .../JsonFilterReaderTest/empty-array-value.json |     3 -
 .../empty-object-value.json                     |     3 -
 .../json/JsonFilterReaderTest/properties.json   |    19 -
 .../JsonFilterReaderTest/simple-values.json     |     7 -
 .../properties-attributes.xml                   |    22 -
 .../XmlFilterReaderTest/properties-elements.xml |    31 -
 .../rewrite-with-same-rules-different-scope.xml |    54 +
 .../rewrite-with-same-rules.xml                 |    39 +
 .../api/UrlRewriteProcessorTest/rewrite.xml     |    36 +
 .../empty.xml                                   |    16 +
 .../filter-complete.xml                         |    33 +
 .../filter-sample.xml                           |    37 +
 .../filter-simple.xml                           |    24 +
 .../invalid.xml                                 |    18 +
 .../noop.xml                                    |    18 +
 .../simple.xml                                  |    19 +
 .../rewrite.xml                                 |    18 +
 .../api/UrlRewriteServletFilterTest/rewrite.xml |   109 +
 .../FrontendFunctionProcessorTest/rewrite.xml   |    64 +
 .../test-input-body.json                        |    10 +
 .../impl/json/JsonFilterReaderTest/array.json   |     4 +
 .../impl/json/JsonFilterReaderTest/complex.json |    16 +
 .../JsonFilterReaderTest/dotted-field-name.json |     6 +
 .../JsonFilterReaderTest/empty-array-value.json |     3 +
 .../empty-object-value.json                     |     3 +
 .../json/JsonFilterReaderTest/properties.json   |    19 +
 .../JsonFilterReaderTest/simple-values.json     |     7 +
 .../properties-attributes.xml                   |    22 +
 .../XmlFilterReaderTest/properties-elements.xml |    31 +
 .../AnonymousAuthDeploymentContributor.java     |    65 -
 .../gateway/filter/AnonymousAuthFilter.java     |   101 -
 .../AnonymousAuthDeploymentContributor.java     |    65 +
 .../gateway/filter/AnonymousAuthFilter.java     |   101 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 .../AnonymousAuthDeploymentContributorTest.java |    44 -
 .../AnonymousAuthDeploymentContributorTest.java |    44 +
 .../impl/AclsAuthzDeploymentContributor.java    |    75 -
 .../apache/hadoop/gateway/filter/AclParser.java |    85 -
 .../gateway/filter/AclsAuthorizationFilter.java |   216 -
 .../filter/AclsAuthorizationMessages.java       |    66 -
 .../filter/AclsAuthorizationResources.java      |    27 -
 .../gateway/filter/InvalidACLException.java     |    31 -
 .../impl/AclsAuthzDeploymentContributor.java    |    73 +
 .../apache/knox/gateway/filter/AclParser.java   |    85 +
 .../gateway/filter/AclsAuthorizationFilter.java |   212 +
 .../filter/AclsAuthorizationMessages.java       |    65 +
 .../filter/AclsAuthorizationResources.java      |    27 +
 .../gateway/filter/InvalidACLException.java     |    31 +
 ...gateway.deploy.ProviderDeploymentContributor |    18 -
 ...gateway.deploy.ProviderDeploymentContributor |    18 +
 .../hadoop/gateway/filter/AclParserTest.java    |   212 -
 .../knox/gateway/filter/AclParserTest.java      |   212 +
 .../gateway/hadoopauth/HadoopAuthMessages.java  |    33 -
 .../deploy/HadoopAuthDeploymentContributor.java |    70 -
 .../hadoopauth/filter/HadoopAuthFilter.java     |    68 -
 .../hadoopauth/filter/HadoopAuthPostFilter.java |   108 -
 .../gateway/hadoopauth/HadoopAuthMessages.java  |    33 +
 .../deploy/HadoopAuthDeploymentContributor.java |    70 +
 .../hadoopauth/filter/HadoopAuthFilter.java     |    68 +
 .../hadoopauth/filter/HadoopAuthPostFilter.java |   108 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 .../provider/federation/jwt/JWTMessages.java    |    57 -
 .../AccessTokenFederationContributor.java       |    51 -
 .../JWTAccessTokenAssertionContributor.java     |    63 -
 .../deploy/JWTAuthCodeAssertionContributor.java |    51 -
 .../jwt/deploy/JWTFederationContributor.java    |    62 -
 .../deploy/SSOCookieFederationContributor.java  |    62 -
 .../jwt/filter/AbstractJWTFilter.java           |   263 -
 .../jwt/filter/AccessTokenFederationFilter.java |   163 -
 .../filter/JWTAccessTokenAssertionFilter.java   |   164 -
 .../jwt/filter/JWTAuthCodeAssertionFilter.java  |   100 -
 .../jwt/filter/JWTFederationFilter.java         |   109 -
 .../jwt/filter/SSOCookieFederationFilter.java   |   168 -
 .../provider/federation/jwt/JWTMessages.java    |    57 +
 .../AccessTokenFederationContributor.java       |    51 +
 .../JWTAccessTokenAssertionContributor.java     |    63 +
 .../deploy/JWTAuthCodeAssertionContributor.java |    51 +
 .../jwt/deploy/JWTFederationContributor.java    |    63 +
 .../deploy/SSOCookieFederationContributor.java  |    63 +
 .../jwt/filter/AbstractJWTFilter.java           |   263 +
 .../jwt/filter/AccessTokenFederationFilter.java |   163 +
 .../filter/JWTAccessTokenAssertionFilter.java   |   164 +
 .../jwt/filter/JWTAuthCodeAssertionFilter.java  |   100 +
 .../jwt/filter/JWTFederationFilter.java         |   109 +
 .../jwt/filter/SSOCookieFederationFilter.java   |   168 +
 ...gateway.deploy.ProviderDeploymentContributor |    23 -
 ...gateway.deploy.ProviderDeploymentContributor |    23 +
 .../federation/AbstractJWTFilterTest.java       |   490 -
 .../federation/JWTFederationFilterTest.java     |    67 -
 .../provider/federation/JWTTokenTest.java       |   133 -
 .../federation/SSOCookieProviderTest.java       |   205 -
 .../federation/AbstractJWTFilterTest.java       |   490 +
 .../federation/JWTFederationFilterTest.java     |    67 +
 .../provider/federation/JWTTokenTest.java       |   133 +
 .../federation/SSOCookieProviderTest.java       |   205 +
 .../hadoop/gateway/pac4j/Pac4jMessages.java     |    50 -
 .../Pac4jFederationProviderContributor.java     |    77 -
 .../pac4j/filter/Pac4jDispatcherFilter.java     |   215 -
 .../pac4j/filter/Pac4jIdentityAdapter.java      |   132 -
 .../gateway/pac4j/session/KnoxSessionStore.java |   120 -
 .../knox/gateway/pac4j/Pac4jMessages.java       |    50 +
 .../Pac4jFederationProviderContributor.java     |    78 +
 .../pac4j/filter/Pac4jDispatcherFilter.java     |   215 +
 .../pac4j/filter/Pac4jIdentityAdapter.java      |   138 +
 .../gateway/pac4j/session/KnoxSessionStore.java |   120 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 .../gateway/pac4j/MockHttpServletRequest.java   |    88 -
 .../gateway/pac4j/MockHttpServletResponse.java  |    82 -
 .../hadoop/gateway/pac4j/Pac4jProviderTest.java |   150 -
 .../gateway/pac4j/MockHttpServletRequest.java   |    88 +
 .../gateway/pac4j/MockHttpServletResponse.java  |    82 +
 .../knox/gateway/pac4j/Pac4jProviderTest.java   |   150 +
 .../gateway/picketlink/PicketlinkMessages.java  |    40 -
 .../picketlink/deploy/PicketlinkConf.java       |   194 -
 ...PicketlinkFederationProviderContributor.java |   132 -
 .../filter/CaptureOriginalURLFilter.java        |    89 -
 .../filter/PicketlinkIdentityAdapter.java       |   102 -
 .../gateway/picketlink/PicketlinkMessages.java  |    40 +
 .../picketlink/deploy/PicketlinkConf.java       |   194 +
 ...PicketlinkFederationProviderContributor.java |   132 +
 .../filter/CaptureOriginalURLFilter.java        |    89 +
 .../filter/PicketlinkIdentityAdapter.java       |   102 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 .../gateway/picketlink/PicketlinkTest.java      |    31 -
 .../knox/gateway/picketlink/PicketlinkTest.java |    30 +
 .../hadoop/gateway/preauth/PreAuthMessages.java |    26 -
 .../deploy/HeaderPreAuthContributor.java        |    66 -
 .../filter/AbstractPreAuthFederationFilter.java |   144 -
 .../preauth/filter/DefaultValidator.java        |    56 -
 .../filter/HeaderPreAuthFederationFilter.java   |    72 -
 .../gateway/preauth/filter/IPValidator.java     |    58 -
 .../preauth/filter/PreAuthFederationFilter.java |   142 -
 .../gateway/preauth/filter/PreAuthService.java  |   106 -
 .../filter/PreAuthValidationException.java      |    32 -
 .../preauth/filter/PreAuthValidator.java        |    42 -
 .../knox/gateway/preauth/PreAuthMessages.java   |    24 +
 .../deploy/HeaderPreAuthContributor.java        |    66 +
 .../filter/AbstractPreAuthFederationFilter.java |   144 +
 .../preauth/filter/DefaultValidator.java        |    56 +
 .../filter/HeaderPreAuthFederationFilter.java   |    71 +
 .../gateway/preauth/filter/IPValidator.java     |    58 +
 .../preauth/filter/PreAuthFederationFilter.java |   142 +
 .../gateway/preauth/filter/PreAuthService.java  |   106 +
 .../filter/PreAuthValidationException.java      |    32 +
 .../preauth/filter/PreAuthValidator.java        |    42 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ...doop.gateway.preauth.filter.PreAuthValidator |    20 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 ...knox.gateway.preauth.filter.PreAuthValidator |    20 +
 .../federation/DefaultValidatorTest.java        |    43 -
 .../HeaderPreAuthFederationFilterTest.java      |   140 -
 .../provider/federation/IPValidatorTest.java    |    61 -
 .../provider/federation/PreAuthSSOTest.java     |    31 -
 .../provider/federation/PreAuthServiceTest.java |   109 -
 .../federation/DefaultValidatorTest.java        |    43 +
 .../HeaderPreAuthFederationFilterTest.java      |   147 +
 .../provider/federation/IPValidatorTest.java    |    61 +
 .../provider/federation/PreAuthSSOTest.java     |    30 +
 .../provider/federation/PreAuthServiceTest.java |   115 +
 ...doop.gateway.preauth.filter.PreAuthValidator |    19 -
 ...knox.gateway.preauth.filter.PreAuthValidator |    19 +
 .../hadoop/gateway/deploy/impl/ShiroConfig.java |    71 -
 .../deploy/impl/ShiroDeploymentContributor.java |   140 -
 .../gateway/filter/RedirectToUrlFilter.java     |    52 -
 .../gateway/filter/ResponseCookieFilter.java    |    88 -
 .../filter/ShiroSubjectIdentityAdapter.java     |   150 -
 .../gateway/shirorealm/KnoxCacheManager.java    |    27 -
 .../shirorealm/KnoxLdapContextFactory.java      |   128 -
 .../gateway/shirorealm/KnoxLdapRealm.java       |   768 --
 .../hadoop/gateway/shirorealm/KnoxPamRealm.java |   163 -
 .../gateway/shirorealm/UnixUserPrincipal.java   |    46 -
 .../shirorealm/impl/i18n/KnoxShiroMessages.java |    44 -
 .../knox/gateway/deploy/impl/ShiroConfig.java   |    71 +
 .../deploy/impl/ShiroDeploymentContributor.java |   140 +
 .../gateway/filter/RedirectToUrlFilter.java     |    52 +
 .../gateway/filter/ResponseCookieFilter.java    |    88 +
 .../filter/ShiroSubjectIdentityAdapter.java     |   150 +
 .../gateway/shirorealm/KnoxCacheManager.java    |    27 +
 .../shirorealm/KnoxLdapContextFactory.java      |   125 +
 .../knox/gateway/shirorealm/KnoxLdapRealm.java  |   768 ++
 .../knox/gateway/shirorealm/KnoxPamRealm.java   |   163 +
 .../gateway/shirorealm/UnixUserPrincipal.java   |    46 +
 .../shirorealm/impl/i18n/KnoxShiroMessages.java |    44 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 .../impl/ShiroDeploymentContributorTest.java    |   108 -
 .../gateway/shirorealm/KnoxLdapRealmTest.java   |   104 -
 .../gateway/shirorealm/KnoxPamRealmTest.java    |    70 -
 .../impl/ShiroDeploymentContributorTest.java    |   104 +
 .../gateway/shirorealm/KnoxLdapRealmTest.java   |   104 +
 .../gateway/shirorealm/KnoxPamRealmTest.java    |    68 +
 .../gateway/webappsec/WebAppSecMessages.java    |    26 -
 .../webappsec/deploy/WebAppSecContributor.java  |   106 -
 .../webappsec/filter/CSRFPreventionFilter.java  |    76 -
 .../webappsec/filter/XFrameOptionsFilter.java   |   137 -
 .../gateway/webappsec/WebAppSecMessages.java    |    24 +
 .../webappsec/deploy/WebAppSecContributor.java  |   106 +
 .../webappsec/filter/CSRFPreventionFilter.java  |    76 +
 .../webappsec/filter/XFrameOptionsFilter.java   |   137 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 .../hadoop/gateway/webappsec/CSRFTest.java      |    29 -
 .../webappsec/XFrameOptionsFilterTest.java      |   193 -
 .../apache/knox/gateway/webappsec/CSRFTest.java |    29 +
 .../webappsec/XFrameOptionsFilterTest.java      |   193 +
 .../home/conf/gateway-log4j.properties          |     2 +-
 gateway-release/home/conf/topologies/admin.xml  |     4 +-
 .../home/conf/topologies/knoxsso.xml            |     4 +-
 .../home/conf/topologies/manager.xml            |     4 +-
 .../home/conf/topologies/sandbox.xml            |     4 +-
 gateway-release/home/templates/ad.xml           |     4 +-
 gateway-release/home/templates/dynamicgroup.xml |     4 +-
 .../home/templates/hs2-grouplookup-cache.xml    |     4 +-
 gateway-release/home/templates/sample.xml       |     4 +-
 gateway-release/home/templates/sandbox-1-3.xml  |     4 +-
 .../templates/sandbox.knoxrealm.ehcache.xml     |     6 +-
 .../home/templates/sandbox.knoxrealm.xml        |     4 +-
 .../home/templates/sandbox.knoxrealm1.xml       |     4 +-
 .../home/templates/sandbox.knoxrealm2.xml       |     8 +-
 .../home/templates/sandbox.knoxrealmdg.xml      |     4 +-
 gateway-release/home/templates/staticgroup.xml  |     4 +-
 gateway-release/home/templates/ui.xml           |     4 +-
 ...ache.hadoop.gateway.services.GatewayServices |    20 -
 ...apache.knox.gateway.services.GatewayServices |    20 +
 gateway-server-launcher/pom.xml                 |     2 +-
 .../gateway/filter/CompositeEnumeration.java    |    56 -
 .../gateway/filter/XForwardedHeaderFilter.java  |    32 -
 .../filter/XForwardedHeaderRequestWrapper.java  |   150 -
 .../gateway/filter/CompositeEnumeration.java    |    56 +
 .../gateway/filter/XForwardedHeaderFilter.java  |    32 +
 .../filter/XForwardedHeaderRequestWrapper.java  |   150 +
 .../filter/CompositeEnumerationTest.java        |   117 -
 .../gateway/filter/TestFilterAdapter.java       |    45 -
 .../hadoop/gateway/filter/TestFilterChain.java  |    35 -
 .../filter/XForwardHeaderFilterTest.java        |   108 -
 .../filter/CompositeEnumerationTest.java        |   117 +
 .../knox/gateway/filter/TestFilterAdapter.java  |    45 +
 .../knox/gateway/filter/TestFilterChain.java    |    35 +
 .../filter/XForwardHeaderFilterTest.java        |   108 +
 .../hadoop/gateway/GatewayCommandLine.java      |    86 -
 .../apache/hadoop/gateway/GatewayFactory.java   |   100 -
 .../apache/hadoop/gateway/GatewayFilter.java    |   390 -
 .../gateway/GatewayForwardingServlet.java       |   141 -
 .../apache/hadoop/gateway/GatewayMessages.java  |   516 -
 .../apache/hadoop/gateway/GatewayResources.java |    88 -
 .../apache/hadoop/gateway/GatewayServer.java    |  1029 --
 .../apache/hadoop/gateway/GatewayServlet.java   |   302 -
 .../gateway/config/impl/GatewayConfigImpl.java  |   915 --
 .../gateway/deploy/DeploymentContextImpl.java   |   140 -
 .../gateway/deploy/DeploymentException.java     |    31 -
 .../gateway/deploy/DeploymentFactory.java       |   770 --
 .../impl/ApplicationDeploymentContributor.java  |   227 -
 .../impl/DispatchDeploymentContributor.java     |    59 -
 .../GenericProviderDeploymentContributor.java   |    93 -
 .../ServiceDefinitionDeploymentContributor.java |   256 -
 .../descriptor/GatewayDescriptorFactory.java    |    67 -
 .../descriptor/impl/FilterDescriptorImpl.java   |   120 -
 .../impl/FilterParamDescriptorImpl.java         |    69 -
 .../descriptor/impl/GatewayDescriptorImpl.java  |    92 -
 .../impl/GatewayParamDescriptorImpl.java        |    64 -
 .../descriptor/impl/ResourceDescriptorImpl.java |   131 -
 .../impl/ResourceParamDescriptorImpl.java       |    65 -
 .../xml/XmlGatewayDescriptorExporter.java       |   114 -
 .../xml/XmlGatewayDescriptorFactory.java        |    30 -
 .../xml/XmlGatewayDescriptorImporter.java       |    52 -
 .../xml/XmlGatewayDescriptorRules.java          |    68 -
 .../xml/XmlGatewayDescriptorTags.java           |    34 -
 .../gateway/dispatch/DispatchParamResolver.java |    68 -
 .../gateway/dispatch/ServletDispatch.java       |    54 -
 .../gateway/dispatch/UrlConnectionDispatch.java |   163 -
 .../filter/BasicAuthChallengeFilter.java        |    84 -
 .../gateway/filter/CorrelationHandler.java      |    45 -
 .../hadoop/gateway/filter/JaasLoginFilter.java  |    86 -
 .../filter/PortMappingHelperHandler.java        |   156 -
 .../gateway/filter/RequestUpdateHandler.java    |   136 -
 .../hadoop/gateway/filter/SessionFilter.java    |    38 -
 .../gateway/services/CLIGatewayServices.java    |   143 -
 .../services/DefaultGatewayServices.java        |   224 -
 .../services/DefaultServerInfoService.java      |    69 -
 .../GatewayMetricsServletContextListener.java   |    31 -
 .../GatewayServicesContextListener.java         |    54 -
 .../hostmap/impl/DefaultHostMapperService.java  |    81 -
 .../metrics/impl/DefaultMetricsContext.java     |    49 -
 .../metrics/impl/DefaultMetricsService.java     |   152 -
 .../impl/instr/InstrGatewayFilterProvider.java  |    37 -
 .../InstrGatewayFilterProviderDescriptor.java   |    40 -
 .../instr/InstrHttpClientBuilderProvider.java   |    70 -
 .../InstrHttpClientProviderDescriptor.java      |    40 -
 .../impl/instr/InstrumentedGatewayFilter.java   |    99 -
 .../impl/reporters/AbstractMetricsReporter.java |    33 -
 .../impl/reporters/GraphiteMetricsReporter.java |    69 -
 .../impl/reporters/JmxMetricsReporter.java      |    56 -
 .../registry/impl/DefaultServiceDefEntry.java   |    52 -
 .../impl/DefaultServiceDefinitionRegistry.java  |    95 -
 .../impl/DefaultServiceRegistryService.java     |   207 -
 .../services/registry/impl/RegEntry.java        |    59 -
 .../services/registry/impl/Registry.java        |    33 -
 .../security/impl/CLIMasterService.java         |    55 -
 .../security/impl/DefaultAliasService.java      |   217 -
 .../security/impl/DefaultCryptoService.java     |   206 -
 .../security/impl/DefaultKeystoreService.java   |   340 -
 .../security/impl/DefaultMasterService.java     |    58 -
 .../services/security/impl/JettySSLService.java |   255 -
 .../impl/DefaultTokenAuthorityService.java      |   225 -
 .../topology/impl/DefaultTopologyService.java   |   447 -
 .../builder/BeanPropertyTopologyBuilder.java    |    94 -
 .../builder/PropertyTopologyBuilder.java        |    64 -
 .../topology/builder/property/Property.java     |    47 -
 .../interpreter/AbstractInterpreter.java        |    22 -
 .../interpreter/GatewayPropertyInterpreter.java |    54 -
 .../interpreter/InterpretException.java         |    36 -
 .../property/interpreter/Interpreter.java       |    22 -
 .../interpreter/PropertyInterpreter.java        |    54 -
 .../ProviderParameterPropertyInterpreter.java   |    50 -
 .../ProviderPropertyInterpreter.java            |    88 -
 .../ServiceParameterPropertyInterpreter.java    |    50 -
 .../interpreter/ServicePropertyInterpreter.java |    89 -
 .../TopologyPropertyInterpreter.java            |    62 -
 .../topology/validation/TopologyValidator.java  |   122 -
 .../xml/AmbariFormatXmlTopologyRules.java       |    37 -
 .../xml/KnoxFormatXmlTopologyRules.java         |    93 -
 .../hadoop/gateway/trace/AccessHandler.java     |    53 -
 .../hadoop/gateway/trace/ErrorHandler.java      |    42 -
 .../hadoop/gateway/trace/TraceHandler.java      |    54 -
 .../apache/hadoop/gateway/trace/TraceInput.java |    71 -
 .../hadoop/gateway/trace/TraceOutput.java       |    76 -
 .../hadoop/gateway/trace/TraceRequest.java      |    83 -
 .../hadoop/gateway/trace/TraceResponse.java     |    77 -
 .../apache/hadoop/gateway/trace/TraceUtil.java  |    72 -
 .../gateway/util/CredentialsProvider.java       |    50 -
 .../org/apache/hadoop/gateway/util/KnoxCLI.java |  1779 ---
 .../gateway/util/PrincipalCredentials.java      |    83 -
 .../gateway/util/ServiceDefinitionsLoader.java  |   138 -
 .../websockets/GatewayWebsocketHandler.java     |   241 -
 .../websockets/MessageEventCallback.java        |    66 -
 .../gateway/websockets/ProxyInboundSocket.java  |    80 -
 .../websockets/ProxyWebSocketAdapter.java       |   277 -
 .../websockets/WebsocketLogMessages.java        |    60 -
 .../apache/knox/gateway/GatewayCommandLine.java |    86 +
 .../org/apache/knox/gateway/GatewayFactory.java |   100 +
 .../org/apache/knox/gateway/GatewayFilter.java  |   390 +
 .../knox/gateway/GatewayForwardingServlet.java  |   145 +
 .../apache/knox/gateway/GatewayMessages.java    |   516 +
 .../apache/knox/gateway/GatewayResources.java   |    88 +
 .../org/apache/knox/gateway/GatewayServer.java  |  1029 ++
 .../org/apache/knox/gateway/GatewayServlet.java |   302 +
 .../gateway/config/impl/GatewayConfigImpl.java  |   915 ++
 .../gateway/deploy/DeploymentContextImpl.java   |   140 +
 .../gateway/deploy/DeploymentException.java     |    31 +
 .../knox/gateway/deploy/DeploymentFactory.java  |   772 ++
 .../impl/ApplicationDeploymentContributor.java  |   228 +
 .../impl/DispatchDeploymentContributor.java     |    60 +
 .../GenericProviderDeploymentContributor.java   |    94 +
 .../ServiceDefinitionDeploymentContributor.java |   256 +
 .../descriptor/GatewayDescriptorFactory.java    |    67 +
 .../descriptor/impl/FilterDescriptorImpl.java   |   120 +
 .../impl/FilterParamDescriptorImpl.java         |    69 +
 .../descriptor/impl/GatewayDescriptorImpl.java  |    92 +
 .../impl/GatewayParamDescriptorImpl.java        |    64 +
 .../descriptor/impl/ResourceDescriptorImpl.java |   131 +
 .../impl/ResourceParamDescriptorImpl.java       |    65 +
 .../xml/XmlGatewayDescriptorExporter.java       |   114 +
 .../xml/XmlGatewayDescriptorFactory.java        |    30 +
 .../xml/XmlGatewayDescriptorImporter.java       |    52 +
 .../xml/XmlGatewayDescriptorRules.java          |    68 +
 .../xml/XmlGatewayDescriptorTags.java           |    34 +
 .../gateway/dispatch/DispatchParamResolver.java |    68 +
 .../knox/gateway/dispatch/ServletDispatch.java  |    54 +
 .../gateway/dispatch/UrlConnectionDispatch.java |   163 +
 .../filter/BasicAuthChallengeFilter.java        |    84 +
 .../knox/gateway/filter/CorrelationHandler.java |    45 +
 .../knox/gateway/filter/JaasLoginFilter.java    |    86 +
 .../filter/PortMappingHelperHandler.java        |   156 +
 .../gateway/filter/RequestUpdateHandler.java    |   136 +
 .../knox/gateway/filter/SessionFilter.java      |    38 +
 .../gateway/services/CLIGatewayServices.java    |   143 +
 .../services/DefaultGatewayServices.java        |   224 +
 .../services/DefaultServerInfoService.java      |    69 +
 .../GatewayMetricsServletContextListener.java   |    31 +
 .../GatewayServicesContextListener.java         |    54 +
 .../hostmap/impl/DefaultHostMapperService.java  |    81 +
 .../metrics/impl/DefaultMetricsContext.java     |    49 +
 .../metrics/impl/DefaultMetricsService.java     |   153 +
 .../impl/instr/InstrGatewayFilterProvider.java  |    38 +
 .../InstrGatewayFilterProviderDescriptor.java   |    40 +
 .../instr/InstrHttpClientBuilderProvider.java   |    70 +
 .../InstrHttpClientProviderDescriptor.java      |    41 +
 .../impl/instr/InstrumentedGatewayFilter.java   |    99 +
 .../impl/reporters/AbstractMetricsReporter.java |    33 +
 .../impl/reporters/GraphiteMetricsReporter.java |    70 +
 .../impl/reporters/JmxMetricsReporter.java      |    57 +
 .../registry/impl/DefaultServiceDefEntry.java   |    52 +
 .../impl/DefaultServiceDefinitionRegistry.java  |    96 +
 .../impl/DefaultServiceRegistryService.java     |   207 +
 .../services/registry/impl/RegEntry.java        |    59 +
 .../services/registry/impl/Registry.java        |    33 +
 .../security/impl/CLIMasterService.java         |    56 +
 .../security/impl/DefaultAliasService.java      |   217 +
 .../security/impl/DefaultCryptoService.java     |   206 +
 .../security/impl/DefaultKeystoreService.java   |   340 +
 .../security/impl/DefaultMasterService.java     |    59 +
 .../services/security/impl/JettySSLService.java |   255 +
 .../impl/DefaultTokenAuthorityService.java      |   225 +
 .../topology/impl/DefaultTopologyService.java   |   448 +
 .../builder/BeanPropertyTopologyBuilder.java    |    94 +
 .../builder/PropertyTopologyBuilder.java        |    64 +
 .../topology/builder/property/Property.java     |    47 +
 .../interpreter/AbstractInterpreter.java        |    22 +
 .../interpreter/GatewayPropertyInterpreter.java |    54 +
 .../interpreter/InterpretException.java         |    36 +
 .../property/interpreter/Interpreter.java       |    22 +
 .../interpreter/PropertyInterpreter.java        |    54 +
 .../ProviderParameterPropertyInterpreter.java   |    50 +
 .../ProviderPropertyInterpreter.java            |    88 +
 .../ServiceParameterPropertyInterpreter.java    |    50 +
 .../interpreter/ServicePropertyInterpreter.java |    89 +
 .../TopologyPropertyInterpreter.java            |    62 +
 .../topology/validation/TopologyValidator.java  |   122 +
 .../xml/AmbariFormatXmlTopologyRules.java       |    37 +
 .../xml/KnoxFormatXmlTopologyRules.java         |    93 +
 .../knox/gateway/trace/AccessHandler.java       |    53 +
 .../apache/knox/gateway/trace/ErrorHandler.java |    42 +
 .../apache/knox/gateway/trace/TraceHandler.java |    54 +
 .../apache/knox/gateway/trace/TraceInput.java   |    71 +
 .../apache/knox/gateway/trace/TraceOutput.java  |    76 +
 .../apache/knox/gateway/trace/TraceRequest.java |    83 +
 .../knox/gateway/trace/TraceResponse.java       |    77 +
 .../apache/knox/gateway/trace/TraceUtil.java    |    72 +
 .../knox/gateway/util/CredentialsProvider.java  |    50 +
 .../org/apache/knox/gateway/util/KnoxCLI.java   |  1777 +++
 .../knox/gateway/util/PrincipalCredentials.java |    81 +
 .../gateway/util/ServiceDefinitionsLoader.java  |   138 +
 .../websockets/GatewayWebsocketHandler.java     |   241 +
 .../websockets/MessageEventCallback.java        |    66 +
 .../gateway/websockets/ProxyInboundSocket.java  |    80 +
 .../websockets/ProxyWebSocketAdapter.java       |   276 +
 .../websockets/WebsocketLogMessages.java        |    60 +
 ...gateway.deploy.ProviderDeploymentContributor |    20 -
 ....gateway.deploy.ServiceDeploymentContributor |    17 -
 ...es.metrics.InstrumentationProviderDescriptor |    20 -
 ...oop.gateway.services.metrics.MetricsReporter |    20 -
 ...gateway.deploy.ProviderDeploymentContributor |    20 +
 ....gateway.deploy.ServiceDeploymentContributor |    17 +
 ...es.metrics.InstrumentationProviderDescriptor |    20 +
 ...nox.gateway.services.metrics.MetricsReporter |    20 +
 .../org/apache/hadoop/gateway/GatewayServer.xml |    67 -
 .../org/apache/knox/gateway/GatewayServer.xml   |    67 +
 .../apache/hadoop/gateway/AuditLoggingTest.java |   255 -
 .../hadoop/gateway/GatewayFilterTest.java       |   171 -
 .../gateway/GatewayForwardingServletTest.java   |    66 -
 .../apache/hadoop/gateway/GatewayFuncTest.xml   |    67 -
 .../hadoop/gateway/GatewayGlobalConfigTest.java |   214 -
 .../gateway/GatewayPortMappingConfigTest.java   |   204 -
 .../apache/hadoop/gateway/TempletonDemo.java    |    70 -
 .../config/impl/GatewayConfigImplTest.java      |   220 -
 .../gateway/deploy/DeploymentFactoryTest.java   |   324 -
 ...enericProviderDeploymentContributorTest.java |    45 -
 ...viceDefinitionDeploymentContributorTest.java |    43 -
 .../descriptor/GatewayDescriptorTest.java       |   117 -
 .../xml/XmlGatewayDescriptorExporterTest.java   |   145 -
 .../xml/XmlGatewayDescriptorImporterTest.java   |   172 -
 .../hadoop/gateway/jetty/JettyPathMapTest.java  |    67 -
 .../hadoop/gateway/jetty/SslSocketTest.java     |   118 -
 .../hadoop/gateway/mock/MockConsoleFactory.java |    43 -
 .../metrics/impl/DefaultMetricsServiceTest.java |    93 -
 .../DefaultServiceDefinitionRegistryTest.java   |    46 -
 .../services/security/CryptoServiceTest.java    |   214 -
 .../topology/DefaultTopologyServiceTest.java    |   208 -
 .../builder/PropertyTopologyBuilderTest.java    |   173 -
 .../validation/TopologyValidatorTest.java       |    48 -
 .../topology/xml/TopologyRulesModuleTest.java   |   262 -
 .../apache/hadoop/gateway/util/KnoxCLITest.java |   649 -
 .../util/ServiceDefinitionsLoaderTest.java      |    49 -
 .../gateway/websockets/BadBackendTest.java      |   118 -
 .../hadoop/gateway/websockets/BadUrlTest.java   |   309 -
 .../websockets/ConnectionDroppedTest.java       |   203 -
 .../hadoop/gateway/websockets/EchoSocket.java   |    68 -
 .../gateway/websockets/MessageFailureTest.java  |   207 -
 .../gateway/websockets/WebsocketClient.java     |   131 -
 .../websockets/WebsocketEchoHandler.java        |    47 -
 .../gateway/websockets/WebsocketEchoTest.java   |   388 -
 .../WebsocketMultipleConnectionTest.java        |   390 -
 .../apache/knox/gateway/AuditLoggingTest.java   |   255 +
 .../apache/knox/gateway/GatewayFilterTest.java  |   171 +
 .../gateway/GatewayForwardingServletTest.java   |    66 +
 .../org/apache/knox/gateway/GatewayFuncTest.xml |    67 +
 .../knox/gateway/GatewayGlobalConfigTest.java   |   214 +
 .../gateway/GatewayPortMappingConfigTest.java   |   204 +
 .../org/apache/knox/gateway/TempletonDemo.java  |    70 +
 .../config/impl/GatewayConfigImplTest.java      |   220 +
 .../gateway/deploy/DeploymentFactoryTest.java   |   324 +
 ...enericProviderDeploymentContributorTest.java |    45 +
 ...viceDefinitionDeploymentContributorTest.java |    43 +
 .../descriptor/GatewayDescriptorTest.java       |   117 +
 .../xml/XmlGatewayDescriptorExporterTest.java   |   145 +
 .../xml/XmlGatewayDescriptorImporterTest.java   |   172 +
 .../knox/gateway/jetty/JettyPathMapTest.java    |    67 +
 .../knox/gateway/jetty/SslSocketTest.java       |   118 +
 .../knox/gateway/mock/MockConsoleFactory.java   |    43 +
 .../metrics/impl/DefaultMetricsServiceTest.java |    93 +
 .../DefaultServiceDefinitionRegistryTest.java   |    46 +
 .../services/security/CryptoServiceTest.java    |   214 +
 .../topology/DefaultTopologyServiceTest.java    |   215 +
 .../builder/PropertyTopologyBuilderTest.java    |   173 +
 .../validation/TopologyValidatorTest.java       |    48 +
 .../topology/xml/TopologyRulesModuleTest.java   |   262 +
 .../apache/knox/gateway/util/KnoxCLITest.java   |   649 +
 .../util/ServiceDefinitionsLoaderTest.java      |    50 +
 .../knox/gateway/websockets/BadBackendTest.java |   117 +
 .../knox/gateway/websockets/BadUrlTest.java     |   309 +
 .../websockets/ConnectionDroppedTest.java       |   198 +
 .../knox/gateway/websockets/EchoSocket.java     |    68 +
 .../gateway/websockets/MessageFailureTest.java  |   207 +
 .../gateway/websockets/WebsocketClient.java     |   131 +
 .../websockets/WebsocketEchoHandler.java        |    47 +
 .../gateway/websockets/WebsocketEchoTest.java   |   388 +
 .../WebsocketMultipleConnectionTest.java        |   389 +
 .../test/resources/gateway-demo-insecure.xml    |    46 +-
 .../src/test/resources/gateway-demo-secure.xml  |    24 +-
 .../apache/hadoop/gateway/GatewayFuncTest.xml   |    69 -
 .../gateway/topology/file/topology-one.xml      |    12 -
 .../gateway/topology/file/topology-three.xml    |    12 -
 .../gateway/topology/file/topology-two.xml      |    12 -
 .../topology-valid-complete.xml                 |    40 -
 .../topology-valid-with-name.xml                |    19 -
 .../TopologyValidatorTest/topology-valid.xml    |    25 -
 .../topology-with-application.xml               |    23 -
 .../service-param-topology-ambari-format.conf   |    55 -
 .../xml/service-param-topology-knox-format.xml  |    43 -
 .../xml/simple-topology-ambari-format.conf      |    79 -
 .../xml/simple-topology-knox-format.xml         |    81 -
 .../org/apache/knox/gateway/GatewayFuncTest.xml |    69 +
 .../knox/gateway/topology/file/topology-one.xml |    12 +
 .../gateway/topology/file/topology-three.xml    |    12 +
 .../knox/gateway/topology/file/topology-two.xml |    12 +
 .../topology-valid-complete.xml                 |    40 +
 .../topology-valid-with-name.xml                |    19 +
 .../TopologyValidatorTest/topology-valid.xml    |    25 +
 .../topology-with-application.xml               |    23 +
 .../service-param-topology-ambari-format.conf   |    55 +
 .../xml/service-param-topology-knox-format.xml  |    43 +
 .../xml/simple-topology-ambari-format.conf      |    79 +
 .../xml/simple-topology-knox-format.xml         |    81 +
 .../service/admin/TopologiesResource.java       |   311 -
 .../admin/TopologyCollectionMarshaller.java     |    70 -
 .../service/admin/TopologyMarshaller.java       |   100 -
 .../service/admin/VersionMarshaller.java        |    72 -
 .../gateway/service/admin/VersionResource.java  |    96 -
 .../service/admin/beans/Application.java        |    34 -
 .../service/admin/beans/BeanConverter.java      |   164 -
 .../gateway/service/admin/beans/Param.java      |    57 -
 .../gateway/service/admin/beans/Provider.java   |    75 -
 .../gateway/service/admin/beans/Service.java    |    87 -
 .../gateway/service/admin/beans/Topology.java   |   108 -
 .../AdminServiceDeploymentContributor.java      |    59 -
 .../service/admin/TopologiesResource.java       |   312 +
 .../admin/TopologyCollectionMarshaller.java     |    70 +
 .../service/admin/TopologyMarshaller.java       |   100 +
 .../service/admin/VersionMarshaller.java        |    72 +
 .../gateway/service/admin/VersionResource.java  |    96 +
 .../service/admin/beans/Application.java        |    34 +
 .../service/admin/beans/BeanConverter.java      |   168 +
 .../knox/gateway/service/admin/beans/Param.java |    57 +
 .../gateway/service/admin/beans/Provider.java   |    74 +
 .../gateway/service/admin/beans/Service.java    |    87 +
 .../gateway/service/admin/beans/Topology.java   |   108 +
 .../AdminServiceDeploymentContributor.java      |    59 +
 ....gateway.deploy.ServiceDeploymentContributor |    19 -
 ....gateway.deploy.ServiceDeploymentContributor |    19 +
 .../gateway/service/admin/beans/jaxb.properties |    16 -
 .../gateway/service/admin/jaxb.properties       |    16 -
 .../gateway/service/admin/beans/jaxb.properties |    16 +
 .../knox/gateway/service/admin/jaxb.properties  |    16 +
 .../service/admin/TopologyMarshallerTest.java   |    60 -
 .../service/admin/TopologyResourceTest.java     |   185 -
 .../service/admin/TopologyMarshallerTest.java   |    61 +
 .../service/admin/TopologyResourceTest.java     |   185 +
 .../gateway/as/ASDeploymentContributor.java     |    58 -
 .../gateway/as/ASDeploymentContributor.java     |    55 +
 ....gateway.deploy.ServiceDeploymentContributor |    19 -
 ....gateway.deploy.ServiceDeploymentContributor |    19 +
 .../service/definition/CustomDispatch.java      |    80 -
 .../gateway/service/definition/Policy.java      |    45 -
 .../gateway/service/definition/Rewrite.java     |    47 -
 .../gateway/service/definition/Route.java       |    73 -
 .../service/definition/ServiceDefinition.java   |   109 -
 .../service/definition/CustomDispatch.java      |    80 +
 .../knox/gateway/service/definition/Policy.java |    45 +
 .../gateway/service/definition/Rewrite.java     |    47 +
 .../knox/gateway/service/definition/Route.java  |    73 +
 .../service/definition/ServiceDefinition.java   |   108 +
 .../definition/ServiceDefinitionTest.java       |    90 -
 .../definition/ServiceDefinitionTest.java       |    90 +
 .../hadoop/gateway/hbase/HBaseDispatch.java     |    52 -
 .../gateway/hbase/HBaseHttpClientDispatch.java  |    38 -
 .../knox/gateway/hbase/HBaseDispatch.java       |    52 +
 .../gateway/hbase/HBaseHttpClientDispatch.java  |    38 +
 .../HBaseDeploymentContributor/rewrite.xml      |    62 -
 .../HBaseDeploymentContributor/rewrite.xml      |    62 +
 .../hadoop/gateway/hbase/HBaseDispatchTest.java |    88 -
 .../knox/gateway/hbase/HBaseDispatchTest.java   |    88 +
 .../service/health/HealthServiceMessages.java   |    32 -
 .../gateway/service/health/MetricsResource.java |   142 -
 .../gateway/service/health/PingResource.java    |    93 -
 .../HealthServiceDeploymentContributor.java     |    55 -
 .../service/health/HealthServiceMessages.java   |    32 +
 .../gateway/service/health/MetricsResource.java |   142 +
 .../gateway/service/health/PingResource.java    |    92 +
 .../HealthServiceDeploymentContributor.java     |    55 +
 ....gateway.deploy.ServiceDeploymentContributor |    19 -
 ....gateway.deploy.ServiceDeploymentContributor |    19 +
 .../service/health/MetricsResourceTest.java     |    32 -
 .../service/health/PingResourceTest.java        |    30 -
 .../service/health/MetricsResourceTest.java     |    32 +
 .../service/health/PingResourceTest.java        |    29 +
 .../hadoop/gateway/hive/HiveDispatch.java       |    53 -
 .../hadoop/gateway/hive/HiveDispatchUtils.java  |    38 -
 .../hadoop/gateway/hive/HiveHaDispatch.java     |    48 -
 .../gateway/hive/HiveHttpClientDispatch.java    |    38 -
 .../apache/knox/gateway/hive/HiveDispatch.java  |    53 +
 .../knox/gateway/hive/HiveDispatchUtils.java    |    38 +
 .../knox/gateway/hive/HiveHaDispatch.java       |    48 +
 .../gateway/hive/HiveHttpClientDispatch.java    |    38 +
 .../service/knoxsso/KnoxSSOMessages.java        |    66 -
 .../gateway/service/knoxsso/WebSSOResource.java |   322 -
 .../KnoxSSOServiceDeploymentContributor.java    |    56 -
 .../service/knoxsso/KnoxSSOMessages.java        |    66 +
 .../gateway/service/knoxsso/WebSSOResource.java |   322 +
 .../KnoxSSOServiceDeploymentContributor.java    |    57 +
 ....gateway.deploy.ServiceDeploymentContributor |    19 -
 ....gateway.deploy.ServiceDeploymentContributor |    19 +
 .../service/knoxsso/WebSSOResourceTest.java     |    71 -
 .../service/knoxsso/WebSSOResourceTest.java     |    71 +
 .../service/knoxsso/KnoxSSOutMessages.java      |    29 -
 .../service/knoxsso/WebSSOutResource.java       |   106 -
 .../KnoxSSOutServiceDeploymentContributor.java  |    56 -
 .../service/knoxsso/KnoxSSOutMessages.java      |    28 +
 .../service/knoxsso/WebSSOutResource.java       |   106 +
 .../KnoxSSOutServiceDeploymentContributor.java  |    56 +
 ....gateway.deploy.ServiceDeploymentContributor |    19 -
 ....gateway.deploy.ServiceDeploymentContributor |    19 +
 .../service/knoxsso/WebSSOutResourceTest.java   |    32 -
 .../service/knoxsso/WebSSOutResourceTest.java   |    32 +
 .../service/knoxtoken/TokenResource.java        |   181 -
 .../service/knoxtoken/TokenServiceMessages.java |    66 -
 .../TokenServiceDeploymentContributor.java      |    55 -
 .../service/knoxtoken/TokenResource.java        |   182 +
 .../service/knoxtoken/TokenServiceMessages.java |    66 +
 .../TokenServiceDeploymentContributor.java      |    55 +
 ....gateway.deploy.ServiceDeploymentContributor |    19 -
 ....gateway.deploy.ServiceDeploymentContributor |    19 +
 .../knoxtoken/TokenServiceResourceTest.java     |    53 -
 .../knoxtoken/TokenServiceResourceTest.java     |    52 +
 .../gateway/rm/dispatch/RMHaBaseDispatcher.java |   220 -
 .../gateway/rm/dispatch/RMHaDispatch.java       |    54 -
 .../gateway/rm/dispatch/RMUIHaDispatch.java     |    54 -
 .../gateway/rm/dispatch/SafeModeException.java  |    21 -
 .../gateway/rm/dispatch/StandbyException.java   |    21 -
 .../hadoop/gateway/rm/i18n/RMMessages.java      |    46 -
 .../gateway/rm/dispatch/RMHaBaseDispatcher.java |   220 +
 .../knox/gateway/rm/dispatch/RMHaDispatch.java  |    52 +
 .../gateway/rm/dispatch/RMUIHaDispatch.java     |    54 +
 .../gateway/rm/dispatch/SafeModeException.java  |    21 +
 .../gateway/rm/dispatch/StandbyException.java   |    21 +
 .../apache/knox/gateway/rm/i18n/RMMessages.java |    46 +
 .../gateway/rm/dispatch/RMHaDispatchTest.java   |   219 -
 .../gateway/rm/dispatch/RMHaDispatchTest.java   |   219 +
 .../hadoop/gateway/storm/StormDispatch.java     |    35 -
 .../knox/gateway/storm/StormDispatch.java       |    35 +
 .../service/test/ServiceTestResource.java       |   417 -
 .../gateway/service/test/ServiceTestURL.java    |    89 -
 .../test/ServiceTestWrapperMarshaller.java      |    72 -
 .../ServiceTestDeploymentContributor.java       |   102 -
 .../service/test/ServiceTestResource.java       |   417 +
 .../gateway/service/test/ServiceTestURL.java    |    89 +
 .../test/ServiceTestWrapperMarshaller.java      |    72 +
 .../ServiceTestDeploymentContributor.java       |   102 +
 ....gateway.deploy.ServiceDeploymentContributor |    19 -
 ....gateway.deploy.ServiceDeploymentContributor |    19 +
 .../hadoop/gateway/service/test/jaxb.properties |    16 -
 .../knox/gateway/service/test/jaxb.properties   |    16 +
 .../gateway/tgs/TGSDeploymentContributor.java   |    58 -
 .../gateway/tgs/TGSDeploymentContributor.java   |    55 +
 ....gateway.deploy.ServiceDeploymentContributor |    19 -
 ....gateway.deploy.ServiceDeploymentContributor |    19 +
 .../service/vault/CredentialResource.java       |   141 -
 .../VaultServiceDeploymentContributor.java      |    60 -
 .../service/vault/CredentialResource.java       |   139 +
 .../VaultServiceDeploymentContributor.java      |    60 +
 ....gateway.deploy.ServiceDeploymentContributor |    19 -
 ....gateway.deploy.ServiceDeploymentContributor |    19 +
 .../hdfs/JobTrackerDeploymentContributor.java   |    41 -
 .../hdfs/NameNodeDeploymentContributor.java     |    41 -
 .../gateway/hdfs/dispatch/HdfsDispatch.java     |    37 -
 .../hdfs/dispatch/HdfsHttpClientDispatch.java   |    45 -
 .../hdfs/dispatch/SafeModeException.java        |    21 -
 .../gateway/hdfs/dispatch/StandbyException.java |    21 -
 .../hdfs/dispatch/WebHdfsHaDispatch.java        |   184 -
 .../dispatch/WebHdfsHaHttpClientDispatch.java   |    38 -
 .../gateway/hdfs/i18n/WebHdfsMessages.java      |    43 -
 .../hdfs/JobTrackerDeploymentContributor.java   |    41 +
 .../hdfs/NameNodeDeploymentContributor.java     |    41 +
 .../gateway/hdfs/dispatch/HdfsDispatch.java     |    37 +
 .../hdfs/dispatch/HdfsHttpClientDispatch.java   |    46 +
 .../hdfs/dispatch/SafeModeException.java        |    21 +
 .../gateway/hdfs/dispatch/StandbyException.java |    21 +
 .../hdfs/dispatch/WebHdfsHaDispatch.java        |   184 +
 .../dispatch/WebHdfsHaHttpClientDispatch.java   |    38 +
 .../knox/gateway/hdfs/i18n/WebHdfsMessages.java |    43 +
 ....gateway.deploy.ServiceDeploymentContributor |    20 -
 ....gateway.deploy.ServiceDeploymentContributor |    20 +
 .../WebHdfsDeploymentContributor/rewrite.xml    |    70 -
 .../WebHdfsDeploymentContributor/rewrite.xml    |    70 +
 .../hdfs/dispatch/WebHdfsHaDispatchTest.java    |   105 -
 .../hdfs/dispatch/WebHdfsHaDispatchTest.java    |   105 +
 gateway-shell-launcher/pom.xml                  |     2 +-
 gateway-shell-release/pom.xml                   |     2 +-
 .../shell/AbstractCredentialCollector.java      |    74 -
 .../AbstractJavaConsoleCredentialCollector.java |    66 -
 .../hadoop/gateway/shell/AbstractRequest.java   |   113 -
 .../hadoop/gateway/shell/BasicResponse.java     |    99 -
 .../shell/ClearInputCredentialCollector.java    |    45 -
 .../hadoop/gateway/shell/ClientContext.java     |   211 -
 .../shell/CredentialCollectionException.java    |    34 -
 .../gateway/shell/CredentialCollector.java      |    29 -
 .../hadoop/gateway/shell/Credentials.java       |    63 -
 .../hadoop/gateway/shell/EmptyResponse.java     |    29 -
 .../hadoop/gateway/shell/ErrorResponse.java     |    35 -
 .../org/apache/hadoop/gateway/shell/Hadoop.java |   307 -
 .../hadoop/gateway/shell/HadoopException.java   |    34 -
 .../shell/HiddenInputCredentialCollector.java   |    45 -
 .../org/apache/hadoop/gateway/shell/KnoxSh.java |   308 -
 .../shell/KnoxTokenCredentialCollector.java     |    82 -
 .../org/apache/hadoop/gateway/shell/Shell.java  |    66 -
 .../gateway/shell/hbase/ClusterVersion.java     |    55 -
 .../hadoop/gateway/shell/hbase/Example.groovy   |   173 -
 .../hadoop/gateway/shell/hbase/HBase.java       |    56 -
 .../hadoop/gateway/shell/hbase/Status.java      |    55 -
 .../gateway/shell/hbase/SystemVersion.java      |    55 -
 .../gateway/shell/hbase/table/Attribute.java    |    36 -
 .../gateway/shell/hbase/table/CreateTable.java  |   117 -
 .../gateway/shell/hbase/table/DeleteTable.java  |    58 -
 .../gateway/shell/hbase/table/Family.java       |    55 -
 .../shell/hbase/table/FamilyContainer.java      |    22 -
 .../hadoop/gateway/shell/hbase/table/Table.java |    88 -
 .../gateway/shell/hbase/table/TableList.java    |    56 -
 .../gateway/shell/hbase/table/TableRegions.java |    59 -
 .../gateway/shell/hbase/table/TableSchema.java  |    59 -
 .../shell/hbase/table/TruncateTable.java        |    79 -
 .../gateway/shell/hbase/table/UpdateTable.java  |   107 -
 .../gateway/shell/hbase/table/row/Column.java   |    48 -
 .../shell/hbase/table/row/DeleteRows.java       |    93 -
 .../shell/hbase/table/row/InsertableColumn.java |    50 -
 .../shell/hbase/table/row/QueryRows.java        |   126 -
 .../gateway/shell/hbase/table/row/Row.java      |    50 -
 .../gateway/shell/hbase/table/row/StoreRow.java |   116 -
 .../hbase/table/scanner/CreateScanner.java      |   201 -
 .../hbase/table/scanner/DeleteScanner.java      |    60 -
 .../shell/hbase/table/scanner/Scanner.java      |    50 -
 .../hbase/table/scanner/ScannerGetNext.java     |    61 -
 .../hadoop/gateway/shell/hdfs/Example.groovy    |    57 -
 .../apache/hadoop/gateway/shell/hdfs/Get.java   |    79 -
 .../apache/hadoop/gateway/shell/hdfs/Hdfs.java  |    54 -
 .../apache/hadoop/gateway/shell/hdfs/Ls.java    |    66 -
 .../apache/hadoop/gateway/shell/hdfs/Mkdir.java |    72 -
 .../apache/hadoop/gateway/shell/hdfs/Put.java   |   139 -
 .../hadoop/gateway/shell/hdfs/Rename.java       |    69 -
 .../apache/hadoop/gateway/shell/hdfs/Rm.java    |    78 -
 .../hadoop/gateway/shell/hdfs/Status.java       |    68 -
 .../hadoop/gateway/shell/job/ExampleHive.groovy |    53 -
 .../hadoop/gateway/shell/job/ExampleJava.groovy |    55 -
 .../hadoop/gateway/shell/job/ExamplePig.groovy  |    57 -
 .../apache/hadoop/gateway/shell/job/Hive.java   |    98 -
 .../apache/hadoop/gateway/shell/job/Java.java   |   106 -
 .../apache/hadoop/gateway/shell/job/Job.java    |    50 -
 .../apache/hadoop/gateway/shell/job/Pig.java    |    98 -
 .../apache/hadoop/gateway/shell/job/Queue.java  |    58 -
 .../apache/hadoop/gateway/shell/job/Sqoop.java  |    99 -
 .../apache/hadoop/gateway/shell/job/Status.java |    65 -
 .../hadoop/gateway/shell/knox/token/Get.java    |    57 -
 .../hadoop/gateway/shell/knox/token/Token.java  |    29 -
 .../gateway/shell/workflow/Example.groovy       |    85 -
 .../hadoop/gateway/shell/workflow/Status.java   |    65 -
 .../hadoop/gateway/shell/workflow/Submit.java   |    96 -
 .../hadoop/gateway/shell/workflow/Workflow.java |    34 -
 .../hadoop/gateway/shell/yarn/AppState.java     |    69 -
 .../gateway/shell/yarn/ExampleYarnApp.groovy    |    87 -
 .../hadoop/gateway/shell/yarn/KillApp.java      |    68 -
 .../hadoop/gateway/shell/yarn/NewApp.java       |    62 -
 .../hadoop/gateway/shell/yarn/SubmitApp.java    |    81 -
 .../apache/hadoop/gateway/shell/yarn/Yarn.java  |    42 -
 .../shell/AbstractCredentialCollector.java      |    74 +
 .../AbstractJavaConsoleCredentialCollector.java |    66 +
 .../knox/gateway/shell/AbstractRequest.java     |   113 +
 .../knox/gateway/shell/BasicResponse.java       |    99 +
 .../shell/ClearInputCredentialCollector.java    |    45 +
 .../knox/gateway/shell/ClientContext.java       |   211 +
 .../shell/CredentialCollectionException.java    |    34 +
 .../knox/gateway/shell/CredentialCollector.java |    29 +
 .../apache/knox/gateway/shell/Credentials.java  |    63 +
 .../knox/gateway/shell/EmptyResponse.java       |    29 +
 .../knox/gateway/shell/ErrorResponse.java       |    35 +
 .../org/apache/knox/gateway/shell/Hadoop.java   |   307 +
 .../knox/gateway/shell/HadoopException.java     |    34 +
 .../shell/HiddenInputCredentialCollector.java   |    45 +
 .../org/apache/knox/gateway/shell/KnoxSh.java   |   306 +
 .../shell/KnoxTokenCredentialCollector.java     |    82 +
 .../org/apache/knox/gateway/shell/Shell.java    |    66 +
 .../gateway/shell/hbase/ClusterVersion.java     |    55 +
 .../knox/gateway/shell/hbase/Example.groovy     |   173 +
 .../apache/knox/gateway/shell/hbase/HBase.java  |    56 +
 .../apache/knox/gateway/shell/hbase/Status.java |    55 +
 .../knox/gateway/shell/hbase/SystemVersion.java |    55 +
 .../gateway/shell/hbase/table/Attribute.java    |    36 +
 .../gateway/shell/hbase/table/CreateTable.java  |   117 +
 .../gateway/shell/hbase/table/DeleteTable.java  |    58 +
 .../knox/gateway/shell/hbase/table/Family.java  |    55 +
 .../shell/hbase/table/FamilyContainer.java      |    22 +
 .../knox/gateway/shell/hbase/table/Table.java   |    88 +
 .../gateway/shell/hbase/table/TableList.java    |    56 +
 .../gateway/shell/hbase/table/TableRegions.java |    59 +
 .../gateway/shell/hbase/table/TableSchema.java  |    59 +
 .../shell/hbase/table/TruncateTable.java        |    79 +
 .../gateway/shell/hbase/table/UpdateTable.java  |   107 +
 .../gateway/shell/hbase/table/row/Column.java   |    48 +
 .../shell/hbase/table/row/DeleteRows.java       |    93 +
 .../shell/hbase/table/row/InsertableColumn.java |    50 +
 .../shell/hbase/table/row/QueryRows.java        |   126 +
 .../knox/gateway/shell/hbase/table/row/Row.java |    50 +
 .../gateway/shell/hbase/table/row/StoreRow.java |   116 +
 .../hbase/table/scanner/CreateScanner.java      |   201 +
 .../hbase/table/scanner/DeleteScanner.java      |    60 +
 .../shell/hbase/table/scanner/Scanner.java      |    50 +
 .../hbase/table/scanner/ScannerGetNext.java     |    61 +
 .../knox/gateway/shell/hdfs/Example.groovy      |    57 +
 .../org/apache/knox/gateway/shell/hdfs/Get.java |    79 +
 .../apache/knox/gateway/shell/hdfs/Hdfs.java    |    54 +
 .../org/apache/knox/gateway/shell/hdfs/Ls.java  |    66 +
 .../apache/knox/gateway/shell/hdfs/Mkdir.java   |    72 +
 .../org/apache/knox/gateway/shell/hdfs/Put.java |   139 +
 .../apache/knox/gateway/shell/hdfs/Rename.java  |    69 +
 .../org/apache/knox/gateway/shell/hdfs/Rm.java  |    78 +
 .../apache/knox/gateway/shell/hdfs/Status.java  |    68 +
 .../knox/gateway/shell/job/ExampleHive.groovy   |    53 +
 .../knox/gateway/shell/job/ExampleJava.groovy   |    55 +
 .../knox/gateway/shell/job/ExamplePig.groovy    |    57 +
 .../org/apache/knox/gateway/shell/job/Hive.java |    98 +
 .../org/apache/knox/gateway/shell/job/Java.java |   106 +
 .../org/apache/knox/gateway/shell/job/Job.java  |    50 +
 .../org/apache/knox/gateway/shell/job/Pig.java  |    98 +
 .../apache/knox/gateway/shell/job/Queue.java    |    58 +
 .../apache/knox/gateway/shell/job/Sqoop.java    |    99 +
 .../apache/knox/gateway/shell/job/Status.java   |    65 +
 .../knox/gateway/shell/knox/token/Get.java      |    57 +
 .../knox/gateway/shell/knox/token/Token.java    |    29 +
 .../knox/gateway/shell/workflow/Example.groovy  |    85 +
 .../knox/gateway/shell/workflow/Status.java     |    65 +
 .../knox/gateway/shell/workflow/Submit.java     |    96 +
 .../knox/gateway/shell/workflow/Workflow.java   |    34 +
 .../knox/gateway/shell/yarn/AppState.java       |    69 +
 .../gateway/shell/yarn/ExampleYarnApp.groovy    |    87 +
 .../apache/knox/gateway/shell/yarn/KillApp.java |    68 +
 .../apache/knox/gateway/shell/yarn/NewApp.java  |    62 +
 .../knox/gateway/shell/yarn/SubmitApp.java      |    81 +
 .../apache/knox/gateway/shell/yarn/Yarn.java    |    42 +
 ...che.hadoop.gateway.shell.CredentialCollector |    21 -
 ...pache.knox.gateway.shell.CredentialCollector |    21 +
 .../hadoop/gateway/SpiGatewayMessages.java      |    76 -
 .../hadoop/gateway/SpiGatewayResources.java     |    38 -
 .../config/FilterConfigurationAdapter.java      |    38 -
 .../FilterConfigurationAdapterDescriptor.java   |    29 -
 .../hadoop/gateway/config/GatewayConfig.java    |   300 -
 .../gateway/deploy/DeploymentContext.java       |    53 -
 .../deploy/DeploymentContributorBase.java       |    37 -
 .../deploy/ProviderDeploymentContributor.java   |    56 -
 .../ProviderDeploymentContributorBase.java      |    36 -
 .../deploy/ServiceDeploymentContributor.java    |    48 -
 .../ServiceDeploymentContributorBase.java       |   114 -
 .../gateway/descriptor/FilterDescriptor.java    |    51 -
 .../descriptor/FilterParamDescriptor.java       |    34 -
 .../gateway/descriptor/GatewayDescriptor.java   |    42 -
 .../descriptor/GatewayDescriptorExporter.java   |    29 -
 .../descriptor/GatewayDescriptorImporter.java   |    29 -
 .../descriptor/GatewayParamDescriptor.java      |    34 -
 .../gateway/descriptor/ResourceDescriptor.java  |    58 -
 .../descriptor/ResourceParamDescriptor.java     |    34 -
 .../dispatch/AbstractGatewayDispatch.java       |   144 -
 .../dispatch/CappedBufferHttpEntity.java        |   150 -
 .../gateway/dispatch/DefaultDispatch.java       |   319 -
 .../dispatch/DefaultHttpClientFactory.java      |   233 -
 .../hadoop/gateway/dispatch/Dispatch.java       |    56 -
 .../gateway/dispatch/GatewayDispatchFilter.java |   171 -
 .../gateway/dispatch/HadoopAuthCookieStore.java |    31 -
 .../gateway/dispatch/HttpClientDispatch.java    |    35 -
 .../gateway/dispatch/HttpClientFactory.java     |    27 -
 .../gateway/dispatch/InputStreamEntity.java     |   150 -
 .../gateway/dispatch/KnoxSpnegoAuthScheme.java  |    54 -
 .../dispatch/KnoxSpnegoAuthSchemeFactory.java   |    38 -
 .../dispatch/PartiallyRepeatableHttpEntity.java |   161 -
 .../dispatch/PassAllHeadersDispatch.java        |    46 -
 .../PassAllHeadersNoEncodingDispatch.java       |    50 -
 .../gateway/filter/AbstractGatewayFilter.java   |    99 -
 .../hadoop/gateway/filter/GatewayRequest.java   |    27 -
 .../gateway/filter/GatewayRequestWrapper.java   |    42 -
 .../hadoop/gateway/filter/GatewayResponse.java  |    34 -
 .../gateway/filter/GatewayResponseWrapper.java  |    68 -
 .../hadoop/gateway/filter/ResponseStreamer.java |    28 -
 .../security/AbstractIdentityAssertionBase.java |    36 -
 .../AbstractIdentityAssertionFilter.java        |   211 -
 .../hadoop/gateway/i18n/GatewaySpiMessages.java |    85 -
 .../gateway/i18n/GatewaySpiResources.java       |    30 -
 .../hadoop/gateway/security/GroupPrincipal.java |    32 -
 .../gateway/security/ImpersonatedPrincipal.java |    33 -
 .../gateway/security/PrimaryPrincipal.java      |    33 -
 .../hadoop/gateway/security/PromptUtils.java    |    82 -
 .../hadoop/gateway/security/SubjectUtils.java   |    96 -
 .../gateway/security/UsernamePassword.java      |    45 -
 .../security/principal/PrincipalMapper.java     |    47 -
 .../principal/PrincipalMappingException.java    |    30 -
 .../principal/SimplePrincipalMapper.java        |   124 -
 .../gateway/services/GatewayServices.java       |    46 -
 .../gateway/services/ServerInfoService.java     |    34 -
 .../apache/hadoop/gateway/services/Service.java |    31 -
 .../services/ServiceLifecycleException.java     |    30 -
 .../services/hostmap/FileBasedHostMapper.java   |    81 -
 .../gateway/services/hostmap/HostMapper.java    |    37 -
 .../services/hostmap/HostMapperService.java     |    41 -
 .../metrics/InstrumentationProvider.java        |    26 -
 .../InstrumentationProviderDescriptor.java      |    25 -
 .../services/metrics/MetricsContext.java        |    27 -
 .../services/metrics/MetricsReporter.java       |    33 -
 .../metrics/MetricsReporterException.java       |    29 -
 .../services/metrics/MetricsService.java        |    28 -
 .../services/registry/ServiceDefEntry.java      |    27 -
 .../registry/ServiceDefinitionRegistry.java     |    25 -
 .../services/registry/ServiceRegistry.java      |    34 -
 .../gateway/services/security/AliasService.java |    55 -
 .../security/AliasServiceException.java         |    27 -
 .../services/security/CryptoService.java        |    35 -
 .../services/security/EncryptionResult.java     |    70 -
 .../services/security/KeystoreService.java      |    54 -
 .../security/KeystoreServiceException.java      |    30 -
 .../services/security/MasterService.java        |    22 -
 .../gateway/services/security/SSLService.java   |    29 -
 .../security/impl/BaseKeystoreService.java      |   234 -
 .../security/impl/CMFKeystoreService.java       |   169 -
 .../security/impl/CMFMasterService.java         |   204 -
 .../security/impl/ConfigurableEncryptor.java    |   188 -
 .../security/impl/X509CertificateUtil.java      |   303 -
 .../security/token/JWTokenAuthority.java        |    52 -
 .../security/token/TokenServiceException.java   |    37 -
 .../services/security/token/impl/JWT.java       |    60 -
 .../token/impl/JWTProviderMessages.java         |    61 -
 .../services/security/token/impl/JWTToken.java  |   278 -
 .../services/topology/TopologyService.java      |    50 -
 .../hadoop/gateway/topology/Application.java    |    30 -
 .../apache/hadoop/gateway/topology/Param.java   |    50 -
 .../hadoop/gateway/topology/Provider.java       |    85 -
 .../hadoop/gateway/topology/Routable.java       |    22 -
 .../apache/hadoop/gateway/topology/Service.java |   150 -
 .../hadoop/gateway/topology/Topology.java       |   142 -
 .../hadoop/gateway/topology/TopologyEvent.java  |    40 -
 .../gateway/topology/TopologyListener.java      |    26 -
 .../gateway/topology/TopologyMonitor.java       |    28 -
 .../gateway/topology/TopologyProvider.java      |    26 -
 .../apache/hadoop/gateway/topology/Version.java |   135 -
 .../topology/builder/TopologyBuilder.java       |    24 -
 .../apache/knox/gateway/SpiGatewayMessages.java |    76 +
 .../knox/gateway/SpiGatewayResources.java       |    38 +
 .../config/FilterConfigurationAdapter.java      |    38 +
 .../FilterConfigurationAdapterDescriptor.java   |    29 +
 .../knox/gateway/config/GatewayConfig.java      |   300 +
 .../knox/gateway/deploy/DeploymentContext.java  |    53 +
 .../deploy/DeploymentContributorBase.java       |    37 +
 .../deploy/ProviderDeploymentContributor.java   |    56 +
 .../ProviderDeploymentContributorBase.java      |    36 +
 .../deploy/ServiceDeploymentContributor.java    |    48 +
 .../ServiceDeploymentContributorBase.java       |   114 +
 .../gateway/descriptor/FilterDescriptor.java    |    51 +
 .../descriptor/FilterParamDescriptor.java       |    34 +
 .../gateway/descriptor/GatewayDescriptor.java   |    42 +
 .../descriptor/GatewayDescriptorExporter.java   |    29 +
 .../descriptor/GatewayDescriptorImporter.java   |    29 +
 .../descriptor/GatewayParamDescriptor.java      |    34 +
 .../gateway/descriptor/ResourceDescriptor.java  |    58 +
 .../descriptor/ResourceParamDescriptor.java     |    34 +
 .../dispatch/AbstractGatewayDispatch.java       |   144 +
 .../dispatch/CappedBufferHttpEntity.java        |   150 +
 .../knox/gateway/dispatch/DefaultDispatch.java  |   319 +
 .../dispatch/DefaultHttpClientFactory.java      |   233 +
 .../apache/knox/gateway/dispatch/Dispatch.java  |    56 +
 .../gateway/dispatch/GatewayDispatchFilter.java |   169 +
 .../gateway/dispatch/HadoopAuthCookieStore.java |    31 +
 .../gateway/dispatch/HttpClientDispatch.java    |    35 +
 .../gateway/dispatch/HttpClientFactory.java     |    27 +
 .../gateway/dispatch/InputStreamEntity.java     |   150 +
 .../gateway/dispatch/KnoxSpnegoAuthScheme.java  |    54 +
 .../dispatch/KnoxSpnegoAuthSchemeFactory.java   |    38 +
 .../dispatch/PartiallyRepeatableHttpEntity.java |   161 +
 .../dispatch/PassAllHeadersDispatch.java        |    46 +
 .../PassAllHeadersNoEncodingDispatch.java       |    50 +
 .../gateway/filter/AbstractGatewayFilter.java   |    99 +
 .../knox/gateway/filter/GatewayRequest.java     |    27 +
 .../gateway/filter/GatewayRequestWrapper.java   |    42 +
 .../knox/gateway/filter/GatewayResponse.java    |    34 +
 .../gateway/filter/GatewayResponseWrapper.java  |    68 +
 .../knox/gateway/filter/ResponseStreamer.java   |    28 +
 .../security/AbstractIdentityAssertionBase.java |    36 +
 .../AbstractIdentityAssertionFilter.java        |   211 +
 .../knox/gateway/i18n/GatewaySpiMessages.java   |    85 +
 .../knox/gateway/i18n/GatewaySpiResources.java  |    30 +
 .../knox/gateway/security/GroupPrincipal.java   |    32 +
 .../gateway/security/ImpersonatedPrincipal.java |    33 +
 .../knox/gateway/security/PrimaryPrincipal.java |    33 +
 .../knox/gateway/security/PromptUtils.java      |    82 +
 .../knox/gateway/security/SubjectUtils.java     |    96 +
 .../knox/gateway/security/UsernamePassword.java |    45 +
 .../security/principal/PrincipalMapper.java     |    47 +
 .../principal/PrincipalMappingException.java    |    30 +
 .../principal/SimplePrincipalMapper.java        |   124 +
 .../knox/gateway/services/GatewayServices.java  |    46 +
 .../gateway/services/ServerInfoService.java     |    34 +
 .../apache/knox/gateway/services/Service.java   |    30 +
 .../services/ServiceLifecycleException.java     |    30 +
 .../services/hostmap/FileBasedHostMapper.java   |    81 +
 .../gateway/services/hostmap/HostMapper.java    |    37 +
 .../services/hostmap/HostMapperService.java     |    41 +
 .../metrics/InstrumentationProvider.java        |    26 +
 .../InstrumentationProviderDescriptor.java      |    25 +
 .../services/metrics/MetricsContext.java        |    27 +
 .../services/metrics/MetricsReporter.java       |    33 +
 .../metrics/MetricsReporterException.java       |    29 +
 .../services/metrics/MetricsService.java        |    28 +
 .../services/registry/ServiceDefEntry.java      |    27 +
 .../registry/ServiceDefinitionRegistry.java     |    25 +
 .../services/registry/ServiceRegistry.java      |    34 +
 .../gateway/services/security/AliasService.java |    55 +
 .../security/AliasServiceException.java         |    27 +
 .../services/security/CryptoService.java        |    35 +
 .../services/security/EncryptionResult.java     |    70 +
 .../services/security/KeystoreService.java      |    54 +
 .../security/KeystoreServiceException.java      |    30 +
 .../services/security/MasterService.java        |    22 +
 .../gateway/services/security/SSLService.java   |    29 +
 .../security/impl/BaseKeystoreService.java      |   233 +
 .../security/impl/CMFKeystoreService.java       |   167 +
 .../security/impl/CMFMasterService.java         |   204 +
 .../security/impl/ConfigurableEncryptor.java    |   188 +
 .../security/impl/X509CertificateUtil.java      |   303 +
 .../security/token/JWTokenAuthority.java        |    52 +
 .../security/token/TokenServiceException.java   |    37 +
 .../services/security/token/impl/JWT.java       |    60 +
 .../token/impl/JWTProviderMessages.java         |    61 +
 .../services/security/token/impl/JWTToken.java  |   278 +
 .../services/topology/TopologyService.java      |    50 +
 .../knox/gateway/topology/Application.java      |    30 +
 .../org/apache/knox/gateway/topology/Param.java |    50 +
 .../apache/knox/gateway/topology/Provider.java  |    85 +
 .../apache/knox/gateway/topology/Routable.java  |    22 +
 .../apache/knox/gateway/topology/Service.java   |   150 +
 .../apache/knox/gateway/topology/Topology.java  |   142 +
 .../knox/gateway/topology/TopologyEvent.java    |    40 +
 .../knox/gateway/topology/TopologyListener.java |    26 +
 .../knox/gateway/topology/TopologyMonitor.java  |    28 +
 .../knox/gateway/topology/TopologyProvider.java |    26 +
 .../apache/knox/gateway/topology/Version.java   |   135 +
 .../topology/builder/TopologyBuilder.java       |    24 +
 ...ay.config.spi.ConfigurationAdapterDescriptor |    18 -
 ...ay.config.spi.ConfigurationAdapterDescriptor |    18 +
 .../apache/hadoop/gateway/topology/jaxb.index   |    22 -
 .../hadoop/gateway/topology/jaxb.properties     |    16 -
 .../gateway/topology/topology_binding-json.xml  |    65 -
 .../gateway/topology/topology_binding-xml.xml   |    63 -
 .../org/apache/knox/gateway/topology/jaxb.index |    22 +
 .../knox/gateway/topology/jaxb.properties       |    16 +
 .../gateway/topology/topology_binding-json.xml  |    65 +
 .../gateway/topology/topology_binding-xml.xml   |    63 +
 .../dispatch/CappedBufferHttpEntityTest.java    |   854 --
 .../gateway/dispatch/DefaultDispatchTest.java   |   234 -
 .../PartiallyRepeatableHttpEntityTest.java      |   874 --
 .../security/principal/PrincipalMapperTest.java |   232 -
 .../hostmap/FileBasedHostMapperTest.java        |    64 -
 .../security/impl/CMFKeystoreServiceTest.java   |   162 -
 .../security/impl/CMFMasterServiceTest.java     |    59 -
 .../security/impl/TestCMFMasterService.java     |    37 -
 .../hadoop/gateway/topology/VersionTest.java    |    50 -
 .../dispatch/CappedBufferHttpEntityTest.java    |   854 ++
 .../gateway/dispatch/DefaultDispatchTest.java   |   234 +
 .../PartiallyRepeatableHttpEntityTest.java      |   874 ++
 .../security/principal/PrincipalMapperTest.java |   232 +
 .../hostmap/FileBasedHostMapperTest.java        |    64 +
 .../security/impl/CMFKeystoreServiceTest.java   |   162 +
 .../security/impl/CMFMasterServiceTest.java     |    59 +
 .../security/impl/TestCMFMasterService.java     |    37 +
 .../knox/gateway/topology/VersionTest.java      |    50 +
 .../hostmap/FileBasedHostMapperTest/hostmap.txt |     6 -
 .../hostmap/FileBasedHostMapperTest/hostmap.txt |     6 +
 .../hadoop/gateway/GatewayTestConfig.java       |   610 -
 .../hadoop/gateway/GatewayTestDriver.java       |   347 -
 .../apache/knox/gateway/GatewayTestConfig.java  |   610 +
 .../apache/knox/gateway/GatewayTestDriver.java  |   347 +
 .../hadoop/gateway/SecureClusterTest.java       |   349 -
 .../apache/knox/gateway/SecureClusterTest.java  |   349 +
 .../org/apache/hadoop/gateway/ShellTest.java    |   198 -
 .../java/org/apache/knox/gateway/ShellTest.java |   189 +
 .../ShellTest/InsecureWebHdfsPutGet.groovy      |    39 -
 .../org/apache/hadoop/gateway/ShellTest/README  |    57 -
 .../gateway/ShellTest/WebHdfsPutGet.groovy      |    40 -
 .../ShellTest/InsecureWebHdfsPutGet.groovy      |    39 +
 .../org/apache/knox/gateway/ShellTest/README    |    57 +
 .../knox/gateway/ShellTest/WebHdfsPutGet.groovy |    40 +
 .../gateway/AmbariServiceDefinitionTest.java    |   367 -
 .../hadoop/gateway/GatewayAdminFuncTest.java    |   218 -
 .../gateway/GatewayAdminTopologyFuncTest.java   |   837 --
 .../hadoop/gateway/GatewayAppFuncTest.java      |   688 -
 .../hadoop/gateway/GatewayBasicFuncTest.java    |  4435 -------
 .../hadoop/gateway/GatewayDeployFuncTest.java   |   354 -
 .../hadoop/gateway/GatewayHealthFuncTest.java   |   229 -
 .../GatewayLdapDynamicGroupFuncTest.java        |   329 -
 .../gateway/GatewayLdapGroupFuncTest.java       |   329 -
 .../gateway/GatewayLdapPosixGroupFuncTest.java  |   298 -
 .../gateway/GatewayLocalServiceFuncTest.java    |   222 -
 .../hadoop/gateway/GatewayMultiFuncTest.java    |   459 -
 .../GatewayPortMappingDisableFeatureTest.java   |   252 -
 .../gateway/GatewayPortMappingFailTest.java     |   150 -
 .../gateway/GatewayPortMappingFuncTest.java     |   279 -
 .../hadoop/gateway/GatewaySampleFuncTest.java   |   220 -
 .../hadoop/gateway/GatewaySslFuncTest.java      |   320 -
 .../apache/hadoop/gateway/Knox242FuncTest.java  |   323 -
 .../gateway/KnoxCliLdapFuncTestNegative.java    |   342 -
 .../gateway/KnoxCliLdapFuncTestPositive.java    |   344 -
 .../hadoop/gateway/KnoxCliSysBindTest.java      |   333 -
 .../gateway/OozieServiceDefinitionTest.java     |   211 -
 .../hadoop/gateway/TestJerseyService.java       |    34 -
 .../TestJerseyServiceDeploymentContributor.java |    44 -
 .../TestProviderDeploymentContributor.java      |    46 -
 .../TestServiceDeploymentContributor.java       |    49 -
 .../gateway/TestServiceDispatchFilter.java      |    44 -
 .../org/apache/hadoop/gateway/TestServlet.java  |    32 -
 .../hadoop/gateway/WebHdfsHaFuncTest.java       |   467 -
 .../deploy/DeploymentFactoryFuncTest.java       |   683 -
 .../gateway/AmbariServiceDefinitionTest.java    |   367 +
 .../knox/gateway/GatewayAdminFuncTest.java      |   216 +
 .../gateway/GatewayAdminTopologyFuncTest.java   |   837 ++
 .../apache/knox/gateway/GatewayAppFuncTest.java |   688 +
 .../knox/gateway/GatewayBasicFuncTest.java      |  4434 +++++++
 .../knox/gateway/GatewayDeployFuncTest.java     |   353 +
 .../knox/gateway/GatewayHealthFuncTest.java     |   229 +
 .../GatewayLdapDynamicGroupFuncTest.java        |   323 +
 .../knox/gateway/GatewayLdapGroupFuncTest.java  |   324 +
 .../gateway/GatewayLdapPosixGroupFuncTest.java  |   297 +
 .../gateway/GatewayLocalServiceFuncTest.java    |   224 +
 .../knox/gateway/GatewayMultiFuncTest.java      |   459 +
 .../GatewayPortMappingDisableFeatureTest.java   |   252 +
 .../gateway/GatewayPortMappingFailTest.java     |   150 +
 .../gateway/GatewayPortMappingFuncTest.java     |   276 +
 .../knox/gateway/GatewaySampleFuncTest.java     |   219 +
 .../apache/knox/gateway/GatewaySslFuncTest.java |   319 +
 .../apache/knox/gateway/Knox242FuncTest.java    |   318 +
 .../gateway/KnoxCliLdapFuncTestNegative.java    |   339 +
 .../gateway/KnoxCliLdapFuncTestPositive.java    |   343 +
 .../apache/knox/gateway/KnoxCliSysBindTest.java |   332 +
 .../gateway/OozieServiceDefinitionTest.java     |   212 +
 .../apache/knox/gateway/TestJerseyService.java  |    34 +
 .../TestJerseyServiceDeploymentContributor.java |    45 +
 .../TestProviderDeploymentContributor.java      |    47 +
 .../TestServiceDeploymentContributor.java       |    49 +
 .../knox/gateway/TestServiceDispatchFilter.java |    44 +
 .../org/apache/knox/gateway/TestServlet.java    |    32 +
 .../apache/knox/gateway/WebHdfsHaFuncTest.java  |   466 +
 .../deploy/DeploymentFactoryFuncTest.java       |   683 +
 ...gateway.deploy.ProviderDeploymentContributor |    19 -
 ....gateway.deploy.ServiceDeploymentContributor |    20 -
 ...gateway.deploy.ProviderDeploymentContributor |    19 +
 ....gateway.deploy.ServiceDeploymentContributor |    20 +
 .../clusters-response-expected.json             |    13 -
 .../clusters-response.json                      |    13 -
 .../encrypted-response.txt                      |     1 -
 .../history-server-response-expected.json       |   250 -
 .../history-server-response.json                |   250 -
 .../post-data-wrong-type.json                   |   421 -
 .../test-svcs/readme.txt                        |    18 -
 .../test-topology.xml                           |    34 -
 .../unwise-character-response.json              |   410 -
 .../views-response-expected.json                |   328 -
 .../views-response.json                         |   328 -
 .../test-cluster.xml                            |    82 -
 .../dynamic-app/app.war/WEB-INF/web.xml         |    15 -
 .../GatewayAppFuncTest/test-apps/readme.txt     |    18 -
 .../test-apps/static-hello-app/app/index.html   |    24 -
 .../test-apps/static-json-app/app.dir/one.json  |     3 -
 .../test-apps/static-json-app/rewrite.xml       |    17 -
 .../test-apps/static-json-app/service.xml       |    21 -
 .../test-apps/static-xml-app/app/test.xml       |    17 -
 .../test-default-app-name-topology.xml          |    53 -
 .../test-dynamic-app-topology.xml               |    54 -
 .../test-multi-apps-topology.xml                |    65 -
 .../test-naked-app-topology.xml                 |    33 -
 .../test-static-hello-topology.xml              |    54 -
 .../test-svcs-and-apps-topology.xml             |    62 -
 .../GatewayAppFuncTest/test-svcs/readme.txt     |    18 -
 .../test-svcs/webhdfs/2.4.0/rewrite.xml         |    70 -
 .../test-svcs/webhdfs/2.4.0/service.xml         |    43 -
 .../gateway/GatewayBasicFuncTest/changes.txt    | 11730 -----------------
 .../falcon/cleanseEmailProcess.xml              |    36 -
 .../falcon/cleansedEmailFeed.xml                |    43 -
 .../falcon/config-build.json                    |    32 -
 .../falcon/config-build.xml                     |    31 -
 .../falcon/config-deploy.json                   |     1 -
 .../falcon/config-deploy.xml                    |    11 -
 .../falcon/config-runtime.json                  |    24 -
 .../falcon/config-runtime.xml                   |    23 -
 .../falcon/config-startup.json                  |   188 -
 .../falcon/config-startup.xml                   |   192 -
 .../falcon/emailIngestProcess.xml               |    29 -
 .../falcon/entity-delete-process.json           |     5 -
 .../falcon/entity-dependency-process.xml        |    22 -
 .../falcon/entity-list-cluster.xml              |    11 -
 .../falcon/entity-resume-feed.xml               |     8 -
 .../falcon/entity-schedule-feed.xml             |     8 -
 .../falcon/entity-status-process.xml            |     8 -
 .../falcon/entity-submit-feed.json              |     5 -
 .../falcon/entity-submit-schedule-process.json  |     5 -
 .../falcon/entity-summary-feed.json             |     1 -
 .../falcon/entity-summary-feed.xml              |     5 -
 .../falcon/entity-update-feed.xml               |    10 -
 .../falcon/entity-validate-cluster.xml          |     5 -
 .../falcon/instance-params-process.json         |     1 -
 .../falcon/instance-process-logs.json           |    77 -
 .../falcon/instance-running-process.json        |    13 -
 .../falcon/instance-status-process.json         |     1 -
 .../falcon/metadata-disc-cluster-entity.json    |     1 -
 .../falcon/metadata-disc-cluster-relations.json |   106 -
 .../falcon/metadata-disc-process-entity.json    |     1 -
 .../falcon/metadata-lineage-edges-all.json      |   559 -
 .../falcon/metadata-lineage-edges-id.json       |     1 -
 .../falcon/metadata-lineage-vertices-all.json   |   238 -
 .../metadata-lineage-vertices-direction.json    |    34 -
 .../falcon/metadata-lineage-vertices-id.json    |    10 -
 .../falcon/metadata-lineage-vertices-key.json   |    13 -
 .../falcon/oregonCluster.xml                    |    15 -
 .../falcon/rawEmailFeed.xml                     |    28 -
 .../GatewayBasicFuncTest/falcon/stack.txt       |    40 -
 .../GatewayBasicFuncTest/falcon/version.json    |    16 -
 .../GatewayBasicFuncTest/falcon/version.xml     |    15 -
 .../falcon/virginiaCluster.xml                  |    15 -
 .../hbase/scanner-definition.xml                |    21 -
 .../GatewayBasicFuncTest/hbase/table-data.json  |    21 -
 .../hbase/table-data.protobuf                   |     9 -
 .../GatewayBasicFuncTest/hbase/table-data.xml   |    28 -
 .../GatewayBasicFuncTest/hbase/table-list.json  |    10 -
 .../hbase/table-list.protobuf                   |     3 -
 .../GatewayBasicFuncTest/hbase/table-list.xml   |    26 -
 .../hbase/table-metadata.json                   |    37 -
 .../hbase/table-metadata.protobuf               |     4 -
 .../hbase/table-metadata.xml                    |    28 -
 .../hbase/table-schema.json                     |    11 -
 .../hbase/table-schema.protobuf                 |     4 -
 .../GatewayBasicFuncTest/hbase/table-schema.xml |    22 -
 .../hive/close-operation-1-request.bin          |   Bin 96 -> 0 bytes
 .../hive/close-operation-1-result.bin           |   Bin 42 -> 0 bytes
 .../hive/close-operation-2-request.bin          |   Bin 96 -> 0 bytes
 .../hive/close-operation-2-result.bin           |   Bin 42 -> 0 bytes
 .../hive/close-operation-3-request.bin          |   Bin 96 -> 0 bytes
 .../hive/close-operation-3-result.bin           |   Bin 42 -> 0 bytes
 .../hive/close-operation-4-request.bin          |   Bin 96 -> 0 bytes
 .../hive/close-operation-4-result.bin           |   Bin 42 -> 0 bytes
 .../hive/close-operation-5-request.bin          |   Bin 96 -> 0 bytes
 .../hive/close-operation-5-result.bin           |   Bin 42 -> 0 bytes
 .../hive/close-operation-6-request.bin          |   Bin 96 -> 0 bytes
 .../hive/close-operation-6-result.bin           |   Bin 42 -> 0 bytes
 .../hive/close-session-request.bin              |   Bin 83 -> 0 bytes
 .../hive/close-session-result.bin               |   Bin 40 -> 0 bytes
 .../hive/execute-create-table-request.bin       |   Bin 147 -> 0 bytes
 .../hive/execute-create-table-result.bin        |   Bin 109 -> 0 bytes
 .../hive/execute-select-from-table-request.bin  |   Bin 126 -> 0 bytes
 .../hive/execute-select-from-table-result.bin   |   Bin 109 -> 0 bytes
 .../execute-set-fetch-output-serde-request.bin  |   Bin 183 -> 0 bytes
 .../execute-set-fetch-output-serde-result.bin   |   Bin 109 -> 0 bytes
 ...t-security-authorization-enabled-request.bin |   Bin 148 -> 0 bytes
 ...et-security-authorization-enabled-result.bin |   Bin 109 -> 0 bytes
 .../execute-set-server2-http-path-request.bin   |   Bin 149 -> 0 bytes
 .../execute-set-server2-http-path-result.bin    |   Bin 109 -> 0 bytes
 .../execute-set-server2-servermode-request.bin  |   Bin 136 -> 0 bytes
 .../execute-set-server2-servermode-result.bin   |   Bin 109 -> 0 bytes
 .../hive/fetch-results-request.bin              |   Bin 112 -> 0 bytes
 .../hive/fetch-results-result.bin               |   Bin 67 -> 0 bytes
 .../hive/get-result-set-metadata-request.bin    |   Bin 102 -> 0 bytes
 .../hive/get-result-set-metadata-result.bin     |   Bin 144 -> 0 bytes
 .../hive/open-session-request.bin               |   Bin 35 -> 0 bytes
 .../hive/open-session-result.bin                |   Bin 109 -> 0 bytes
 .../oozie-admin-build-version.json              |     3 -
 .../oozie-admin-configuration.json              |   152 -
 .../oozie-admin-instrumentation.json            |   836 --
 .../oozie-admin-java-sys-properties.json        |    77 -
 .../oozie-admin-os-env.json                     |    43 -
 .../oozie-admin-status.json                     |     3 -
 .../oozie-job-action-rerun-request.xml          |    37 -
 .../oozie-job-show-definition.xml               |    56 -
 .../oozie-job-show-info.json                    |    43 -
 .../GatewayBasicFuncTest/oozie-job-show-log.txt |   134 -
 .../gateway/GatewayBasicFuncTest/oozie-job.json |    43 -
 .../GatewayBasicFuncTest/oozie-jobs-empty.json  |     6 -
 .../GatewayBasicFuncTest/oozie-jobs-sample.json |    27 -
 .../oozie-jobs-submit-request.xml               |    43 -
 .../oozie-jobs-submit-response.json             |     3 -
 .../GatewayBasicFuncTest/oozie-versions.json    |     4 -
 .../GatewayBasicFuncTest/oozie-workflow.xml     |    40 -
 .../gateway/GatewayBasicFuncTest/passwd.txt     |     4 -
 .../gateway/GatewayBasicFuncTest/script.hive    |     1 -
 .../gateway/GatewayBasicFuncTest/script.pig     |     3 -
 .../gateway/GatewayBasicFuncTest/small1.txt     |    18 -
 .../gateway/GatewayBasicFuncTest/small2.txt     |    18 -
 .../storm/cluster-configuration.json            |   141 -
 .../storm/cluster-summary.json                  |    12 -
 .../storm/supervisor-summary.json               |    11 -
 .../storm/topology-component-id.json            |   122 -
 .../GatewayBasicFuncTest/storm/topology-id.json |   284 -
 .../storm/topology-summary.json                 |    15 -
 .../gateway/GatewayBasicFuncTest/test.txt       |     1 -
 .../webhcat-job-status.json                     |     1 -
 .../webhdfs-liststatus-default.json             |     5 -
 .../webhdfs-liststatus-empty.json               |     3 -
 .../webhdfs-liststatus-test.json                |     3 -
 .../GatewayBasicFuncTest/webhdfs-success.json   |     1 -
 .../GatewayBasicFuncTest/yarn/app_running.json  |    25 -
 .../GatewayBasicFuncTest/yarn/app_running.xml   |    40 -
 .../yarn/app_succeeded.json                     |    25 -
 .../GatewayBasicFuncTest/yarn/app_succeeded.xml |    40 -
 .../GatewayBasicFuncTest/yarn/appattempts.json  |    14 -
 .../GatewayBasicFuncTest/yarn/appattempts.xml   |    27 -
 .../yarn/application-killing.json               |     1 -
 .../yarn/application-submit-request.json        |    49 -
 .../gateway/GatewayBasicFuncTest/yarn/apps.json |    73 -
 .../gateway/GatewayBasicFuncTest/yarn/apps.xml  |    86 -
 .../yarn/appstatistics.json                     |    26 -
 .../GatewayBasicFuncTest/yarn/appstatistics.xml |    39 -
 .../GatewayBasicFuncTest/yarn/cluster-info.json |    14 -
 .../GatewayBasicFuncTest/yarn/cluster-info.xml  |    34 -
 .../yarn/cluster-metrics.json                   |    23 -
 .../yarn/cluster-metrics.xml                    |    38 -
 .../yarn/new-application.json                   |     1 -
 .../gateway/GatewayBasicFuncTest/yarn/node.json |    15 -
 .../gateway/GatewayBasicFuncTest/yarn/node.xml  |    30 -
 .../GatewayBasicFuncTest/yarn/nodes.json        |    19 -
 .../gateway/GatewayBasicFuncTest/yarn/nodes.xml |    32 -
 .../yarn/proxy-mapreduce-info.json              |     9 -
 .../yarn/proxy-mapreduce-info.xml               |    24 -
 .../yarn/proxy-mapreduce-job-attempts.json      |    14 -
 .../yarn/proxy-mapreduce-job-attempts.xml       |    27 -
 .../yarn/proxy-mapreduce-job-conf.json          |  5263 --------
 .../yarn/proxy-mapreduce-job-conf.xml           |  4019 ------
 .../yarn/proxy-mapreduce-job-counters.json      |   307 -
 .../yarn/proxy-mapreduce-job-counters.xml       |   313 -
 .../yarn/proxy-mapreduce-job.json               |    33 -
 .../yarn/proxy-mapreduce-job.xml                |    48 -
 .../yarn/proxy-mapreduce-jobs.json              |    37 -
 .../yarn/proxy-mapreduce-jobs.xml               |    50 -
 .../proxy-mapreduce-task-attempt-counters.json  |   155 -
 .../proxy-mapreduce-task-attempt-counters.xml   |   163 -
 .../yarn/proxy-mapreduce-task-attempt.json      |    21 -
 .../yarn/proxy-mapreduce-task-attempt.xml       |    37 -
 .../yarn/proxy-mapreduce-task-attempts.json     |    26 -
 .../yarn/proxy-mapreduce-task-attempts.xml      |    40 -
 .../yarn/proxy-mapreduce-task-counters.json     |   155 -
 .../yarn/proxy-mapreduce-task-counters.xml      |   160 -
 .../yarn/proxy-mapreduce-task.json              |    13 -
 .../yarn/proxy-mapreduce-task.xml               |    28 -
 .../yarn/proxy-mapreduce-tasks.json             |    28 -
 .../yarn/proxy-mapreduce-tasks.xml              |    42 -
 .../GatewayBasicFuncTest/yarn/scheduler.json    |    41 -
 .../GatewayBasicFuncTest/yarn/scheduler.xml     |    53 -
 .../GatewayLdapPosixGroupFuncTest/users.ldif    |   106 -
 .../applications/readme.txt                     |    18 -
 .../GatewayMultiFuncTest/services/readme.txt    |    18 -
 .../services/repeat/0.0.0/rewrite.xml           |    28 -
 .../services/repeat/0.0.0/service.xml           |    23 -
 .../test-knox678-utf8-chars-topology.xml        |    54 -
 ...knox694-principal-regex-search-attribute.xml |    81 -
 ...st-knox694-principal-regex-search-filter.xml |    77 -
 ...x694-principal-regex-search-scope-object.xml |    77 -
 ...pal-regex-search-scope-onelevel-negative.xml |    81 -
 ...pal-regex-search-scope-onelevel-positive.xml |    81 -
 ...knox694-principal-regex-user-dn-template.xml |    65 -
 .../GatewaySslFuncTest/test-admin-topology.xml  |    53 -
 .../oozie-request-relative.xml                  |    14 -
 .../oozie-request-with-complex-var.xml          |    14 -
 .../oozie-request-with-var.xml                  |    14 -
 .../webhdfs-liststatus-standby.json             |     5 -
 .../webhdfs-liststatus-success.json             |    88 -
 .../webhdfs-mkdirs-safemode.json                |     5 -
 .../webhdfs-rename-safemode-off.json            |     1 -
 .../webhdfs-rename-safemode.json                |     5 -
 .../test-apps/minimal-test-app/rewrite.xml      |    17 -
 .../test-apps/minimal-test-app/service.xml      |    21 -
 .../clusters-response-expected.json             |    13 +
 .../clusters-response.json                      |    13 +
 .../encrypted-response.txt                      |     1 +
 .../history-server-response-expected.json       |   250 +
 .../history-server-response.json                |   250 +
 .../post-data-wrong-type.json                   |   421 +
 .../test-svcs/readme.txt                        |    18 +
 .../test-topology.xml                           |    34 +
 .../unwise-character-response.json              |   410 +
 .../views-response-expected.json                |   328 +
 .../views-response.json                         |   328 +
 .../test-cluster.xml                            |    82 +
 .../dynamic-app/app.war/WEB-INF/web.xml         |    15 +
 .../GatewayAppFuncTest/test-apps/readme.txt     |    18 +
 .../test-apps/static-hello-app/app/index.html   |    24 +
 .../test-apps/static-json-app/app.dir/one.json  |     3 +
 .../test-apps/static-json-app/rewrite.xml       |    17 +
 .../test-apps/static-json-app/service.xml       |    21 +
 .../test-apps/static-xml-app/app/test.xml       |    17 +
 .../test-default-app-name-topology.xml          |    53 +
 .../test-dynamic-app-topology.xml               |    54 +
 .../test-multi-apps-topology.xml                |    65 +
 .../test-naked-app-topology.xml                 |    33 +
 .../test-static-hello-topology.xml              |    54 +
 .../test-svcs-and-apps-topology.xml             |    62 +
 .../GatewayAppFuncTest/test-svcs/readme.txt     |    18 +
 .../test-svcs/webhdfs/2.4.0/rewrite.xml         |    70 +
 .../test-svcs/webhdfs/2.4.0/service.xml         |    43 +
 .../gateway/GatewayBasicFuncTest/changes.txt    | 11730 +++++++++++++++++
 .../falcon/cleanseEmailProcess.xml              |    36 +
 .../falcon/cleansedEmailFeed.xml                |    43 +
 .../falcon/config-build.json                    |    32 +
 .../falcon/config-build.xml                     |    31 +
 .../falcon/config-deploy.json                   |     1 +
 .../falcon/config-deploy.xml                    |    11 +
 .../falcon/config-runtime.json                  |    24 +
 .../falcon/config-runtime.xml                   |    23 +
 .../falcon/config-startup.json                  |   188 +
 .../falcon/config-startup.xml                   |   192 +
 .../falcon/emailIngestProcess.xml               |    29 +
 .../falcon/entity-delete-process.json           |     5 +
 .../falcon/entity-dependency-process.xml        |    22 +
 .../falcon/entity-list-cluster.xml              |    11 +
 .../falcon/entity-resume-feed.xml               |     8 +
 .../falcon/entity-schedule-feed.xml             |     8 +
 .../falcon/entity-status-process.xml            |     8 +
 .../falcon/entity-submit-feed.json              |     5 +
 .../falcon/entity-submit-schedule-process.json  |     5 +
 .../falcon/entity-summary-feed.json             |     1 +
 .../falcon/entity-summary-feed.xml              |     5 +
 .../falcon/entity-update-feed.xml               |    10 +
 .../falcon/entity-validate-cluster.xml          |     5 +
 .../falcon/instance-params-process.json         |     1 +
 .../falcon/instance-process-logs.json           |    77 +
 .../falcon/instance-running-process.json        |    13 +
 .../falcon/instance-status-process.json         |     1 +
 .../falcon/metadata-disc-cluster-entity.json    |     1 +
 .../falcon/metadata-disc-cluster-relations.json |   106 +
 .../falcon/metadata-disc-process-entity.json    |     1 +
 .../falcon/metadata-lineage-edges-all.json      |   559 +
 .../falcon/metadata-lineage-edges-id.json       |     1 +
 .../falcon/metadata-lineage-vertices-all.json   |   238 +
 .../metadata-lineage-vertices-direction.json    |    34 +
 .../falcon/metadata-lineage-vertices-id.json    |    10 +
 .../falcon/metadata-lineage-vertices-key.json   |    13 +
 .../falcon/oregonCluster.xml                    |    15 +
 .../falcon/rawEmailFeed.xml                     |    28 +
 .../GatewayBasicFuncTest/falcon/stack.txt       |    40 +
 .../GatewayBasicFuncTest/falcon/version.json    |    16 +
 .../GatewayBasicFuncTest/falcon/version.xml     |    15 +
 .../falcon/virginiaCluster.xml                  |    15 +
 .../hbase/scanner-definition.xml                |    21 +
 .../GatewayBasicFuncTest/hbase/table-data.json  |    21 +
 .../hbase/table-data.protobuf                   |     9 +
 .../GatewayBasicFuncTest/hbase/table-data.xml   |    28 +
 .../GatewayBasicFuncTest/hbase/table-list.json  |    10 +
 .../hbase/table-list.protobuf                   |     3 +
 .../GatewayBasicFuncTest/hbase/table-list.xml   |    26 +
 .../hbase/table-metadata.json                   |    37 +
 .../hbase/table-metadata.protobuf               |     4 +
 .../hbase/table-metadata.xml                    |    28 +
 .../hbase/table-schema.json                     |    11 +
 .../hbase/table-schema.protobuf                 |     4 +
 .../GatewayBasicFuncTest/hbase/table-schema.xml |    22 +
 .../hive/close-operation-1-request.bin          |   Bin 0 -> 96 bytes
 .../hive/close-operation-1-result.bin           |   Bin 0 -> 42 bytes
 .../hive/close-operation-2-request.bin          |   Bin 0 -> 96 bytes
 .../hive/close-operation-2-result.bin           |   Bin 0 -> 42 bytes
 .../hive/close-operation-3-request.bin          |   Bin 0 -> 96 bytes
 .../hive/close-operation-3-result.bin           |   Bin 0 -> 42 bytes
 .../hive/close-operation-4-request.bin          |   Bin 0 -> 96 bytes
 .../hive/close-operation-4-result.bin           |   Bin 0 -> 42 bytes
 .../hive/close-operation-5-request.bin          |   Bin 0 -> 96 bytes
 .../hive/close-operation-5-result.bin           |   Bin 0 -> 42 bytes
 .../hive/close-operation-6-request.bin          |   Bin 0 -> 96 bytes
 .../hive/close-operation-6-result.bin           |   Bin 0 -> 42 bytes
 .../hive/close-session-request.bin              |   Bin 0 -> 83 bytes
 .../hive/close-session-result.bin               |   Bin 0 -> 40 bytes
 .../hive/execute-create-table-request.bin       |   Bin 0 -> 147 bytes
 .../hive/execute-create-table-result.bin        |   Bin 0 -> 109 bytes
 .../hive/execute-select-from-table-request.bin  |   Bin 0 -> 126 bytes
 .../hive/execute-select-from-table-result.bin   |   Bin 0 -> 109 bytes
 .../execute-set-fetch-output-serde-request.bin  |   Bin 0 -> 183 bytes
 .../execute-set-fetch-output-serde-result.bin   |   Bin 0 -> 109 bytes
 ...t-security-authorization-enabled-request.bin |   Bin 0 -> 148 bytes
 ...et-security-authorization-enabled-result.bin |   Bin 0 -> 109 bytes
 .../execute-set-server2-http-path-request.bin   |   Bin 0 -> 149 bytes
 .../execute-set-server2-http-path-result.bin    |   Bin 0 -> 109 bytes
 .../execute-set-server2-servermode-request.bin  |   Bin 0 -> 136 bytes
 .../execute-set-server2-servermode-result.bin   |   Bin 0 -> 109 bytes
 .../hive/fetch-results-request.bin              |   Bin 0 -> 112 bytes
 .../hive/fetch-results-result.bin               |   Bin 0 -> 67 bytes
 .../hive/get-result-set-metadata-request.bin    |   Bin 0 -> 102 bytes
 .../hive/get-result-set-metadata-result.bin     |   Bin 0 -> 144 bytes
 .../hive/open-session-request.bin               |   Bin 0 -> 35 bytes
 .../hive/open-session-result.bin                |   Bin 0 -> 109 bytes
 .../oozie-admin-build-version.json              |     3 +
 .../oozie-admin-configuration.json              |   152 +
 .../oozie-admin-instrumentation.json            |   836 ++
 .../oozie-admin-java-sys-properties.json        |    77 +
 .../oozie-admin-os-env.json                     |    43 +
 .../oozie-admin-status.json                     |     3 +
 .../oozie-job-action-rerun-request.xml          |    37 +
 .../oozie-job-show-definition.xml               |    56 +
 .../oozie-job-show-info.json                    |    43 +
 .../GatewayBasicFuncTest/oozie-job-show-log.txt |   134 +
 .../gateway/GatewayBasicFuncTest/oozie-job.json |    43 +
 .../GatewayBasicFuncTest/oozie-jobs-empty.json  |     6 +
 .../GatewayBasicFuncTest/oozie-jobs-sample.json |    27 +
 .../oozie-jobs-submit-request.xml               |    43 +
 .../oozie-jobs-submit-response.json             |     3 +
 .../GatewayBasicFuncTest/oozie-versions.json    |     4 +
 .../GatewayBasicFuncTest/oozie-workflow.xml     |    40 +
 .../gateway/GatewayBasicFuncTest/passwd.txt     |     4 +
 .../gateway/GatewayBasicFuncTest/script.hive    |     1 +
 .../gateway/GatewayBasicFuncTest/script.pig     |     3 +
 .../gateway/GatewayBasicFuncTest/small1.txt     |    18 +
 .../gateway/GatewayBasicFuncTest/small2.txt     |    18 +
 .../storm/cluster-configuration.json            |   141 +
 .../storm/cluster-summary.json                  |    12 +
 .../storm/supervisor-summary.json               |    11 +
 .../storm/topology-component-id.json            |   122 +
 .../GatewayBasicFuncTest/storm/topology-id.json |   284 +
 .../storm/topology-summary.json                 |    15 +
 .../knox/gateway/GatewayBasicFuncTest/test.txt  |     1 +
 .../webhcat-job-status.json                     |     1 +
 .../webhdfs-liststatus-default.json             |     5 +
 .../webhdfs-liststatus-empty.json               |     3 +
 .../webhdfs-liststatus-test.json                |     3 +
 .../GatewayBasicFuncTest/webhdfs-success.json   |     1 +
 .../GatewayBasicFuncTest/yarn/app_running.json  |    25 +
 .../GatewayBasicFuncTest/yarn/app_running.xml   |    40 +
 .../yarn/app_succeeded.json                     |    25 +
 .../GatewayBasicFuncTest/yarn/app_succeeded.xml |    40 +
 .../GatewayBasicFuncTest/yarn/appattempts.json  |    14 +
 .../GatewayBasicFuncTest/yarn/appattempts.xml   |    27 +
 .../yarn/application-killing.json               |     1 +
 .../yarn/application-submit-request.json        |    49 +
 .../gateway/GatewayBasicFuncTest/yarn/apps.json |    73 +
 .../gateway/GatewayBasicFuncTest/yarn/apps.xml  |    86 +
 .../yarn/appstatistics.json                     |    26 +
 .../GatewayBasicFuncTest/yarn/appstatistics.xml |    39 +
 .../GatewayBasicFuncTest/yarn/cluster-info.json |    14 +
 .../GatewayBasicFuncTest/yarn/cluster-info.xml  |    34 +
 .../yarn/cluster-metrics.json                   |    23 +
 .../yarn/cluster-metrics.xml                    |    38 +
 .../yarn/new-application.json                   |     1 +
 .../gateway/GatewayBasicFuncTest/yarn/node.json |    15 +
 .../gateway/GatewayBasicFuncTest/yarn/node.xml  |    30 +
 .../GatewayBasicFuncTest/yarn/nodes.json        |    19 +
 .../gateway/GatewayBasicFuncTest/yarn/nodes.xml |    32 +
 .../yarn/proxy-mapreduce-info.json              |     9 +
 .../yarn/proxy-mapreduce-info.xml               |    24 +
 .../yarn/proxy-mapreduce-job-attempts.json      |    14 +
 .../yarn/proxy-mapreduce-job-attempts.xml       |    27 +
 .../yarn/proxy-mapreduce-job-conf.json          |  5263 ++++++++
 .../yarn/proxy-mapreduce-job-conf.xml           |  4019 ++++++
 .../yarn/proxy-mapreduce-job-counters.json      |   307 +
 .../yarn/proxy-mapreduce-job-counters.xml       |   313 +
 .../yarn/proxy-mapreduce-job.json               |    33 +
 .../yarn/proxy-mapreduce-job.xml                |    48 +
 .../yarn/proxy-mapreduce-jobs.json              |    37 +
 .../yarn/proxy-mapreduce-jobs.xml               |    50 +
 .../proxy-mapreduce-task-attempt-counters.json  |   155 +
 .../proxy-mapreduce-task-attempt-counters.xml   |   163 +
 .../yarn/proxy-mapreduce-task-attempt.json      |    21 +
 .../yarn/proxy-mapreduce-task-attempt.xml       |    37 +
 .../yarn/proxy-mapreduce-task-attempts.json     |    26 +
 .../yarn/proxy-mapreduce-task-attempts.xml      |    40 +
 .../yarn/proxy-mapreduce-task-counters.json     |   155 +
 .../yarn/proxy-mapreduce-task-counters.xml      |   160 +
 .../yarn/proxy-mapreduce-task.json              |    13 +
 .../yarn/proxy-mapreduce-task.xml               |    28 +
 .../yarn/proxy-mapreduce-tasks.json             |    28 +
 .../yarn/proxy-mapreduce-tasks.xml              |    42 +
 .../GatewayBasicFuncTest/yarn/scheduler.json    |    41 +
 .../GatewayBasicFuncTest/yarn/scheduler.xml     |    53 +
 .../GatewayLdapPosixGroupFuncTest/users.ldif    |   106 +
 .../applications/readme.txt                     |    18 +
 .../GatewayMultiFuncTest/services/readme.txt    |    18 +
 .../services/repeat/0.0.0/rewrite.xml           |    28 +
 .../services/repeat/0.0.0/service.xml           |    23 +
 .../test-knox678-utf8-chars-topology.xml        |    54 +
 ...knox694-principal-regex-search-attribute.xml |    81 +
 ...st-knox694-principal-regex-search-filter.xml |    77 +
 ...x694-principal-regex-search-scope-object.xml |    77 +
 ...pal-regex-search-scope-onelevel-negative.xml |    81 +
 ...pal-regex-search-scope-onelevel-positive.xml |    81 +
 ...knox694-principal-regex-user-dn-template.xml |    65 +
 .../GatewaySslFuncTest/test-admin-topology.xml  |    53 +
 .../oozie-request-relative.xml                  |    14 +
 .../oozie-request-with-complex-var.xml          |    14 +
 .../oozie-request-with-var.xml                  |    14 +
 .../webhdfs-liststatus-standby.json             |     5 +
 .../webhdfs-liststatus-success.json             |    88 +
 .../webhdfs-mkdirs-safemode.json                |     5 +
 .../webhdfs-rename-safemode-off.json            |     1 +
 .../webhdfs-rename-safemode.json                |     5 +
 .../test-apps/minimal-test-app/rewrite.xml      |    17 +
 .../test-apps/minimal-test-app/service.xml      |    21 +
 .../apache/hadoop/gateway/audit/api/Action.java |    34 -
 .../hadoop/gateway/audit/api/ActionOutcome.java |    36 -
 .../hadoop/gateway/audit/api/AuditContext.java  |    51 -
 .../hadoop/gateway/audit/api/AuditService.java  |    77 -
 .../gateway/audit/api/AuditServiceFactory.java  |    43 -
 .../hadoop/gateway/audit/api/Auditor.java       |    86 -
 .../gateway/audit/api/CorrelationContext.java   |    74 -
 .../gateway/audit/api/CorrelationService.java   |    99 -
 .../audit/api/CorrelationServiceFactory.java    |    44 -
 .../hadoop/gateway/audit/api/ResourceType.java  |    28 -
 .../gateway/audit/log4j/appender/JdbmQueue.java |   176 -
 .../appender/JdbmStoreAndForwardAppender.java   |   123 -
 .../audit/log4j/audit/AuditConstants.java       |    35 -
 .../audit/log4j/audit/Log4jAuditContext.java    |   113 -
 .../audit/log4j/audit/Log4jAuditService.java    |    84 -
 .../gateway/audit/log4j/audit/Log4jAuditor.java |   111 -
 .../correlation/Log4jCorrelationContext.java    |   105 -
 .../correlation/Log4jCorrelationService.java    |   128 -
 .../gateway/audit/log4j/layout/AuditLayout.java |    79 -
 .../gateway/i18n/GatewayUtilCommonMessages.java |    36 -
 .../SynchronousServletInputStreamAdapter.java   |    39 -
 .../SynchronousServletOutputStreamAdapter.java  |    34 -
 .../hadoop/gateway/util/CertificateUtils.java   |    65 -
 .../apache/hadoop/gateway/util/HttpUtils.java   |   123 -
 .../hadoop/gateway/util/IpAddressValidator.java |   116 -
 .../apache/hadoop/gateway/util/JsonPath.java    |   386 -
 .../apache/hadoop/gateway/util/JsonUtils.java   |    70 -
 .../apache/hadoop/gateway/util/MimeTypeMap.java |   110 -
 .../apache/hadoop/gateway/util/MimeTypes.java   |    78 -
 .../apache/hadoop/gateway/util/RegExUtils.java  |    43 -
 .../org/apache/hadoop/gateway/util/Urls.java    |   176 -
 .../gateway/util/X500PrincipalParser.java       |   189 -
 .../apache/hadoop/gateway/util/XmlUtils.java    |   107 -
 .../apache/knox/gateway/audit/api/Action.java   |    34 +
 .../knox/gateway/audit/api/ActionOutcome.java   |    36 +
 .../knox/gateway/audit/api/AuditContext.java    |    51 +
 .../knox/gateway/audit/api/AuditService.java    |    77 +
 .../gateway/audit/api/AuditServiceFactory.java  |    43 +
 .../apache/knox/gateway/audit/api/Auditor.java  |    86 +
 .../gateway/audit/api/CorrelationContext.java   |    74 +
 .../gateway/audit/api/CorrelationService.java   |    99 +
 .../audit/api/CorrelationServiceFactory.java    |    44 +
 .../knox/gateway/audit/api/ResourceType.java    |    28 +
 .../gateway/audit/log4j/appender/JdbmQueue.java |   176 +
 .../appender/JdbmStoreAndForwardAppender.java   |   123 +
 .../audit/log4j/audit/AuditConstants.java       |    35 +
 .../audit/log4j/audit/Log4jAuditContext.java    |   113 +
 .../audit/log4j/audit/Log4jAuditService.java    |    84 +
 .../gateway/audit/log4j/audit/Log4jAuditor.java |   111 +
 .../correlation/Log4jCorrelationContext.java    |   105 +
 .../correlation/Log4jCorrelationService.java    |   128 +
 .../gateway/audit/log4j/layout/AuditLayout.java |    79 +
 .../gateway/i18n/GatewayUtilCommonMessages.java |    36 +
 .../SynchronousServletInputStreamAdapter.java   |    39 +
 .../SynchronousServletOutputStreamAdapter.java  |    34 +
 .../knox/gateway/util/CertificateUtils.java     |    65 +
 .../org/apache/knox/gateway/util/HttpUtils.java |   123 +
 .../knox/gateway/util/IpAddressValidator.java   |   116 +
 .../org/apache/knox/gateway/util/JsonPath.java  |   386 +
 .../org/apache/knox/gateway/util/JsonUtils.java |    70 +
 .../apache/knox/gateway/util/MimeTypeMap.java   |   110 +
 .../org/apache/knox/gateway/util/MimeTypes.java |    78 +
 .../apache/knox/gateway/util/RegExUtils.java    |    43 +
 .../java/org/apache/knox/gateway/util/Urls.java |   176 +
 .../knox/gateway/util/X500PrincipalParser.java  |   189 +
 .../org/apache/knox/gateway/util/XmlUtils.java  |   107 +
 .../hadoop/gateway/audit/AuditLayoutTest.java   |   156 -
 .../hadoop/gateway/audit/AuditServiceTest.java  |   187 -
 .../hadoop/gateway/audit/JdbmQueueTest.java     |   297 -
 .../audit/StoreAndForwardAppenderTest.java      |    71 -
 .../hadoop/gateway/util/HttpUtilsTest.java      |   213 -
 .../gateway/util/IpAddressValidatorTest.java    |    78 -
 .../hadoop/gateway/util/JsonPathTest.java       |   580 -
 .../hadoop/gateway/util/JsonUtilsTest.java      |    57 -
 .../hadoop/gateway/util/MimeTypeMapTest.java    |    52 -
 .../apache/hadoop/gateway/util/UrlsTest.java    |    98 -
 .../knox/gateway/audit/AuditLayoutTest.java     |   157 +
 .../knox/gateway/audit/AuditServiceTest.java    |   187 +
 .../knox/gateway/audit/JdbmQueueTest.java       |   296 +
 .../audit/StoreAndForwardAppenderTest.java      |    71 +
 .../apache/knox/gateway/util/HttpUtilsTest.java |   213 +
 .../gateway/util/IpAddressValidatorTest.java    |    78 +
 .../apache/knox/gateway/util/JsonPathTest.java  |   580 +
 .../apache/knox/gateway/util/JsonUtilsTest.java |    57 +
 .../knox/gateway/util/MimeTypeMapTest.java      |    52 +
 .../org/apache/knox/gateway/util/UrlsTest.java  |    98 +
 .../src/test/resources/audit-log4j.properties   |     2 +-
 .../org/apache/hadoop/gateway/config/Alias.java |    31 -
 .../gateway/config/ConfigurationAdapter.java    |    24 -
 .../gateway/config/ConfigurationBinding.java    |    24 -
 .../gateway/config/ConfigurationException.java  |    30 -
 .../config/ConfigurationInjectorBuilder.java    |   107 -
 .../apache/hadoop/gateway/config/Configure.java |    30 -
 .../apache/hadoop/gateway/config/Default.java   |    31 -
 .../apache/hadoop/gateway/config/Optional.java  |    30 -
 .../config/impl/BeanConfigurationAdapter.java   |    40 -
 .../BeanConfigurationAdapterDescriptor.java     |    30 -
 .../impl/ConfigurationAdapterFactory.java       |   132 -
 .../impl/DefaultConfigurationBinding.java       |    29 -
 .../impl/DefaultConfigurationInjector.java      |   229 -
 .../config/impl/MapConfigurationAdapter.java    |    37 -
 .../impl/MapConfigurationAdapterDescriptor.java |    30 -
 .../config/impl/MappedConfigurationBinding.java |    38 -
 .../impl/PropertiesConfigurationAdapter.java    |    38 -
 ...ropertiesConfigurationAdapterDescriptor.java |    30 -
 .../AbstractConfigurationAdapterDescriptor.java |    42 -
 .../spi/ConfigurationAdapterDescriptor.java     |    28 -
 .../config/spi/ConfigurationInjector.java       |    27 -
 .../org/apache/knox/gateway/config/Alias.java   |    31 +
 .../gateway/config/ConfigurationAdapter.java    |    24 +
 .../gateway/config/ConfigurationBinding.java    |    24 +
 .../gateway/config/ConfigurationException.java  |    30 +
 .../config/ConfigurationInjectorBuilder.java    |   107 +
 .../apache/knox/gateway/config/Configure.java   |    30 +
 .../org/apache/knox/gateway/config/Default.java |    31 +
 .../apache/knox/gateway/config/Optional.java    |    30 +
 .../config/impl/BeanConfigurationAdapter.java   |    40 +
 .../BeanConfigurationAdapterDescriptor.java     |    29 +
 .../impl/ConfigurationAdapterFactory.java       |   132 +
 .../impl/DefaultConfigurationBinding.java       |    29 +
 .../impl/DefaultConfigurationInjector.java      |   235 +
 .../config/impl/MapConfigurationAdapter.java    |    37 +
 .../impl/MapConfigurationAdapterDescriptor.java |    31 +
 .../config/impl/MappedConfigurationBinding.java |    38 +
 .../impl/PropertiesConfigurationAdapter.java    |    38 +
 ...ropertiesConfigurationAdapterDescriptor.java |    31 +
 .../AbstractConfigurationAdapterDescriptor.java |    42 +
 .../spi/ConfigurationAdapterDescriptor.java     |    28 +
 .../config/spi/ConfigurationInjector.java       |    27 +
 ...ay.config.spi.ConfigurationAdapterDescriptor |    20 -
 ...oop.gateway.config.spi.ConfigurationInjector |    18 -
 ...ay.config.spi.ConfigurationAdapterDescriptor |    20 +
 ...nox.gateway.config.spi.ConfigurationInjector |    18 +
 .../gateway/config/AdapterSampleTest.java       |    57 -
 .../apache/hadoop/gateway/config/FuncTest.java  |   379 -
 .../gateway/config/MapFieldSampleTest.java      |    45 -
 .../gateway/config/MapMethodSampleTest.java     |    49 -
 .../hadoop/gateway/config/OptionalTest.java     |    59 -
 .../config/PropertiesFactorySampleTest.java     |    40 -
 .../config/PropertiesFieldSampleTest.java       |    39 -
 .../config/PropertiesMethodSampleTest.java      |    57 -
 .../apache/hadoop/gateway/config/UsageTest.java |    43 -
 .../BeanConfigurationAdapterDescriptorTest.java |    57 -
 .../impl/BeanConfigurationAdapterTest.java      |    40 -
 .../knox/gateway/config/AdapterSampleTest.java  |    57 +
 .../apache/knox/gateway/config/FuncTest.java    |   378 +
 .../knox/gateway/config/MapFieldSampleTest.java |    45 +
 .../gateway/config/MapMethodSampleTest.java     |    49 +
 .../knox/gateway/config/OptionalTest.java       |    58 +
 .../config/PropertiesFactorySampleTest.java     |    39 +
 .../config/PropertiesFieldSampleTest.java       |    39 +
 .../config/PropertiesMethodSampleTest.java      |    57 +
 .../apache/knox/gateway/config/UsageTest.java   |    43 +
 .../BeanConfigurationAdapterDescriptorTest.java |    57 +
 .../impl/BeanConfigurationAdapterTest.java      |    40 +
 .../apache/hadoop/gateway/launcher/Command.java |   156 -
 .../apache/hadoop/gateway/launcher/Config.java  |   149 -
 .../apache/hadoop/gateway/launcher/Forker.java  |    32 -
 .../apache/hadoop/gateway/launcher/Invoker.java |    92 -
 .../hadoop/gateway/launcher/Launcher.java       |   174 -
 .../hadoop/gateway/launcher/Streamer.java       |    52 -
 .../apache/knox/gateway/launcher/Command.java   |   156 +
 .../apache/knox/gateway/launcher/Config.java    |   149 +
 .../apache/knox/gateway/launcher/Forker.java    |    32 +
 .../apache/knox/gateway/launcher/Invoker.java   |    92 +
 .../apache/knox/gateway/launcher/Launcher.java  |   174 +
 .../apache/knox/gateway/launcher/Streamer.java  |    52 +
 .../hadoop/gateway/launcher/ConfigTest.java     |   116 -
 .../knox/gateway/launcher/ConfigTest.java       |   116 +
 .../gateway/util/urltemplate/Builder.java       |   402 -
 .../gateway/util/urltemplate/Evaluator.java     |    26 -
 .../gateway/util/urltemplate/Expander.java      |   320 -
 .../gateway/util/urltemplate/Fragment.java      |    34 -
 .../gateway/util/urltemplate/Function.java      |   114 -
 .../hadoop/gateway/util/urltemplate/Host.java   |    34 -
 .../gateway/util/urltemplate/Matcher.java       |   521 -
 .../gateway/util/urltemplate/Messages.java      |    22 -
 .../gateway/util/urltemplate/MockParams.java    |    58 -
 .../hadoop/gateway/util/urltemplate/Params.java |    26 -
 .../hadoop/gateway/util/urltemplate/Parser.java |   345 -
 .../gateway/util/urltemplate/Password.java      |    34 -
 .../hadoop/gateway/util/urltemplate/Path.java   |    34 -
 .../hadoop/gateway/util/urltemplate/Port.java   |    34 -
 .../hadoop/gateway/util/urltemplate/Query.java  |    53 -
 .../gateway/util/urltemplate/Resolver.java      |    26 -
 .../gateway/util/urltemplate/Resources.java     |    28 -
 .../gateway/util/urltemplate/Rewriter.java      |   102 -
 .../hadoop/gateway/util/urltemplate/Scheme.java |    34 -
 .../gateway/util/urltemplate/Segment.java       |   374 -
 .../gateway/util/urltemplate/Template.java      |   345 -
 .../hadoop/gateway/util/urltemplate/Token.java  |    55 -
 .../gateway/util/urltemplate/Username.java      |    34 -
 .../knox/gateway/util/urltemplate/Builder.java  |   402 +
 .../gateway/util/urltemplate/Evaluator.java     |    26 +
 .../knox/gateway/util/urltemplate/Expander.java |   320 +
 .../knox/gateway/util/urltemplate/Fragment.java |    34 +
 .../knox/gateway/util/urltemplate/Function.java |   114 +
 .../knox/gateway/util/urltemplate/Host.java     |    34 +
 .../knox/gateway/util/urltemplate/Matcher.java  |   521 +
 .../knox/gateway/util/urltemplate/Messages.java |    22 +
 .../gateway/util/urltemplate/MockParams.java    |    58 +
 .../knox/gateway/util/urltemplate/Params.java   |    26 +
 .../knox/gateway/util/urltemplate/Parser.java   |   345 +
 .../knox/gateway/util/urltemplate/Password.java |    34 +
 .../knox/gateway/util/urltemplate/Path.java     |    34 +
 .../knox/gateway/util/urltemplate/Port.java     |    34 +
 .../knox/gateway/util/urltemplate/Query.java    |    53 +
 .../knox/gateway/util/urltemplate/Resolver.java |    26 +
 .../gateway/util/urltemplate/Resources.java     |    28 +
 .../knox/gateway/util/urltemplate/Rewriter.java |   102 +
 .../knox/gateway/util/urltemplate/Scheme.java   |    34 +
 .../knox/gateway/util/urltemplate/Segment.java  |   374 +
 .../knox/gateway/util/urltemplate/Template.java |   345 +
 .../knox/gateway/util/urltemplate/Token.java    |    55 +
 .../knox/gateway/util/urltemplate/Username.java |    34 +
 .../gateway/util/urltemplate/ExpanderTest.java  |   538 -
 .../gateway/util/urltemplate/FunctionTest.java  |   167 -
 .../gateway/util/urltemplate/MatcherTest.java   |  1008 --
 .../util/urltemplate/MatcherTest.java.orig      |   839 --
 .../gateway/util/urltemplate/ParserTest.java    |  1305 --
 .../gateway/util/urltemplate/RewriterTest.java  |   422 -
 .../gateway/util/urltemplate/SegmentTest.java   |   145 -
 .../gateway/util/urltemplate/TemplateTest.java  |   177 -
 .../gateway/util/urltemplate/TokenTest.java     |    42 -
 .../gateway/util/urltemplate/ExpanderTest.java  |   538 +
 .../gateway/util/urltemplate/FunctionTest.java  |   167 +
 .../gateway/util/urltemplate/MatcherTest.java   |  1008 ++
 .../util/urltemplate/MatcherTest.java.orig      |   839 ++
 .../gateway/util/urltemplate/ParserTest.java    |  1305 ++
 .../gateway/util/urltemplate/RewriterTest.java  |   421 +
 .../gateway/util/urltemplate/SegmentTest.java   |   145 +
 .../gateway/util/urltemplate/TemplateTest.java  |   176 +
 .../gateway/util/urltemplate/TokenTest.java     |    42 +
 .../org/apache/hadoop/examples/WordCount.java   |    84 -
 .../org/apache/knox/examples/WordCount.java     |    84 +
 knox-cli-launcher/pom.xml                       |     2 +-
 2584 files changed, 147117 insertions(+), 147140 deletions(-)
----------------------------------------------------------------------



[49/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/SimpleLdapDirectoryServer.java
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/SimpleLdapDirectoryServer.java b/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/SimpleLdapDirectoryServer.java
deleted file mode 100644
index 12fe30d..0000000
--- a/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/SimpleLdapDirectoryServer.java
+++ /dev/null
@@ -1,124 +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.hadoop.gateway.security.ldap;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.directory.api.ldap.model.entry.DefaultModification;
-import org.apache.directory.api.ldap.model.entry.ModificationOperation;
-import org.apache.directory.api.ldap.model.exception.LdapException;
-import org.apache.directory.api.ldap.model.name.Dn;
-import org.apache.directory.server.core.api.CoreSession;
-import org.apache.directory.server.core.api.DirectoryService;
-import org.apache.directory.server.core.api.partition.Partition;
-import org.apache.directory.server.core.factory.DirectoryServiceFactory;
-import org.apache.directory.server.ldap.LdapServer;
-import org.apache.directory.server.protocol.shared.store.LdifFileLoader;
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
-import org.apache.directory.server.protocol.shared.transport.Transport;
-import org.apache.log4j.PropertyConfigurator;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.net.ServerSocket;
-import java.util.UUID;
-
-public class SimpleLdapDirectoryServer {
-
-  private DirectoryServiceFactory factory;
-
-  private DirectoryService service;
-
-  private LdapServer server;
-
-  public SimpleLdapDirectoryServer( String rootDn, File usersLdif, Transport... transports ) throws Exception {
-    if( !usersLdif.exists() ) {
-      throw new FileNotFoundException( usersLdif.getAbsolutePath() );
-    }
-
-    factory = new SimpleDirectoryServiceFactory();
-    factory.init( UUID.randomUUID().toString() );
-    service = factory.getDirectoryService();
-
-    enabledPosixSchema( service );
-
-    Partition partition = factory.getPartitionFactory().createPartition(
-        service.getSchemaManager(), service.getDnFactory(), "users", rootDn, 500,
-        service.getInstanceLayout().getInstanceDirectory() );
-    service.addPartition( partition );
-
-    CoreSession session = service.getAdminSession();
-    LdifFileLoader lfl = new LdifFileLoader( session, usersLdif, null );
-    lfl.execute();
-
-    server = new LdapServer();
-    server.setTransports( transports );
-    server.setDirectoryService( service );
-  }
-
-  private static void enabledPosixSchema( DirectoryService service ) throws LdapException {
-    service.getSchemaManager().getLoadedSchema( "nis" ).enable();
-    service.getAdminSession().modify(
-        new Dn( "cn=nis,ou=schema" ),
-        new DefaultModification( ModificationOperation.REPLACE_ATTRIBUTE, "m-disabled", "FALSE" ) );
-  }
-
-  public void start() throws Exception {
-    service.startup();
-    server.start();
-  }
-
-  public void stop( boolean clean ) throws Exception {
-    server.stop();
-    service.shutdown();
-    if( clean ) {
-      FileUtils.deleteDirectory( service.getInstanceLayout().getInstanceDirectory() );
-    }
-  }
-
-  public static void main( String[] args ) throws Exception {
-    PropertyConfigurator.configure( System.getProperty( "log4j.configuration" ) );
-
-    SimpleLdapDirectoryServer ldap;
-
-    File file;
-    if ( args.length < 1 ) {
-      file = new File( "conf/users.ldif" );
-    } else {
-      File dir = new File( args[0] );
-      if( !dir.exists() || !dir.isDirectory() ) {
-        throw new FileNotFoundException( dir.getAbsolutePath() );
-      }
-      file = new File( dir, "users.ldif" );
-    }
-
-    if( !file.exists() || !file.canRead() ) {
-      throw new FileNotFoundException( file.getAbsolutePath() );
-    }
-
-    int port = 33389;
-
-    // Make sure the port is free.
-    ServerSocket socket = new ServerSocket( port );
-    socket.close();
-
-    TcpTransport transport = new TcpTransport( port );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", file, transport );
-    ldap.start();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/BaseDirectoryService.java
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/BaseDirectoryService.java b/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/BaseDirectoryService.java
new file mode 100644
index 0000000..53add76
--- /dev/null
+++ b/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/BaseDirectoryService.java
@@ -0,0 +1,2323 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT 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.knox.gateway.security.ldap;
+
+
+import org.apache.directory.api.ldap.codec.api.LdapApiService;
+import org.apache.directory.api.ldap.codec.api.LdapApiServiceFactory;
+import org.apache.directory.api.ldap.model.constants.AuthenticationLevel;
+import org.apache.directory.api.ldap.model.constants.SchemaConstants;
+import org.apache.directory.api.ldap.model.csn.Csn;
+import org.apache.directory.api.ldap.model.csn.CsnFactory;
+import org.apache.directory.api.ldap.model.cursor.Cursor;
+import org.apache.directory.api.ldap.model.entry.Attribute;
+import org.apache.directory.api.ldap.model.entry.DefaultEntry;
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.apache.directory.api.ldap.model.entry.Modification;
+import org.apache.directory.api.ldap.model.entry.Value;
+import org.apache.directory.api.ldap.model.exception.LdapException;
+import org.apache.directory.api.ldap.model.exception.LdapNoPermissionException;
+import org.apache.directory.api.ldap.model.exception.LdapOperationException;
+import org.apache.directory.api.ldap.model.ldif.ChangeType;
+import org.apache.directory.api.ldap.model.ldif.LdifEntry;
+import org.apache.directory.api.ldap.model.ldif.LdifReader;
+import org.apache.directory.api.ldap.model.name.Dn;
+import org.apache.directory.api.ldap.model.name.DnUtils;
+import org.apache.directory.api.ldap.model.name.Rdn;
+import org.apache.directory.api.ldap.model.schema.SchemaManager;
+import org.apache.directory.api.ldap.util.tree.DnNode;
+import org.apache.directory.api.util.DateUtils;
+import org.apache.directory.api.util.Strings;
+import org.apache.directory.api.util.exception.NotImplementedException;
+import org.apache.directory.server.constants.ServerDNConstants;
+import org.apache.directory.server.core.DefaultOperationManager;
+import org.apache.directory.server.core.admin.AdministrativePointInterceptor;
+import org.apache.directory.server.core.api.*;
+import org.apache.directory.server.core.api.administrative.AccessControlAdministrativePoint;
+import org.apache.directory.server.core.api.administrative.CollectiveAttributeAdministrativePoint;
+import org.apache.directory.server.core.api.administrative.SubschemaAdministrativePoint;
+import org.apache.directory.server.core.api.administrative.TriggerExecutionAdministrativePoint;
+import org.apache.directory.server.core.api.changelog.ChangeLog;
+import org.apache.directory.server.core.api.changelog.ChangeLogEvent;
+import org.apache.directory.server.core.api.changelog.Tag;
+import org.apache.directory.server.core.api.changelog.TaggableSearchableChangeLogStore;
+import org.apache.directory.server.core.api.event.EventService;
+import org.apache.directory.server.core.api.interceptor.BaseInterceptor;
+import org.apache.directory.server.core.api.interceptor.Interceptor;
+import org.apache.directory.server.core.api.interceptor.context.AddOperationContext;
+import org.apache.directory.server.core.api.interceptor.context.BindOperationContext;
+import org.apache.directory.server.core.api.interceptor.context.HasEntryOperationContext;
+import org.apache.directory.server.core.api.interceptor.context.LookupOperationContext;
+import org.apache.directory.server.core.api.interceptor.context.OperationContext;
+import org.apache.directory.server.core.api.journal.Journal;
+import org.apache.directory.server.core.api.partition.Partition;
+import org.apache.directory.server.core.api.partition.PartitionNexus;
+import org.apache.directory.server.core.api.schema.SchemaPartition;
+import org.apache.directory.server.core.api.subtree.SubentryCache;
+import org.apache.directory.server.core.api.subtree.SubtreeEvaluator;
+import org.apache.directory.server.core.authn.AuthenticationInterceptor;
+import org.apache.directory.server.core.authn.ppolicy.PpolicyConfigContainer;
+import org.apache.directory.server.core.authz.AciAuthorizationInterceptor;
+import org.apache.directory.server.core.authz.DefaultAuthorizationInterceptor;
+import org.apache.directory.server.core.changelog.ChangeLogInterceptor;
+import org.apache.directory.server.core.changelog.DefaultChangeLog;
+import org.apache.directory.server.core.collective.CollectiveAttributeInterceptor;
+import org.apache.directory.server.core.event.EventInterceptor;
+import org.apache.directory.server.core.exception.ExceptionInterceptor;
+import org.apache.directory.server.core.journal.DefaultJournal;
+import org.apache.directory.server.core.journal.JournalInterceptor;
+import org.apache.directory.server.core.normalization.NormalizationInterceptor;
+import org.apache.directory.server.core.operational.OperationalAttributeInterceptor;
+import org.apache.directory.server.core.referral.ReferralInterceptor;
+import org.apache.directory.server.core.schema.SchemaInterceptor;
+import org.apache.directory.server.core.security.TlsKeyGenerator;
+import org.apache.directory.server.core.shared.DefaultCoreSession;
+import org.apache.directory.server.core.shared.DefaultDnFactory;
+import org.apache.directory.server.core.shared.partition.DefaultPartitionNexus;
+import org.apache.directory.server.core.subtree.SubentryInterceptor;
+import org.apache.directory.server.core.trigger.TriggerInterceptor;
+import org.apache.directory.server.i18n.I18n;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.io.StringReader;
+import java.lang.reflect.Method;
+import java.nio.channels.FileLock;
+import java.nio.channels.OverlappingFileLockException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+
+/**
+ * Base implementation of {@link DirectoryService}.
+ * This is a copy of org.apache.directory.server.core.DefaultDirectoryService
+ * created to make showSecurityWarnings protected.  This can be removed
+ * when http://svn.apache.org/r1546144 in ApacheDS 2.0.0-M16 is available.
+ *
+ * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
+ */
+public class BaseDirectoryService implements DirectoryService
+{
+  /** The logger */
+  private static final Logger LOG = LoggerFactory.getLogger( BaseDirectoryService.class );
+
+  private SchemaPartition schemaPartition;
+
+  /** A reference on the SchemaManager */
+  private SchemaManager schemaManager;
+
+  /** The LDAP Codec Service */
+  private LdapApiService ldapCodecService = LdapApiServiceFactory.getSingleton();
+
+  /** the root nexus */
+  private DefaultPartitionNexus partitionNexus;
+
+  /** whether or not server is started for the first time */
+  private boolean firstStart;
+
+  /** whether or not this instance has been shutdown */
+  private boolean started;
+
+  /** the change log service */
+  private ChangeLog changeLog;
+
+  /** the journal service */
+  private Journal journal;
+
+  /**
+   * the interface used to perform various operations on this
+   * DirectoryService
+   */
+  private OperationManager operationManager = new DefaultOperationManager( this );
+
+  /** the distinguished name of the administrative user */
+  private Dn adminDn;
+
+  /** session used as admin for internal operations */
+  private CoreSession adminSession;
+
+  /** The referral manager */
+  private ReferralManager referralManager;
+
+  /** A flag to tell if the userPassword attribute's value must be hidden */
+  private boolean passwordHidden = false;
+
+  /** The service's CSN factory */
+  private CsnFactory csnFactory;
+
+  /** The directory instance replication ID */
+  private int replicaId;
+
+  /** remove me after implementation is completed */
+  private static final String PARTIAL_IMPL_WARNING =
+      "WARNING: the changelog is only partially operational and will revert\n" +
+          "state without consideration of who made the original change.  All reverting " +
+          "changes are made by the admin user.\n Furthermore the used controls are not at " +
+          "all taken into account";
+
+  /** The delay to wait between each sync on disk */
+  private long syncPeriodMillis;
+
+  /** The default delay to wait between sync on disk : 15 seconds */
+  private static final long DEFAULT_SYNC_PERIOD = 15000;
+
+  /** */
+  private Thread workerThread;
+
+  /** The default timeLimit : 100 entries */
+  public static final int MAX_SIZE_LIMIT_DEFAULT = 100;
+
+  /** The default timeLimit : 10 seconds */
+  public static final int MAX_TIME_LIMIT_DEFAULT = 10000;
+
+  /** The instance Id */
+  private String instanceId;
+
+  /** The server directory layout*/
+  private InstanceLayout instanceLayout;
+
+  /**
+   * A flag used to shutdown the VM when stopping the server. Useful
+   * when the server is standalone. If the server is embedded, we don't
+   * want to shutdown the VM
+   */
+  private boolean exitVmOnShutdown = true; // allow by default
+
+  /** A flag used to indicate that a shutdown hook has been installed */
+  private boolean shutdownHookEnabled = true; // allow by default
+
+  /** Manage anonymous access to entries other than the RootDSE */
+  private boolean allowAnonymousAccess = false; // forbid by default
+
+  /** Manage the basic access control checks */
+  private boolean accessControlEnabled; // off by default
+
+  /** Manage the operational attributes denormalization */
+  private boolean denormalizeOpAttrsEnabled; // off by default
+
+  /** The list of declared interceptors */
+  private List<Interceptor> interceptors;
+  private Map<String, Interceptor> interceptorNames;
+
+  /** A lock to protect the interceptors List */
+  private ReadWriteLock interceptorsLock = new ReentrantReadWriteLock();
+
+  /** The read and write locks */
+  private Lock readLock = interceptorsLock.readLock();
+  private Lock writeLock = interceptorsLock.writeLock();
+
+  /** A map associating a list of interceptor to each operation */
+  private Map<OperationEnum, List<String>> operationInterceptors;
+
+  /** The System partition */
+  private Partition systemPartition;
+
+  /** The set of all declared partitions */
+  private Set<Partition> partitions = new HashSet<>();
+
+  /** A list of LDIF entries to inject at startup */
+  private List<? extends LdifEntry> testEntries = new ArrayList<LdifEntry>(); // List<Attributes>
+
+  /** The event service */
+  private EventService eventService;
+
+  /** The maximum size for an incoming PDU */
+  private int maxPDUSize = Integer.MAX_VALUE;
+
+  /** the value of last successful add/update operation's CSN */
+  private String contextCsn;
+
+  /** lock file for directory service's working directory */
+  private RandomAccessFile lockFile = null;
+
+  private static final String LOCK_FILE_NAME = ".dirservice.lock";
+
+  /** the ehcache based cache service */
+  private CacheService cacheService;
+
+  /** The AccessControl AdministrativePoint cache */
+  private DnNode<AccessControlAdministrativePoint> accessControlAPCache;
+
+  /** The CollectiveAttribute AdministrativePoint cache */
+  private DnNode<CollectiveAttributeAdministrativePoint> collectiveAttributeAPCache;
+
+  /** The Subschema AdministrativePoint cache */
+  private DnNode<SubschemaAdministrativePoint> subschemaAPCache;
+
+  /** The TriggerExecution AdministrativePoint cache */
+  private DnNode<TriggerExecutionAdministrativePoint> triggerExecutionAPCache;
+
+  /** The Dn factory */
+  private DnFactory dnFactory;
+
+  /** The Subentry cache */
+  SubentryCache subentryCache = new SubentryCache();
+
+  /** The Subtree evaluator instance */
+  private SubtreeEvaluator evaluator;
+
+
+  // ------------------------------------------------------------------------
+  // Constructor
+  // ------------------------------------------------------------------------
+
+  /**
+   * Creates a new instance of the directory service.
+   */
+  public BaseDirectoryService() throws Exception
+  {
+    changeLog = new DefaultChangeLog();
+    journal = new DefaultJournal();
+    syncPeriodMillis = DEFAULT_SYNC_PERIOD;
+    csnFactory = new CsnFactory( replicaId );
+    evaluator = new SubtreeEvaluator( schemaManager );
+    setDefaultInterceptorConfigurations();
+  }
+
+
+  // ------------------------------------------------------------------------
+  // C O N F I G U R A T I O N   M E T H O D S
+  // ------------------------------------------------------------------------
+
+  public void setInstanceId( String instanceId )
+  {
+    this.instanceId = instanceId;
+  }
+
+
+  public String getInstanceId()
+  {
+    return instanceId;
+  }
+
+
+  /**
+   * Gets the {@link Partition}s used by this DirectoryService.
+   *
+   * @return the set of partitions used
+   */
+  public Set<? extends Partition> getPartitions()
+  {
+    Set<Partition> cloned = new HashSet<>();
+    cloned.addAll( partitions );
+    return cloned;
+  }
+
+
+  /**
+   * Sets {@link Partition}s used by this DirectoryService.
+   *
+   * @param partitions the partitions to used
+   */
+  public void setPartitions( Set<? extends Partition> partitions )
+  {
+    Set<Partition> cloned = new HashSet<>();
+    cloned.addAll( partitions );
+    Set<String> names = new HashSet<>();
+
+    for ( Partition partition : cloned )
+    {
+      String id = partition.getId();
+
+      if ( names.contains( id ) )
+      {
+        LOG.warn( "Encountered duplicate partition {} identifier.", id );
+      }
+
+      names.add( id );
+    }
+
+    this.partitions = cloned;
+  }
+
+
+  /**
+   * Returns <tt>true</tt> if access control checks are enabled.
+   *
+   * @return true if access control checks are enabled, false otherwise
+   */
+  public boolean isAccessControlEnabled()
+  {
+    return accessControlEnabled;
+  }
+
+
+  /**
+   * Sets whether to enable basic access control checks or not.
+   *
+   * @param accessControlEnabled true to enable access control checks, false otherwise
+   */
+  public void setAccessControlEnabled( boolean accessControlEnabled )
+  {
+    this.accessControlEnabled = accessControlEnabled;
+  }
+
+
+  /**
+   * Returns <tt>true</tt> if anonymous access is allowed on entries besides the RootDSE.
+   * If the access control subsystem is enabled then access to some entries may not be
+   * allowed even when full anonymous access is enabled.
+   *
+   * @return true if anonymous access is allowed on entries besides the RootDSE, false
+   * if anonymous access is allowed to all entries.
+   */
+  public boolean isAllowAnonymousAccess()
+  {
+    return allowAnonymousAccess;
+  }
+
+
+  /**
+   * Sets whether to allow anonymous access to entries other than the RootDSE.  If the
+   * access control subsystem is enabled then access to some entries may not be allowed
+   * even when full anonymous access is enabled.
+   *
+   * @param enableAnonymousAccess true to enable anonymous access, false to disable it
+   */
+  public void setAllowAnonymousAccess( boolean enableAnonymousAccess )
+  {
+    this.allowAnonymousAccess = enableAnonymousAccess;
+  }
+
+
+  /**
+   * Returns interceptors in the server.
+   *
+   * @return the interceptors in the server.
+   */
+  public List<Interceptor> getInterceptors()
+  {
+    List<Interceptor> cloned = new ArrayList<Interceptor>();
+
+    readLock.lock();
+
+    try
+    {
+      cloned.addAll( interceptors );
+
+      return cloned;
+    }
+    finally
+    {
+      readLock.unlock();
+    }
+  }
+
+
+  /**
+   * Returns interceptors in the server for a given operation.
+   *
+   * @return the interceptors in the server for the given operation.
+   */
+  public List<String> getInterceptors( OperationEnum operation )
+  {
+    List<String> cloned = new ArrayList<String>();
+
+    readLock.lock();
+
+    try
+    {
+      cloned.addAll( operationInterceptors.get( operation ) );
+
+      return cloned;
+    }
+    finally
+    {
+      readLock.unlock();
+    }
+
+  }
+
+
+  /**
+   * Compute the list of  to call for each operation
+   */
+  private void initOperationsList()
+  {
+    writeLock.lock();
+
+    try
+    {
+      operationInterceptors = new ConcurrentHashMap<OperationEnum, List<String>>();
+
+      for ( OperationEnum operation : OperationEnum.getOperations() )
+      {
+        List<String> operationList = new ArrayList<String>();
+
+        for ( Interceptor interceptor : interceptors )
+        {
+          gatherInterceptors( interceptor, interceptor.getClass(), operation, operationList );
+        }
+
+        operationInterceptors.put( operation, operationList );
+      }
+    }
+    finally
+    {
+      writeLock.unlock();
+    }
+  }
+
+
+  /**
+   * Recursively checks if the given interceptor can be added to the list of interceptors for a given
+   * operation and adds to the list of interceptors if it implements the respective operation
+   *
+   * @param interceptor the instance of the interceptor
+   * @param interceptorClz the class of the interceptor
+   * @param operation type of operation
+   * @param selectedInterceptorList the list of selected interceptors
+   */
+  private void gatherInterceptors( Interceptor interceptor, Class<?> interceptorClz, OperationEnum operation,
+                                   List<String> selectedInterceptorList )
+  {
+    // We stop recursing when we reach the Base class
+    if ( ( interceptorClz == null ) || ( interceptorClz == BaseInterceptor.class ) )
+    {
+      return;
+    }
+
+    // We don't call getMethods() because it would get back the default methods
+    // from the BaseInterceptor, something we don't want.
+    Method[] methods = interceptorClz.getDeclaredMethods();
+
+    for ( Method method : methods )
+    {
+      Class<?>[] param = method.getParameterTypes();
+      boolean hasCorrestSig = false;
+
+      // check for the correct signature
+      if ( ( param == null ) || ( param.length > 1 ) || ( param.length == 0 ) )
+      {
+        continue;
+      }
+
+      if ( OperationContext.class.isAssignableFrom( param[0] ) )
+      {
+        hasCorrestSig = true;
+      }
+      else
+      {
+        continue;
+      }
+
+      if ( hasCorrestSig && method.getName().equals( operation.getMethodName() ) )
+      {
+        if ( !selectedInterceptorList.contains( interceptor.getName() ) )
+        {
+          selectedInterceptorList.add( interceptor.getName() );
+        }
+
+        break;
+      }
+    }
+
+    // Recurse on extended classes, as we have used getDeclaredMethods() instead of getmethods()
+    gatherInterceptors( interceptor, interceptorClz.getSuperclass(), operation, selectedInterceptorList );
+  }
+
+
+  /**
+   * Add an interceptor to the list of interceptors to call for each operation
+   * @throws LdapException
+   */
+  private void addInterceptor( Interceptor interceptor, int position ) throws LdapException
+  {
+    // First, init the interceptor
+    interceptor.init( this );
+
+    writeLock.lock();
+
+    try
+    {
+      for ( OperationEnum operation : OperationEnum.getOperations() )
+      {
+        List<String> operationList = operationInterceptors.get( operation );
+
+        Method[] methods = interceptor.getClass().getDeclaredMethods();
+
+        for ( Method method : methods )
+        {
+          if ( method.getName().equals( operation.getMethodName() ) )
+          {
+            if ( position == -1 )
+            {
+              operationList.add( interceptor.getName() );
+            }
+            else
+            {
+              operationList.add( position, interceptor.getName() );
+            }
+
+            break;
+          }
+        }
+      }
+
+      interceptorNames.put( interceptor.getName(), interceptor );
+
+      if ( position == -1 )
+      {
+        interceptors.add( interceptor );
+      }
+      else
+      {
+        interceptors.add( position, interceptor );
+      }
+    }
+    finally
+    {
+      writeLock.unlock();
+    }
+  }
+
+
+  /**
+   * Remove an interceptor to the list of interceptors to call for each operation
+   */
+  private void removeOperationsList( String interceptorName )
+  {
+    Interceptor interceptor = interceptorNames.get( interceptorName );
+
+    writeLock.lock();
+
+    try
+    {
+      for ( OperationEnum operation : OperationEnum.getOperations() )
+      {
+        List<String> operationList = operationInterceptors.get( operation );
+
+        Method[] methods = interceptor.getClass().getDeclaredMethods();
+
+        for ( Method method : methods )
+        {
+          if ( method.getName().equals( operation.getMethodName() ) )
+          {
+            operationList.remove( interceptor.getName() );
+
+            break;
+          }
+        }
+      }
+
+      interceptorNames.remove( interceptorName );
+      interceptors.remove( interceptor );
+    }
+    finally
+    {
+      writeLock.unlock();
+    }
+  }
+
+
+  /**
+   * Sets the interceptors in the server.
+   *
+   * @param interceptors the interceptors to be used in the server.
+   */
+  public void setInterceptors( List<Interceptor> interceptors )
+  {
+    Map<String, Interceptor> interceptorNames = new HashMap<>();
+
+    // Check if we don't have duplicate names in the interceptors list
+    for ( Interceptor interceptor : interceptors )
+    {
+      if ( interceptorNames.containsKey( interceptor.getName() ) )
+      {
+        LOG.warn( "Encountered duplicate definitions for {} interceptor", interceptor.getName() );
+        continue;
+      }
+
+      interceptorNames.put( interceptor.getName(), interceptor );
+    }
+
+    this.interceptors = interceptors;
+    this.interceptorNames = interceptorNames;
+
+    // Now update the Map that connect each operation with the list of interceptors.
+    initOperationsList();
+  }
+
+
+  /**
+   * Initialize the interceptors
+   */
+  private void initInterceptors() throws LdapException
+  {
+    for ( Interceptor interceptor : interceptors )
+    {
+      interceptor.init( this );
+    }
+  }
+
+
+  /**
+   * Returns test directory entries({@link LdifEntry}) to be loaded while
+   * bootstrapping.
+   *
+   * @return test entries to load during bootstrapping
+   */
+  public List<LdifEntry> getTestEntries()
+  {
+    List<LdifEntry> cloned = new ArrayList<LdifEntry>();
+    cloned.addAll( testEntries );
+
+    return cloned;
+  }
+
+
+  /**
+   * Sets test directory entries({@link javax.naming.directory.Attributes}) to be loaded while
+   * bootstrapping.
+   *
+   * @param testEntries the test entries to load while bootstrapping
+   */
+  public void setTestEntries( List<? extends LdifEntry> testEntries )
+  {
+    //noinspection MismatchedQueryAndUpdateOfCollection
+    List<LdifEntry> cloned = new ArrayList<LdifEntry>();
+    cloned.addAll( testEntries );
+    this.testEntries = cloned;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public InstanceLayout getInstanceLayout()
+  {
+    return instanceLayout;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public void setInstanceLayout( InstanceLayout instanceLayout ) throws IOException
+  {
+    this.instanceLayout = instanceLayout;
+
+    // Create the directories if they are missing
+    if ( !instanceLayout.getInstanceDirectory().exists() )
+    {
+      if ( !instanceLayout.getInstanceDirectory().mkdirs() )
+      {
+        throw new IOException( I18n.err( I18n.ERR_112_COULD_NOT_CREATE_DIRECORY,
+            instanceLayout.getInstanceDirectory() ) );
+      }
+    }
+
+    if ( !instanceLayout.getLogDirectory().exists() )
+    {
+      if ( !instanceLayout.getLogDirectory().mkdirs() )
+      {
+        throw new IOException( I18n.err( I18n.ERR_112_COULD_NOT_CREATE_DIRECORY,
+            instanceLayout.getLogDirectory() ) );
+      }
+    }
+
+    if ( !instanceLayout.getRunDirectory().exists() )
+    {
+      if ( !instanceLayout.getRunDirectory().mkdirs() )
+      {
+        throw new IOException( I18n.err( I18n.ERR_112_COULD_NOT_CREATE_DIRECORY,
+            instanceLayout.getRunDirectory() ) );
+      }
+    }
+
+    if ( !instanceLayout.getPartitionsDirectory().exists() )
+    {
+      if ( !instanceLayout.getPartitionsDirectory().mkdirs() )
+      {
+        throw new IOException( I18n.err( I18n.ERR_112_COULD_NOT_CREATE_DIRECORY,
+            instanceLayout.getPartitionsDirectory() ) );
+      }
+    }
+
+    if ( !instanceLayout.getConfDirectory().exists() )
+    {
+      if ( !instanceLayout.getConfDirectory().mkdirs() )
+      {
+        throw new IOException( I18n.err( I18n.ERR_112_COULD_NOT_CREATE_DIRECORY,
+            instanceLayout.getConfDirectory() ) );
+      }
+    }
+  }
+
+
+  public void setShutdownHookEnabled( boolean shutdownHookEnabled )
+  {
+    this.shutdownHookEnabled = shutdownHookEnabled;
+  }
+
+
+  public boolean isShutdownHookEnabled()
+  {
+    return shutdownHookEnabled;
+  }
+
+
+  public void setExitVmOnShutdown( boolean exitVmOnShutdown )
+  {
+    this.exitVmOnShutdown = exitVmOnShutdown;
+  }
+
+
+  public boolean isExitVmOnShutdown()
+  {
+    return exitVmOnShutdown;
+  }
+
+
+  public void setSystemPartition( Partition systemPartition )
+  {
+    this.systemPartition = systemPartition;
+  }
+
+
+  public Partition getSystemPartition()
+  {
+    return systemPartition;
+  }
+
+
+  /**
+   * return true if the operational attributes must be normalized when returned
+   */
+  public boolean isDenormalizeOpAttrsEnabled()
+  {
+    return denormalizeOpAttrsEnabled;
+  }
+
+
+  /**
+   * Sets whether the operational attributes are denormalized when returned
+   * @param denormalizeOpAttrsEnabled The flag value
+   */
+  public void setDenormalizeOpAttrsEnabled( boolean denormalizeOpAttrsEnabled )
+  {
+    this.denormalizeOpAttrsEnabled = denormalizeOpAttrsEnabled;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public ChangeLog getChangeLog()
+  {
+    return changeLog;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public Journal getJournal()
+  {
+    return journal;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public void setChangeLog( ChangeLog changeLog )
+  {
+    this.changeLog = changeLog;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public void setJournal( Journal journal )
+  {
+    this.journal = journal;
+  }
+
+
+  public void addPartition( Partition partition ) throws Exception
+  {
+    partition.setSchemaManager( schemaManager );
+
+    try
+    {
+      // can be null when called before starting up
+      if ( partitionNexus != null )
+      {
+        partitionNexus.addContextPartition( partition );
+      }
+    }
+    catch ( LdapException le )
+    {
+      // We've got an exception, we cannot add the partition to the partitions
+      throw le;
+    }
+
+    // Now, add the partition to the set of managed partitions
+    partitions.add( partition );
+  }
+
+
+  public void removePartition( Partition partition ) throws Exception
+  {
+    // Do the backend cleanup first
+    try
+    {
+      // can be null when called before starting up
+      if ( partitionNexus != null )
+      {
+        partitionNexus.removeContextPartition( partition.getSuffixDn() );
+      }
+    }
+    catch ( LdapException le )
+    {
+      // Bad ! We can't go any further
+      throw le;
+    }
+
+    // And update the set of managed partitions
+    partitions.remove( partition );
+  }
+
+
+  // ------------------------------------------------------------------------
+  // BackendSubsystem Interface Method Implementations
+  // ------------------------------------------------------------------------
+  /**
+   * Define a default list of interceptors that has to be used if no other
+   * configuration is defined.
+   */
+  private void setDefaultInterceptorConfigurations()
+  {
+    // Set default interceptor chains
+    List<Interceptor> list = new ArrayList<Interceptor>();
+
+    list.add( new NormalizationInterceptor() );
+    list.add( new AuthenticationInterceptor() );
+    list.add( new ReferralInterceptor() );
+    list.add( new AciAuthorizationInterceptor() );
+    list.add( new DefaultAuthorizationInterceptor() );
+    list.add( new AdministrativePointInterceptor() );
+    list.add( new ExceptionInterceptor() );
+    list.add( new SchemaInterceptor() );
+    list.add( new OperationalAttributeInterceptor() );
+    list.add( new CollectiveAttributeInterceptor() );
+    list.add( new SubentryInterceptor() );
+    list.add( new EventInterceptor() );
+    list.add( new TriggerInterceptor() );
+    list.add( new ChangeLogInterceptor() );
+    list.add( new JournalInterceptor() );
+
+    setInterceptors( list );
+  }
+
+
+  public CoreSession getAdminSession()
+  {
+    return adminSession;
+  }
+
+
+  /**
+   * Get back an anonymous session
+   */
+  public CoreSession getSession()
+  {
+    return new DefaultCoreSession( new LdapPrincipal( schemaManager ), this );
+  }
+
+
+  /**
+   * Get back a session for a given principal
+   */
+  public CoreSession getSession( LdapPrincipal principal )
+  {
+    return new DefaultCoreSession( principal, this );
+  }
+
+
+  /**
+   * Get back a session for the give user and credentials bound with Simple Bind
+   */
+  public CoreSession getSession( Dn principalDn, byte[] credentials ) throws LdapException
+  {
+    synchronized ( this )
+    {
+      if ( !started )
+      {
+        throw new IllegalStateException( "Service has not started." );
+      }
+    }
+
+    BindOperationContext bindContext = new BindOperationContext( null );
+    bindContext.setCredentials( credentials );
+    bindContext.setDn( principalDn.apply( schemaManager ) );
+    bindContext.setInterceptors( getInterceptors( OperationEnum.BIND ) );
+
+    operationManager.bind( bindContext );
+
+    return bindContext.getSession();
+  }
+
+
+  /**
+   * Get back a session for a given user bound with SASL Bind
+   */
+  public CoreSession getSession( Dn principalDn, byte[] credentials, String saslMechanism, String saslAuthId )
+      throws Exception
+  {
+    synchronized ( this )
+    {
+      if ( !started )
+      {
+        throw new IllegalStateException( "Service has not started." );
+
+      }
+    }
+
+    BindOperationContext bindContext = new BindOperationContext( null );
+    bindContext.setCredentials( credentials );
+    bindContext.setDn( principalDn.apply( schemaManager ) );
+    bindContext.setSaslMechanism( saslMechanism );
+    bindContext.setInterceptors( getInterceptors( OperationEnum.BIND ) );
+
+    operationManager.bind( bindContext );
+
+    return bindContext.getSession();
+  }
+
+
+  public long revert() throws LdapException
+  {
+    if ( changeLog == null || !changeLog.isEnabled() )
+    {
+      throw new IllegalStateException( I18n.err( I18n.ERR_310 ) );
+    }
+
+    Tag latest = changeLog.getLatest();
+
+    if ( null != latest )
+    {
+      if ( latest.getRevision() < changeLog.getCurrentRevision() )
+      {
+        return revert( latest.getRevision() );
+      }
+      else
+      {
+        LOG.info( "Ignoring request to revert without changes since the latest tag." );
+        return changeLog.getCurrentRevision();
+      }
+    }
+
+    throw new IllegalStateException( I18n.err( I18n.ERR_311 ) );
+  }
+
+
+  /**
+   * We handle the ModDN/ModRDN operation for the revert here.
+   */
+  private void moddn( Dn oldDn, Dn newDn, boolean delOldRdn ) throws LdapException
+  {
+    if ( oldDn.size() == 0 )
+    {
+      throw new LdapNoPermissionException( I18n.err( I18n.ERR_312 ) );
+    }
+
+    // calculate parents
+    Dn oldBase = oldDn.getParent();
+    Dn newBase = newDn.getParent();
+
+    // Compute the Rdn for each of the Dn
+    Rdn newRdn = newDn.getRdn();
+    Rdn oldRdn = oldDn.getRdn();
+
+        /*
+         * We need to determine if this rename operation corresponds to a simple
+         * Rdn name change or a move operation.  If the two names are the same
+         * except for the Rdn then it is a simple modifyRdn operation.  If the
+         * names differ in size or have a different baseDN then the operation is
+         * a move operation.  Furthermore if the Rdn in the move operation
+         * changes it is both an Rdn change and a move operation.
+         */
+    if ( ( oldDn.size() == newDn.size() ) && oldBase.equals( newBase ) )
+    {
+      adminSession.rename( oldDn, newRdn, delOldRdn );
+    }
+    else
+    {
+      Dn target = newDn.getParent();
+
+      if ( newRdn.equals( oldRdn ) )
+      {
+        adminSession.move( oldDn, target );
+      }
+      else
+      {
+        adminSession.moveAndRename( oldDn, target, new Rdn( newRdn ), delOldRdn );
+      }
+    }
+  }
+
+
+  public long revert( long revision ) throws LdapException
+  {
+    if ( changeLog == null || !changeLog.isEnabled() )
+    {
+      throw new IllegalStateException( I18n.err( I18n.ERR_310 ) );
+    }
+
+    if ( revision < 0 )
+    {
+      throw new IllegalArgumentException( I18n.err( I18n.ERR_239 ) );
+    }
+
+    if ( revision >= changeLog.getChangeLogStore().getCurrentRevision() )
+    {
+      throw new IllegalArgumentException( I18n.err( I18n.ERR_314 ) );
+    }
+
+    Cursor<ChangeLogEvent> cursor = changeLog.getChangeLogStore().findAfter( revision );
+
+        /*
+         * BAD, BAD, BAD!!!
+         *
+         * No synchronization no nothing.  Just getting this to work for now
+         * so we can revert tests.  Any production grade use of this feature
+         * needs to synchronize on all changes while the revert is in progress.
+         *
+         * How about making this operation transactional?
+         *
+         * First of all just stop using JNDI and construct the operations to
+         * feed into the interceptor pipeline.
+         *
+         * TODO review this code.
+         */
+
+    try
+    {
+      LOG.warn( PARTIAL_IMPL_WARNING );
+      cursor.afterLast();
+
+      while ( cursor.previous() ) // apply ldifs in reverse order
+      {
+        ChangeLogEvent event = cursor.get();
+        List<LdifEntry> reverses = event.getReverseLdifs();
+
+        for ( LdifEntry reverse : reverses )
+        {
+          switch ( reverse.getChangeType().getChangeType() )
+          {
+            case ChangeType.ADD_ORDINAL:
+              adminSession.add(
+                  new DefaultEntry( schemaManager, reverse.getEntry() ), true );
+              break;
+
+            case ChangeType.DELETE_ORDINAL:
+              adminSession.delete( reverse.getDn(), true );
+              break;
+
+            case ChangeType.MODIFY_ORDINAL:
+              List<Modification> mods = reverse.getModifications();
+
+              adminSession.modify( reverse.getDn(), mods, true );
+              break;
+
+            case ChangeType.MODDN_ORDINAL:
+              // NO BREAK - both ModDN and ModRDN handling is the same
+
+            case ChangeType.MODRDN_ORDINAL:
+              Dn forwardDn = event.getForwardLdif().getDn();
+              Dn reverseDn = reverse.getDn();
+
+              moddn( reverseDn, forwardDn, reverse.isDeleteOldRdn() );
+
+              break;
+
+            default:
+              LOG.error( I18n.err( I18n.ERR_75 ) );
+              throw new NotImplementedException( I18n.err( I18n.ERR_76, reverse.getChangeType() ) );
+          }
+        }
+      }
+    }
+    catch ( Exception e )
+    {
+      throw new LdapOperationException( e.getMessage(), e );
+    }
+    finally
+    {
+      try
+      {
+        cursor.close();
+      }
+      catch ( Exception e )
+      {
+        throw new LdapOperationException( e.getMessage(), e );
+      }
+    }
+
+    return changeLog.getCurrentRevision();
+  }
+
+
+  public OperationManager getOperationManager()
+  {
+    return operationManager;
+  }
+
+
+  /**
+   * @throws Exception if the LDAP server cannot be started
+   */
+  public synchronized void startup() throws Exception
+  {
+    if ( started )
+    {
+      return;
+    }
+
+    lockWorkDir();
+
+    if ( shutdownHookEnabled )
+    {
+      Runtime.getRuntime().addShutdownHook( new Thread( new Runnable()
+      {
+        public void run()
+        {
+          try
+          {
+            shutdown();
+          }
+          catch ( Exception e )
+          {
+            LOG.warn( "Failed to shut down the directory service: "
+                + BaseDirectoryService.this.instanceId, e );
+          }
+        }
+      }, "ApacheDS Shutdown Hook (" + instanceId + ')' ) );
+
+      LOG.info( "ApacheDS shutdown hook has been registered with the runtime." );
+    }
+    else if ( LOG.isWarnEnabled() )
+    {
+      LOG.warn( "ApacheDS shutdown hook has NOT been registered with the runtime."
+          + "  This default setting for standalone operation has been overriden." );
+    }
+
+    initialize();
+    showSecurityWarnings();
+
+    // load the last stored valid CSN value
+    LookupOperationContext loc = new LookupOperationContext( getAdminSession(), systemPartition.getSuffixDn(),
+        SchemaConstants.ALL_ATTRIBUTES_ARRAY );
+
+    Entry entry = systemPartition.lookup( loc );
+
+    Attribute cntextCsnAt = entry.get( SchemaConstants.CONTEXT_CSN_AT );
+
+    if ( cntextCsnAt != null )
+    {
+      // this is a multivalued attribute but current syncrepl provider implementation stores only ONE value at ou=system
+      contextCsn = cntextCsnAt.getString();
+    }
+
+    started = true;
+
+    if ( !testEntries.isEmpty() )
+    {
+      createTestEntries();
+    }
+  }
+
+
+  public synchronized void sync() throws Exception
+  {
+    if ( !started )
+    {
+      return;
+    }
+
+    this.changeLog.sync();
+    this.partitionNexus.sync();
+  }
+
+
+  public synchronized void shutdown() throws Exception
+  {
+    LOG.debug( "+++ DirectoryService Shutdown required" );
+
+    if ( !started )
+    {
+      return;
+    }
+
+    // --------------------------------------------------------------------
+    // Shutdown the sync thread
+    // --------------------------------------------------------------------
+    LOG.debug( "--- Syncing the nexus " );
+    partitionNexus.sync();
+
+    // --------------------------------------------------------------------
+    // Shutdown the changelog
+    // --------------------------------------------------------------------
+    LOG.debug( "--- Syncing the changeLog " );
+    changeLog.sync();
+    changeLog.destroy();
+
+    // --------------------------------------------------------------------
+    // Shutdown the journal if enabled
+    // --------------------------------------------------------------------
+    if ( journal.isEnabled() )
+    {
+      LOG.debug( "--- Destroying the journal " );
+      journal.destroy();
+    }
+
+    // --------------------------------------------------------------------
+    // Shutdown the partition
+    // --------------------------------------------------------------------
+
+    LOG.debug( "--- Destroying the nexus" );
+    partitionNexus.destroy();
+
+    // Last flush...
+    LOG.debug( "--- Flushing everything before quitting" );
+    getOperationManager().lockWrite();
+    partitionNexus.sync();
+    getOperationManager().unlockWrite();
+
+    // --------------------------------------------------------------------
+    // And shutdown the server
+    // --------------------------------------------------------------------
+    LOG.debug( "--- Deleting the cache service" );
+    cacheService.destroy();
+
+    LOG.debug( "---Deleting the DnCache" );
+    dnFactory = null;
+
+    if ( lockFile != null )
+    {
+      try
+      {
+        lockFile.close();
+        // no need to delete the lock file
+      }
+      catch ( IOException e )
+      {
+        LOG.warn( "couldn't delete the lock file {}", LOCK_FILE_NAME );
+      }
+    }
+
+    LOG.debug( "+++ DirectoryService stopped" );
+    started = false;
+  }
+
+
+  /**
+   * @return The referral manager
+   */
+  public ReferralManager getReferralManager()
+  {
+    return referralManager;
+  }
+
+
+  /**
+   * Set the referralManager
+   * @param referralManager The initialized referralManager
+   */
+  public void setReferralManager( ReferralManager referralManager )
+  {
+    this.referralManager = referralManager;
+  }
+
+
+  /**
+   * @return the SchemaManager
+   */
+  public SchemaManager getSchemaManager()
+  {
+    return schemaManager;
+  }
+
+
+  /**
+   * Set the SchemaManager instance.
+   *
+   * @param schemaManager The server schemaManager
+   */
+  public void setSchemaManager( SchemaManager schemaManager )
+  {
+    this.schemaManager = schemaManager;
+  }
+
+
+  public LdapApiService getLdapCodecService()
+  {
+    return ldapCodecService;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public SchemaPartition getSchemaPartition()
+  {
+    return schemaPartition;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public void setSchemaPartition( SchemaPartition schemaPartition )
+  {
+    this.schemaPartition = schemaPartition;
+  }
+
+
+  public DefaultPartitionNexus getPartitionNexus()
+  {
+    return partitionNexus;
+  }
+
+
+  public boolean isFirstStart()
+  {
+    return firstStart;
+  }
+
+
+  public synchronized boolean isStarted()
+  {
+    return started;
+  }
+
+
+  public Entry newEntry( Dn dn )
+  {
+    return new DefaultEntry( schemaManager, dn );
+  }
+
+
+  /**
+   * Returns true if we had to create the bootstrap entries on the first
+   * start of the server.  Otherwise if all entries exist, meaning none
+   * had to be created, then we are not starting for the first time.
+   *
+   * @return true if the bootstrap entries had to be created, false otherwise
+   * @throws Exception if entries cannot be created
+   */
+  private boolean createBootstrapEntries() throws Exception
+  {
+    boolean firstStart = false;
+
+    // -------------------------------------------------------------------
+    // create admin entry
+    // -------------------------------------------------------------------
+
+        /*
+         * If the admin entry is there, then the database was already created
+         */
+    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, adminDn ) ) )
+    {
+      firstStart = true;
+
+      Entry serverEntry = new DefaultEntry( schemaManager, adminDn );
+
+      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT,
+          SchemaConstants.TOP_OC,
+          SchemaConstants.PERSON_OC,
+          SchemaConstants.ORGANIZATIONAL_PERSON_OC,
+          SchemaConstants.INET_ORG_PERSON_OC );
+
+      serverEntry.put( SchemaConstants.UID_AT, PartitionNexus.ADMIN_UID );
+      serverEntry.put( SchemaConstants.USER_PASSWORD_AT, PartitionNexus.ADMIN_PASSWORD_BYTES );
+      serverEntry.put( SchemaConstants.DISPLAY_NAME_AT, "Directory Superuser" );
+      serverEntry.put( SchemaConstants.CN_AT, "system administrator" );
+      serverEntry.put( SchemaConstants.SN_AT, "administrator" );
+      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
+      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
+      serverEntry.put( SchemaConstants.DISPLAY_NAME_AT, "Directory Superuser" );
+      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
+      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
+
+      TlsKeyGenerator.addKeyPair( serverEntry );
+      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
+    }
+
+    // -------------------------------------------------------------------
+    // create system users area
+    // -------------------------------------------------------------------
+
+    Dn userDn = getDnFactory().create( ServerDNConstants.USERS_SYSTEM_DN );
+
+    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, userDn ) ) )
+    {
+      firstStart = true;
+
+      Entry serverEntry = new DefaultEntry( schemaManager, userDn );
+
+      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT,
+          SchemaConstants.TOP_OC,
+          SchemaConstants.ORGANIZATIONAL_UNIT_OC );
+
+      serverEntry.put( SchemaConstants.OU_AT, "users" );
+      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
+      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
+      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
+      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
+
+      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
+    }
+
+    // -------------------------------------------------------------------
+    // create system groups area
+    // -------------------------------------------------------------------
+
+    Dn groupDn = getDnFactory().create( ServerDNConstants.GROUPS_SYSTEM_DN );
+
+    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, groupDn ) ) )
+    {
+      firstStart = true;
+
+      Entry serverEntry = new DefaultEntry( schemaManager, groupDn );
+
+      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT,
+          SchemaConstants.TOP_OC,
+          SchemaConstants.ORGANIZATIONAL_UNIT_OC );
+
+      serverEntry.put( SchemaConstants.OU_AT, "groups" );
+      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
+      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
+      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
+      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
+
+      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
+    }
+
+    // -------------------------------------------------------------------
+    // create administrator group
+    // -------------------------------------------------------------------
+
+    Dn name = getDnFactory().create( ServerDNConstants.ADMINISTRATORS_GROUP_DN );
+
+    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, name ) ) )
+    {
+      firstStart = true;
+
+      Entry serverEntry = new DefaultEntry( schemaManager, name );
+
+      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT,
+          SchemaConstants.TOP_OC,
+          SchemaConstants.GROUP_OF_UNIQUE_NAMES_OC );
+
+      serverEntry.put( SchemaConstants.CN_AT, "Administrators" );
+      serverEntry.put( SchemaConstants.UNIQUE_MEMBER_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
+      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
+      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
+      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
+      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
+
+      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
+    }
+
+    // -------------------------------------------------------------------
+    // create system configuration area
+    // -------------------------------------------------------------------
+
+    Dn configurationDn = getDnFactory().create( "ou=configuration,ou=system" );
+
+    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, configurationDn ) ) )
+    {
+      firstStart = true;
+
+      Entry serverEntry = new DefaultEntry( schemaManager, configurationDn );
+      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT, SchemaConstants.TOP_OC,
+          SchemaConstants.ORGANIZATIONAL_UNIT_OC );
+
+      serverEntry.put( SchemaConstants.OU_AT, "configuration" );
+      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
+      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
+      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
+      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
+
+      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
+    }
+
+    // -------------------------------------------------------------------
+    // create system configuration area for partition information
+    // -------------------------------------------------------------------
+
+    Dn partitionsDn = getDnFactory().create( "ou=partitions,ou=configuration,ou=system" );
+
+    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, partitionsDn ) ) )
+    {
+      firstStart = true;
+
+      Entry serverEntry = new DefaultEntry( schemaManager, partitionsDn );
+      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT, SchemaConstants.TOP_OC,
+          SchemaConstants.ORGANIZATIONAL_UNIT_OC );
+      serverEntry.put( SchemaConstants.OU_AT, "partitions" );
+      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
+      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
+      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
+      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
+
+      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
+    }
+
+    // -------------------------------------------------------------------
+    // create system configuration area for services
+    // -------------------------------------------------------------------
+
+    Dn servicesDn = getDnFactory().create( "ou=services,ou=configuration,ou=system" );
+
+    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, servicesDn ) ) )
+    {
+      firstStart = true;
+
+      Entry serverEntry = new DefaultEntry( schemaManager, servicesDn );
+      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT, SchemaConstants.TOP_OC,
+          SchemaConstants.ORGANIZATIONAL_UNIT_OC );
+
+      serverEntry.put( SchemaConstants.OU_AT, "services" );
+      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
+      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
+      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
+      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
+
+      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
+    }
+
+    // -------------------------------------------------------------------
+    // create system configuration area for interceptors
+    // -------------------------------------------------------------------
+
+    Dn interceptorsDn = getDnFactory().create( "ou=interceptors,ou=configuration,ou=system" );
+
+    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, interceptorsDn ) ) )
+    {
+      firstStart = true;
+
+      Entry serverEntry = new DefaultEntry( schemaManager, interceptorsDn );
+      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT, SchemaConstants.TOP_OC,
+          SchemaConstants.ORGANIZATIONAL_UNIT_OC );
+
+      serverEntry.put( SchemaConstants.OU_AT, "interceptors" );
+      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
+      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
+      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
+      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
+
+      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
+    }
+
+    // -------------------------------------------------------------------
+    // create system preferences area
+    // -------------------------------------------------------------------
+
+    Dn sysPrefRootDn = getDnFactory().create( ServerDNConstants.SYSPREFROOT_SYSTEM_DN );
+
+    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, sysPrefRootDn ) ) )
+    {
+      firstStart = true;
+
+      Entry serverEntry = new DefaultEntry( schemaManager, sysPrefRootDn );
+      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT,
+          SchemaConstants.TOP_OC,
+          SchemaConstants.ORGANIZATIONAL_UNIT_OC,
+          SchemaConstants.EXTENSIBLE_OBJECT_OC );
+
+      serverEntry.put( "prefNodeName", "sysPrefRoot" );
+      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
+      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
+      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
+      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
+
+      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
+    }
+
+    return firstStart;
+  }
+
+
+  /**
+   * Displays security warning messages if any possible secutiry issue is found.
+   * @throws Exception if there are failures parsing and accessing internal structures
+   */
+  protected void showSecurityWarnings() throws Exception
+  {
+    // Warn if the default password is not changed.
+    boolean needToChangeAdminPassword = false;
+
+    Dn adminDn = getDnFactory().create( ServerDNConstants.ADMIN_SYSTEM_DN );
+
+    Entry adminEntry = partitionNexus.lookup( new LookupOperationContext( adminSession, adminDn ) );
+    Value<?> userPassword = adminEntry.get( SchemaConstants.USER_PASSWORD_AT ).get();
+    needToChangeAdminPassword = Arrays.equals( PartitionNexus.ADMIN_PASSWORD_BYTES, userPassword.getBytes() );
+
+    if ( needToChangeAdminPassword )
+    {
+      LOG.warn( "You didn't change the admin password of directory service " + "instance '" + instanceId + "'.  "
+          + "Please update the admin password as soon as possible " + "to prevent a possible security breach." );
+    }
+  }
+
+
+  /**
+   * Adds test entries into the core.
+   *
+   * @todo this may no longer be needed when JNDI is not used for bootstrapping
+   *
+   * @throws Exception if the creation of test entries fails.
+   */
+  private void createTestEntries() throws Exception
+  {
+    for ( LdifEntry testEntry : testEntries )
+    {
+      try
+      {
+        LdifEntry ldifEntry = testEntry.clone();
+        Entry entry = ldifEntry.getEntry();
+        String dn = ldifEntry.getDn().getName();
+
+        try
+        {
+          getAdminSession().add( new DefaultEntry( schemaManager, entry ) );
+        }
+        catch ( Exception e )
+        {
+          LOG.warn( dn + " test entry already exists.", e );
+        }
+      }
+      catch ( CloneNotSupportedException cnse )
+      {
+        LOG.warn( "Cannot clone the entry ", cnse );
+      }
+    }
+  }
+
+
+  private void initializeSystemPartition() throws Exception
+  {
+    Partition system = getSystemPartition();
+
+    // Add root context entry for system partition
+    Dn systemSuffixDn = getDnFactory().create( ServerDNConstants.SYSTEM_DN );
+    CoreSession adminSession = getAdminSession();
+
+    if ( !system.hasEntry( new HasEntryOperationContext( adminSession, systemSuffixDn ) ) )
+    {
+      Entry systemEntry = new DefaultEntry( schemaManager, systemSuffixDn );
+
+      // Add the ObjectClasses
+      systemEntry.put( SchemaConstants.OBJECT_CLASS_AT, SchemaConstants.TOP_OC,
+          SchemaConstants.ORGANIZATIONAL_UNIT_OC, SchemaConstants.EXTENSIBLE_OBJECT_OC );
+
+      // Add some operational attributes
+      systemEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN );
+      systemEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
+      systemEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
+      systemEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
+      systemEntry.put( DnUtils.getRdnAttributeType( ServerDNConstants.SYSTEM_DN ), DnUtils
+          .getRdnValue( ServerDNConstants.SYSTEM_DN ) );
+
+      AddOperationContext addOperationContext = new AddOperationContext( adminSession, systemEntry );
+      system.add( addOperationContext );
+    }
+  }
+
+
+  /**
+   * Kicks off the initialization of the entire system.
+   *
+   * @throws Exception if there are problems along the way
+   */
+  private void initialize() throws Exception
+  {
+    if ( LOG.isDebugEnabled() )
+    {
+      LOG.debug( "---> Initializing the DefaultDirectoryService " );
+    }
+
+    csnFactory.setReplicaId( replicaId );
+
+    // If no interceptor list is defined, setup a default list
+    if ( interceptors == null )
+    {
+      setDefaultInterceptorConfigurations();
+    }
+
+    if ( cacheService == null )
+    {
+      // Initialize a default cache service
+      cacheService = new CacheService();
+    }
+
+    cacheService.initialize( instanceLayout );
+
+    // Initialize the AP caches
+    accessControlAPCache = new DnNode<AccessControlAdministrativePoint>();
+    collectiveAttributeAPCache = new DnNode<CollectiveAttributeAdministrativePoint>();
+    subschemaAPCache = new DnNode<SubschemaAdministrativePoint>();
+    triggerExecutionAPCache = new DnNode<TriggerExecutionAdministrativePoint>();
+
+    if ( dnFactory == null )
+    {
+      dnFactory = new DefaultDnFactory( schemaManager, cacheService.getCache( "dnCache" ) );
+    }
+
+    // triggers partition to load schema fully from schema partition
+    schemaPartition.setCacheService( cacheService );
+    schemaPartition.initialize();
+    partitions.add( schemaPartition );
+    systemPartition.setCacheService( cacheService );
+    systemPartition.getSuffixDn().apply( schemaManager );
+
+    adminDn = getDnFactory().create( ServerDNConstants.ADMIN_SYSTEM_DN );
+    adminSession = new DefaultCoreSession( new LdapPrincipal( schemaManager, adminDn, AuthenticationLevel.STRONG ),
+        this );
+
+    // @TODO - NOTE: Need to find a way to instantiate without dependency on DPN
+    partitionNexus = new DefaultPartitionNexus( new DefaultEntry( schemaManager, Dn.ROOT_DSE ) );
+    partitionNexus.setDirectoryService( this );
+    partitionNexus.initialize();
+
+    initializeSystemPartition();
+
+    // --------------------------------------------------------------------
+    // Create all the bootstrap entries before initializing chain
+    // --------------------------------------------------------------------
+
+    firstStart = createBootstrapEntries();
+
+    // Initialize the interceptors
+    initInterceptors();
+
+    // --------------------------------------------------------------------
+    // Initialize the changeLog if it's enabled
+    // --------------------------------------------------------------------
+
+    if ( changeLog.isEnabled() )
+    {
+      changeLog.init( this );
+
+      if ( changeLog.isExposed() && changeLog.isTagSearchSupported() )
+      {
+        String clSuffix = ( ( TaggableSearchableChangeLogStore ) changeLog.getChangeLogStore() ).getPartition()
+            .getSuffixDn().getName();
+        partitionNexus.getRootDse( null ).add( SchemaConstants.CHANGELOG_CONTEXT_AT, clSuffix );
+      }
+    }
+
+    // --------------------------------------------------------------------
+    // Initialize the journal if it's enabled
+    // --------------------------------------------------------------------
+    if ( journal.isEnabled() )
+    {
+      journal.init( this );
+    }
+
+    if ( LOG.isDebugEnabled() )
+    {
+      LOG.debug( "<--- DefaultDirectoryService initialized" );
+    }
+  }
+
+
+  /**
+   * Read an entry (without Dn)
+   *
+   * @param text The ldif format file
+   * @return An entry.
+   */
+  // This will suppress PMD.EmptyCatchBlock warnings in this method
+  @SuppressWarnings("PMD.EmptyCatchBlock")
+  private Entry readEntry( String text )
+  {
+    StringReader strIn = new StringReader( text );
+    BufferedReader in = new BufferedReader( strIn );
+
+    String line = null;
+    Entry entry = new DefaultEntry();
+
+    try
+    {
+      while ( ( line = in.readLine() ) != null )
+      {
+        if ( line.length() == 0 )
+        {
+          continue;
+        }
+
+        String addedLine = line.trim();
+
+        if ( Strings.isEmpty( addedLine ) )
+        {
+          continue;
+        }
+
+        Attribute attribute = LdifReader.parseAttributeValue( addedLine );
+        Attribute oldAttribute = entry.get( attribute.getId() );
+
+        if ( oldAttribute != null )
+        {
+          try
+          {
+            oldAttribute.add( attribute.get() );
+            entry.put( oldAttribute );
+          }
+          catch ( LdapException ne )
+          {
+            // Do nothing
+          }
+        }
+        else
+        {
+          try
+          {
+            entry.put( attribute );
+          }
+          catch ( LdapException ne )
+          {
+            // TODO do nothing ...
+          }
+        }
+      }
+    }
+    catch ( IOException ioe )
+    {
+      // Do nothing : we can't reach this point !
+    }
+
+    return entry;
+  }
+
+
+  /**
+   * Create a new Entry
+   *
+   * @param ldif The String representing the attributes, as a LDIF file
+   * @param dn The Dn for this new entry
+   */
+  public Entry newEntry( String ldif, String dn )
+  {
+    try
+    {
+      Entry entry = readEntry( ldif );
+      Dn newDn = getDnFactory().create( dn );
+
+      entry.setDn( newDn );
+
+      // TODO Let's get rid of this Attributes crap
+      Entry serverEntry = new DefaultEntry( schemaManager, entry );
+      return serverEntry;
+    }
+    catch ( Exception e )
+    {
+      LOG.error( I18n.err( I18n.ERR_78, ldif, dn ) );
+      // do nothing
+      return null;
+    }
+  }
+
+
+  public EventService getEventService()
+  {
+    return eventService;
+  }
+
+
+  public void setEventService( EventService eventService )
+  {
+    this.eventService = eventService;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public boolean isPasswordHidden()
+  {
+    return passwordHidden;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public void setPasswordHidden( boolean passwordHidden )
+  {
+    this.passwordHidden = passwordHidden;
+  }
+
+
+  /**
+   * @return The maximum allowed size for an incoming PDU
+   */
+  public int getMaxPDUSize()
+  {
+    return maxPDUSize;
+  }
+
+
+  /**
+   * Set the maximum allowed size for an incoming PDU
+   * @param maxPDUSize A positive number of bytes for the PDU. A negative or
+   * null value will be transformed to {@link Integer#MAX_VALUE}
+   */
+  public void setMaxPDUSize( int maxPDUSize )
+  {
+    if ( maxPDUSize <= 0 )
+    {
+      maxPDUSize = Integer.MAX_VALUE;
+    }
+
+    this.maxPDUSize = maxPDUSize;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public Interceptor getInterceptor( String interceptorName )
+  {
+    readLock.lock();
+
+    try
+    {
+      return interceptorNames.get( interceptorName );
+    }
+    finally
+    {
+      readLock.unlock();
+    }
+  }
+
+
+  /**
+   * {@inheritDoc}
+   * @throws LdapException
+   */
+  public void addFirst( Interceptor interceptor ) throws LdapException
+  {
+    addInterceptor( interceptor, 0 );
+  }
+
+
+  /**
+   * {@inheritDoc}
+   * @throws LdapException
+   */
+  public void addLast( Interceptor interceptor ) throws LdapException
+  {
+    addInterceptor( interceptor, -1 );
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public void addAfter( String interceptorName, Interceptor interceptor )
+  {
+    writeLock.lock();
+
+    try
+    {
+      int position = 0;
+
+      // Find the position
+      for ( Interceptor inter : interceptors )
+      {
+        if ( interceptorName.equals( inter.getName() ) )
+        {
+          break;
+        }
+
+        position++;
+      }
+
+      if ( position == interceptors.size() )
+      {
+        interceptors.add( interceptor );
+      }
+      else
+      {
+        interceptors.add( position, interceptor );
+      }
+    }
+    finally
+    {
+      writeLock.unlock();
+    }
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public void remove( String interceptorName )
+  {
+    removeOperationsList( interceptorName );
+  }
+
+
+  /**
+   * Get a new CSN
+   * @return The CSN generated for this directory service
+   */
+  public Csn getCSN()
+  {
+    return csnFactory.newInstance();
+  }
+
+
+  /**
+   * @return the replicaId
+   */
+  public int getReplicaId()
+  {
+    return replicaId;
+  }
+
+
+  /**
+   * @param replicaId the replicaId to set
+   */
+  public void setReplicaId( int replicaId )
+  {
+    if ( ( replicaId < 0 ) || ( replicaId > 999 ) )
+    {
+      LOG.error( I18n.err( I18n.ERR_79 ) );
+      this.replicaId = 0;
+    }
+    else
+    {
+      this.replicaId = replicaId;
+    }
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public long getSyncPeriodMillis()
+  {
+    return syncPeriodMillis;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public void setSyncPeriodMillis( long syncPeriodMillis )
+  {
+    this.syncPeriodMillis = syncPeriodMillis;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public String getContextCsn()
+  {
+    return contextCsn;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public void setContextCsn( String lastKnownCsn )
+  {
+    this.contextCsn = lastKnownCsn;
+  }
+
+
+  /**
+   * checks if the working directory is already in use by some other directory service, if yes
+   * then throws a runtime exception else will obtain the lock on the working directory
+   */
+  private void lockWorkDir()
+  {
+    FileLock fileLock = null;
+
+    try
+    {
+      lockFile = new RandomAccessFile( new File( instanceLayout.getInstanceDirectory(), LOCK_FILE_NAME ), "rw" );
+      try
+      {
+        fileLock = lockFile.getChannel().tryLock( 0, 1, false );
+      }
+      catch ( IOException e )
+      {
+        // shoudn't happen, but log
+        LOG.error( "failed to lock the work directory", e );
+      }
+      catch ( OverlappingFileLockException e ) // thrown if we can't get a lock
+      {
+        fileLock = null;
+      }
+    }
+    catch ( FileNotFoundException e )
+    {
+      // shouldn't happen, but log anyway
+      LOG.error( "failed to lock the work directory", e );
+    }
+
+    if ( ( fileLock == null ) || ( !fileLock.isValid() ) )
+    {
+      String message = "the working directory " + instanceLayout.getRunDirectory()
+          + " has been locked by another directory service.";
+      LOG.error( message );
+      throw new RuntimeException( message );
+    }
+
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public CacheService getCacheService()
+  {
+    return cacheService;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public DnNode<AccessControlAdministrativePoint> getAccessControlAPCache()
+  {
+    return accessControlAPCache;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public DnNode<CollectiveAttributeAdministrativePoint> getCollectiveAttributeAPCache()
+  {
+    return collectiveAttributeAPCache;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public DnNode<SubschemaAdministrativePoint> getSubschemaAPCache()
+  {
+    return subschemaAPCache;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public DnNode<TriggerExecutionAdministrativePoint> getTriggerExecutionAPCache()
+  {
+    return triggerExecutionAPCache;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public boolean isPwdPolicyEnabled()
+  {
+    AuthenticationInterceptor authenticationInterceptor = (AuthenticationInterceptor) getInterceptor( InterceptorEnum.AUTHENTICATION_INTERCEPTOR
+        .getName() );
+
+    if ( authenticationInterceptor == null )
+    {
+      return false;
+    }
+
+    PpolicyConfigContainer pwdPolicyContainer = authenticationInterceptor.getPwdPolicyContainer();
+
+    return ( ( pwdPolicyContainer != null )
+        && ( ( pwdPolicyContainer.getDefaultPolicy() != null )
+        || ( pwdPolicyContainer.hasCustomConfigs() ) ) );
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public DnFactory getDnFactory()
+  {
+    return dnFactory;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public void setDnFactory( DnFactory dnFactory )
+  {
+    this.dnFactory = dnFactory;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public SubentryCache getSubentryCache()
+  {
+    return subentryCache;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public SubtreeEvaluator getEvaluator()
+  {
+    return evaluator;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public void setCacheService( CacheService cacheService )
+  {
+    this.cacheService = cacheService;
+  }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/BaseDirectoryServiceFactory.java
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/BaseDirectoryServiceFactory.java b/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/BaseDirectoryServiceFactory.java
new file mode 100644
index 0000000..aed78bf
--- /dev/null
+++ b/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/BaseDirectoryServiceFactory.java
@@ -0,0 +1,290 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT 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.knox.gateway.security.ldap;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.directory.api.ldap.model.constants.SchemaConstants;
+import org.apache.directory.api.ldap.model.schema.LdapComparator;
+import org.apache.directory.api.ldap.model.schema.SchemaManager;
+import org.apache.directory.api.ldap.model.schema.comparators.NormalizingComparator;
+import org.apache.directory.api.ldap.model.schema.registries.ComparatorRegistry;
+import org.apache.directory.api.ldap.model.schema.registries.SchemaLoader;
+import org.apache.directory.api.ldap.schemaextractor.SchemaLdifExtractor;
+import org.apache.directory.api.ldap.schemaextractor.impl.DefaultSchemaLdifExtractor;
+import org.apache.directory.api.ldap.schemaloader.LdifSchemaLoader;
+import org.apache.directory.api.ldap.schemamanager.impl.DefaultSchemaManager;
+import org.apache.directory.api.util.exception.Exceptions;
+import org.apache.directory.server.constants.ServerDNConstants;
+import org.apache.directory.server.core.DefaultDirectoryService;
+import org.apache.directory.server.core.api.CacheService;
+import org.apache.directory.server.core.api.DirectoryService;
+import org.apache.directory.server.core.api.InstanceLayout;
+import org.apache.directory.server.core.api.partition.Partition;
+import org.apache.directory.server.core.api.schema.SchemaPartition;
+import org.apache.directory.server.core.factory.DefaultDirectoryServiceFactory;
+import org.apache.directory.server.core.factory.DirectoryServiceFactory;
+import org.apache.directory.server.core.factory.JdbmPartitionFactory;
+import org.apache.directory.server.core.factory.PartitionFactory;
+import org.apache.directory.server.core.partition.ldif.LdifPartition;
+import org.apache.directory.server.i18n.I18n;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+
+
+/**
+ * A Default factory for DirectoryService.
+ * This is a copy of org.apache.directory.server.core.factory.DefaultDirectoryServiceFactory
+ * created to control how the DirectoryService is created.  This can be removed
+ * when http://svn.apache.org/r1546144 in ApacheDS 2.0.0-M16 is available.
+ *
+ * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
+ */
+public class BaseDirectoryServiceFactory implements DirectoryServiceFactory
+{
+  /** A logger for this class */
+  private static final Logger LOG = LoggerFactory.getLogger( DefaultDirectoryServiceFactory.class );
+
+  /** The directory service. */
+  private DirectoryService directoryService;
+
+  /** The partition factory. */
+  private PartitionFactory partitionFactory;
+
+
+  public BaseDirectoryServiceFactory()
+  {
+    directoryService = createDirectoryService();
+    partitionFactory = createPartitionFactory();
+  }
+
+  protected DirectoryService createDirectoryService() {
+    DirectoryService result;
+    try
+    {
+      // Creating the instance here so that
+      // we we can set some properties like accesscontrol, anon access
+      // before starting up the service
+      result = new DefaultDirectoryService();
+
+      // No need to register a shutdown hook during tests because this
+      // starts a lot of threads and slows down test execution
+      result.setShutdownHookEnabled( false );
+    }
+    catch ( Exception e )
+    {
+      throw new RuntimeException( e );
+    }
+    return result;
+  }
+
+  protected PartitionFactory createPartitionFactory() {
+    PartitionFactory result;
+    try
+    {
+      String typeName = System.getProperty( "apacheds.partition.factory" );
+      if ( typeName != null )
+      {
+        Class<? extends PartitionFactory> type = ( Class<? extends PartitionFactory> ) Class.forName( typeName );
+        result = type.newInstance();
+      }
+      else
+      {
+        result = new JdbmPartitionFactory();
+      }
+    }
+    catch ( Exception e )
+    {
+      LOG.error( "Error instantiating custom partition factory", e );
+      throw new RuntimeException( e );
+    }
+    return result;
+  }
+
+  /**
+   * {@inheritDoc}
+   */
+  public void init( String name ) throws Exception
+  {
+    if ( ( directoryService != null ) && directoryService.isStarted() )
+    {
+      return;
+    }
+
+    build( name );
+  }
+
+
+  /**
+   * Build the working directory
+   */
+  private void buildInstanceDirectory( String name ) throws IOException
+  {
+    String instanceDirectory = System.getProperty( "workingDirectory" );
+
+    if ( instanceDirectory == null )
+    {
+      instanceDirectory = System.getProperty( "java.io.tmpdir" ) + "/server-work-" + name;
+    }
+
+    InstanceLayout instanceLayout = new InstanceLayout( instanceDirectory );
+
+    if ( instanceLayout.getInstanceDirectory().exists() )
+    {
+      try
+      {
+        FileUtils.deleteDirectory( instanceLayout.getInstanceDirectory() );
+      }
+      catch ( IOException e )
+      {
+        LOG.warn( "couldn't delete the instance directory before initializing the DirectoryService", e );
+      }
+    }
+
+    directoryService.setInstanceLayout( instanceLayout );
+  }
+
+
+  /**
+   * Inits the schema and schema partition.
+   */
+  private void initSchema() throws Exception
+  {
+    File workingDirectory = directoryService.getInstanceLayout().getPartitionsDirectory();
+
+    // Extract the schema on disk (a brand new one) and load the registries
+    File schemaRepository = new File( workingDirectory, "schema" );
+    SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor( workingDirectory );
+
+    try
+    {
+      extractor.extractOrCopy();
+    }
+    catch ( IOException ioe )
+    {
+      // The schema has already been extracted, bypass
+    }
+
+    SchemaLoader loader = new LdifSchemaLoader( schemaRepository );
+    SchemaManager schemaManager = new DefaultSchemaManager( loader );
+
+    // We have to load the schema now, otherwise we won't be able
+    // to initialize the Partitions, as we won't be able to parse
+    // and normalize their suffix Dn
+    schemaManager.loadAllEnabled();
+
+    // Tell all the normalizer comparators that they should not normalize anything
+    ComparatorRegistry comparatorRegistry = schemaManager.getComparatorRegistry();
+
+    for ( LdapComparator<?> comparator : comparatorRegistry )
+    {
+      if ( comparator instanceof NormalizingComparator )
+      {
+        ( ( NormalizingComparator ) comparator ).setOnServer();
+      }
+    }
+
+    directoryService.setSchemaManager( schemaManager );
+
+    // Init the LdifPartition
+    LdifPartition ldifPartition = new LdifPartition( schemaManager, directoryService.getDnFactory() );
+    ldifPartition.setPartitionPath( new File( workingDirectory, "schema" ).toURI() );
+    SchemaPartition schemaPartition = new SchemaPartition( schemaManager );
+    schemaPartition.setWrappedPartition( ldifPartition );
+    directoryService.setSchemaPartition( schemaPartition );
+
+    List<Throwable> errors = schemaManager.getErrors();
+
+    if ( errors.size() != 0 )
+    {
+      throw new Exception( I18n.err( I18n.ERR_317, Exceptions.printErrors( errors ) ) );
+    }
+  }
+
+
+  /**
+   * Inits the system partition.
+   *
+   * @throws Exception the exception
+   */
+  private void initSystemPartition() throws Exception
+  {
+    // change the working directory to something that is unique
+    // on the system and somewhere either under target directory
+    // or somewhere in a temp area of the machine.
+
+    // Inject the System Partition
+    Partition systemPartition = partitionFactory.createPartition(
+        directoryService.getSchemaManager(),
+        directoryService.getDnFactory(),
+        "system",
+        ServerDNConstants.SYSTEM_DN,
+        500,
+        new File( directoryService.getInstanceLayout().getPartitionsDirectory(), "system" ) );
+    systemPartition.setSchemaManager( directoryService.getSchemaManager() );
+
+    partitionFactory.addIndex( systemPartition, SchemaConstants.OBJECT_CLASS_AT, 100 );
+
+    directoryService.setSystemPartition( systemPartition );
+  }
+
+
+  /**
+   * Builds the directory server instance.
+   *
+   * @param name the instance name
+   */
+  private void build( String name ) throws Exception
+  {
+    directoryService.setInstanceId( name );
+    buildInstanceDirectory( name );
+
+    CacheService cacheService = new CacheService();
+    cacheService.initialize( directoryService.getInstanceLayout() );
+
+    directoryService.setCacheService( cacheService );
+
+    // Init the service now
+    initSchema();
+    initSystemPartition();
+
+    directoryService.startup();
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public DirectoryService getDirectoryService() throws Exception
+  {
+    return directoryService;
+  }
+
+
+  /**
+   * {@inheritDoc}
+   */
+  public PartitionFactory getPartitionFactory() throws Exception
+  {
+    return partitionFactory;
+  }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/SimpleDirectoryService.java
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/SimpleDirectoryService.java b/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/SimpleDirectoryService.java
new file mode 100644
index 0000000..69cdb3c
--- /dev/null
+++ b/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/SimpleDirectoryService.java
@@ -0,0 +1,29 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.security.ldap;
+
+public class SimpleDirectoryService extends BaseDirectoryService {
+
+  public SimpleDirectoryService() throws Exception {
+  }
+
+  protected void showSecurityWarnings() throws Exception {
+    // NoOp - This prevents confusing warnings from being output.
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/SimpleDirectoryServiceFactory.java
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/SimpleDirectoryServiceFactory.java b/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/SimpleDirectoryServiceFactory.java
new file mode 100644
index 0000000..a25355b
--- /dev/null
+++ b/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/SimpleDirectoryServiceFactory.java
@@ -0,0 +1,34 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.security.ldap;
+
+import org.apache.directory.server.core.api.DirectoryService;
+
+public class SimpleDirectoryServiceFactory extends BaseDirectoryServiceFactory {
+
+  protected DirectoryService createDirectoryService() {
+    DirectoryService result;
+    try {
+      result = new SimpleDirectoryService();
+    } catch( Exception e ) {
+      throw new RuntimeException( e );
+    }
+    return result;
+  }
+
+}


[46/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTestFormattingSubject.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTestFormattingSubject.java b/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTestFormattingSubject.java
new file mode 100644
index 0000000..2f49cc6
--- /dev/null
+++ b/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTestFormattingSubject.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.knox.gateway.i18n.resources;
+
+/**
+ *
+ */
+@Resources( bundle="some.bundle.name" )
+public interface ResourcesTestFormattingSubject {
+
+  @Resource(text="{0}")
+  String withAnnotationWithSimplePatternOneParam( int x );
+
+  @Resource(text="before{0}after")
+  String withAnnotationWithPatternOneParam( int x );
+
+  @Resource
+  String withAnnotationWithoutPatternOneParam( int x );
+
+  String withoutAnnotationsOrParameters();
+
+  String withoutAnnotationsWithOneParam( int x );
+
+  String withoutAnnotationsWithElevenParams( String p1, String p2, String p3, String p4, String p5, String p6, String p7, String p8, String p9, String p10, String p11 );
+
+  @Resource(text="{0},{1}")
+  String withMoreFormatParamsThanMethodParams( int x );
+
+  @Resource(text="{0}")
+  String withLessFormatParamsThanMethodParams( int x, int y );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject.java b/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject.java
new file mode 100644
index 0000000..e9b0abd
--- /dev/null
+++ b/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject.java
@@ -0,0 +1,29 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.resources;
+
+/**
+ *
+ */
+@Resources
+public interface ResourcesTestLocaleSubject {
+
+  @Resource(text="default=[{0}]")
+  String testResource( String param );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTestNamedSubject.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTestNamedSubject.java b/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTestNamedSubject.java
new file mode 100644
index 0000000..0c5f1af
--- /dev/null
+++ b/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTestNamedSubject.java
@@ -0,0 +1,29 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.resources;
+
+/**
+ *
+ */
+@Resources( bundle="org.apache.knox.gateway.i18n.resources.NamedBundle" )
+public interface ResourcesTestNamedSubject {
+
+  @Resource(text="default=[{0}]")
+  String testResource( String param );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/resources/META-INF/services/org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/resources/META-INF/services/org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory b/gateway-i18n/src/test/resources/META-INF/services/org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory
deleted file mode 100644
index 6f559f0..0000000
--- a/gateway-i18n/src/test/resources/META-INF/services/org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory
+++ /dev/null
@@ -1,17 +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.
-
-org.apache.hadoop.gateway.i18n.messages.loggers.test.TestMessageLoggerFactory
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/resources/META-INF/services/org.apache.knox.gateway.i18n.messages.MessageLoggerFactory
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/resources/META-INF/services/org.apache.knox.gateway.i18n.messages.MessageLoggerFactory b/gateway-i18n/src/test/resources/META-INF/services/org.apache.knox.gateway.i18n.messages.MessageLoggerFactory
new file mode 100644
index 0000000..bb615be
--- /dev/null
+++ b/gateway-i18n/src/test/resources/META-INF/services/org.apache.knox.gateway.i18n.messages.MessageLoggerFactory
@@ -0,0 +1,17 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+org.apache.knox.gateway.i18n.messages.loggers.test.TestMessageLoggerFactory
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/NamedBundle_en_CA.properties
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/NamedBundle_en_CA.properties b/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/NamedBundle_en_CA.properties
deleted file mode 100644
index 84dece1..0000000
--- a/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/NamedBundle_en_CA.properties
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-testResource=ca=[{0}]
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject.properties
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject.properties b/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject.properties
deleted file mode 100644
index 6acb5d1..0000000
--- a/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject.properties
+++ /dev/null
@@ -1,14 +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.

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject_en.properties
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject_en.properties b/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject_en.properties
deleted file mode 100644
index f5cf5e0..0000000
--- a/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject_en.properties
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-testResource=en=[{0}]
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject_en_GB.properties
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject_en_GB.properties b/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject_en_GB.properties
deleted file mode 100644
index 64cc4bf..0000000
--- a/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject_en_GB.properties
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-testResource=uk=[{0}]
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject_en_US.properties
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject_en_US.properties b/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject_en_US.properties
deleted file mode 100644
index d9a3cb7..0000000
--- a/gateway-i18n/src/test/resources/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject_en_US.properties
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-testResource=us=[{0}]
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/NamedBundle_en_CA.properties
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/NamedBundle_en_CA.properties b/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/NamedBundle_en_CA.properties
new file mode 100644
index 0000000..84dece1
--- /dev/null
+++ b/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/NamedBundle_en_CA.properties
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+testResource=ca=[{0}]
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject.properties
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject.properties b/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject.properties
new file mode 100644
index 0000000..6acb5d1
--- /dev/null
+++ b/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject.properties
@@ -0,0 +1,14 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject_en.properties
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject_en.properties b/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject_en.properties
new file mode 100644
index 0000000..f5cf5e0
--- /dev/null
+++ b/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject_en.properties
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+testResource=en=[{0}]
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject_en_GB.properties
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject_en_GB.properties b/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject_en_GB.properties
new file mode 100644
index 0000000..64cc4bf
--- /dev/null
+++ b/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject_en_GB.properties
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+testResource=uk=[{0}]
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject_en_US.properties
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject_en_US.properties b/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject_en_US.properties
new file mode 100644
index 0000000..d9a3cb7
--- /dev/null
+++ b/gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject_en_US.properties
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+testResource=us=[{0}]
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/deploy/HaProviderDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/deploy/HaProviderDeploymentContributor.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/deploy/HaProviderDeploymentContributor.java
deleted file mode 100644
index 10cce6c..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/deploy/HaProviderDeploymentContributor.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.hadoop.gateway.ha.deploy;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.ha.provider.HaDescriptor;
-import org.apache.hadoop.gateway.ha.provider.HaServiceConfig;
-import org.apache.hadoop.gateway.ha.provider.HaServletContextListener;
-import org.apache.hadoop.gateway.ha.provider.impl.HaDescriptorFactory;
-import org.apache.hadoop.gateway.ha.provider.impl.HaDescriptorManager;
-import org.apache.hadoop.gateway.ha.provider.impl.i18n.HaMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-import org.jboss.shrinkwrap.api.asset.StringAsset;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-public class HaProviderDeploymentContributor extends ProviderDeploymentContributorBase {
-
-   private static final String PROVIDER_ROLE_NAME = "ha";
-
-   private static final String PROVIDER_IMPL_NAME = "HaProvider";
-
-   private static final String HA_DESCRIPTOR_NAME = "ha.provider.descriptor";
-
-   private static final HaMessages LOG = MessagesFactory.get(HaMessages.class);
-
-   @Override
-   public String getRole() {
-      return PROVIDER_ROLE_NAME;
-   }
-
-   @Override
-   public String getName() {
-      return PROVIDER_IMPL_NAME;
-   }
-
-   @Override
-   public void contributeProvider(DeploymentContext context, Provider provider) {
-      Map<String, String> params = provider.getParams();
-      HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
-      for (Entry<String, String> entry : params.entrySet()) {
-         HaServiceConfig config = HaDescriptorFactory.createServiceConfig(entry.getKey(), entry.getValue());
-         descriptor.addServiceConfig(config);
-      }
-      StringWriter writer = new StringWriter();
-      try {
-         HaDescriptorManager.store(descriptor, writer);
-      } catch (IOException e) {
-         LOG.failedToWriteHaDescriptor(e);
-      }
-      String asset = writer.toString();
-      context.getWebArchive().addAsWebInfResource(
-            new StringAsset(asset),
-            HaServletContextListener.DESCRIPTOR_DEFAULT_FILE_NAME);
-      context.addDescriptor(HA_DESCRIPTOR_NAME, descriptor);
-   }
-
-   @Override
-   public void finalizeContribution(DeploymentContext context) {
-      if (context.getDescriptor(HA_DESCRIPTOR_NAME) != null) {
-         // Tell the provider the location of the descriptor.
-         // Doing this here instead of in 'contributeProvider' so that this ServletContextListener comes after the gateway services have been set.
-         context.getWebAppDescriptor().createListener().listenerClass(HaServletContextListener.class.getName());
-         context.getWebAppDescriptor().createContextParam()
-               .paramName(HaServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME)
-               .paramValue(HaServletContextListener.DESCRIPTOR_DEFAULT_LOCATION);
-      }
-   }
-
-   @Override
-   public void contributeFilter(DeploymentContext context, Provider provider, Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params) {
-      //no op
-   }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/dispatch/DefaultHaDispatch.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/dispatch/DefaultHaDispatch.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/dispatch/DefaultHaDispatch.java
deleted file mode 100644
index 4f66273..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/dispatch/DefaultHaDispatch.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.hadoop.gateway.ha.dispatch;
-
-import org.apache.hadoop.gateway.config.Configure;
-import org.apache.hadoop.gateway.config.Optional;
-import org.apache.hadoop.gateway.dispatch.DefaultDispatch;
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.ha.dispatch.i18n.HaDispatchMessages;
-import org.apache.hadoop.gateway.ha.provider.HaProvider;
-import org.apache.hadoop.gateway.ha.provider.HaServiceConfig;
-import org.apache.hadoop.gateway.ha.provider.impl.HaServiceConfigConstants;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.methods.HttpRequestBase;
-import org.apache.http.client.methods.HttpUriRequest;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.net.URI;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * Default HA dispatch class that has a very basic failover mechanism
- */
-public class DefaultHaDispatch extends DefaultDispatch {
-
-  protected static final String FAILOVER_COUNTER_ATTRIBUTE = "dispatch.ha.failover.counter";
-
-  private static final HaDispatchMessages LOG = MessagesFactory.get(HaDispatchMessages.class);
-
-  private int maxFailoverAttempts = HaServiceConfigConstants.DEFAULT_MAX_FAILOVER_ATTEMPTS;
-
-  private int failoverSleep = HaServiceConfigConstants.DEFAULT_FAILOVER_SLEEP;
-
-  private HaProvider haProvider;
-
-  @Optional
-  @Configure
-  private String serviceRole;
-
-  @Override
-  public void init() {
-    super.init();
-    LOG.initializingForResourceRole(getServiceRole());
-    if ( haProvider != null ) {
-      HaServiceConfig serviceConfig = haProvider.getHaDescriptor().getServiceConfig(getServiceRole());
-      maxFailoverAttempts = serviceConfig.getMaxFailoverAttempts();
-      failoverSleep = serviceConfig.getFailoverSleep();
-    }
-  }
-
-  public String getServiceRole() {
-    return serviceRole;
-  }
-
-  public void setServiceRole(String serviceRole) {
-    this.serviceRole = serviceRole;
-  }
-
-  public HaProvider getHaProvider() {
-    return haProvider;
-  }
-
-  @Configure
-  public void setHaProvider(HaProvider haProvider) {
-    this.haProvider = haProvider;
-  }
-
-  @Override
-  protected void executeRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse) throws IOException {
-    HttpResponse inboundResponse = null;
-    try {
-      inboundResponse = executeOutboundRequest(outboundRequest);
-      writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
-    } catch ( IOException e ) {
-      LOG.errorConnectingToServer(outboundRequest.getURI().toString(), e);
-      failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, e);
-    }
-  }
-
-
-  private void failoverRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse, HttpResponse inboundResponse, Exception exception) throws IOException {
-    LOG.failingOverRequest(outboundRequest.getURI().toString());
-    AtomicInteger counter = (AtomicInteger) inboundRequest.getAttribute(FAILOVER_COUNTER_ATTRIBUTE);
-    if ( counter == null ) {
-      counter = new AtomicInteger(0);
-    }
-    inboundRequest.setAttribute(FAILOVER_COUNTER_ATTRIBUTE, counter);
-    if ( counter.incrementAndGet() <= maxFailoverAttempts ) {
-      haProvider.markFailedURL(getServiceRole(), outboundRequest.getURI().toString());
-      //null out target url so that rewriters run again
-      inboundRequest.setAttribute(AbstractGatewayFilter.TARGET_REQUEST_URL_ATTRIBUTE_NAME, null);
-      URI uri = getDispatchUrl(inboundRequest);
-      ((HttpRequestBase) outboundRequest).setURI(uri);
-      if ( failoverSleep > 0 ) {
-        try {
-          Thread.sleep(failoverSleep);
-        } catch ( InterruptedException e ) {
-          LOG.failoverSleepFailed(getServiceRole(), e);
-        }
-      }
-      executeRequest(outboundRequest, inboundRequest, outboundResponse);
-    } else {
-      LOG.maxFailoverAttemptsReached(maxFailoverAttempts, getServiceRole());
-      if ( inboundResponse != null ) {
-        writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
-      } else {
-        throw new IOException(exception);
-      }
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/dispatch/i18n/HaDispatchMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/dispatch/i18n/HaDispatchMessages.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/dispatch/i18n/HaDispatchMessages.java
deleted file mode 100644
index 928f8b0..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/dispatch/i18n/HaDispatchMessages.java
+++ /dev/null
@@ -1,41 +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.hadoop.gateway.ha.dispatch.i18n;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-import org.apache.hadoop.gateway.i18n.messages.StackTrace;
-
-@Messages(logger = "org.apache.hadoop.gateway")
-public interface HaDispatchMessages {
-  @Message(level = MessageLevel.INFO, text = "Initializing Ha Dispatch for: {0}")
-  void initializingForResourceRole(String resourceRole);
-
-  @Message(level = MessageLevel.INFO, text = "Could not connect to server: {0} {1}")
-  void errorConnectingToServer(String uri, @StackTrace(level = MessageLevel.DEBUG) Exception e);
-
-  @Message(level = MessageLevel.INFO, text = "Failing over request to a different server: {0}")
-  void failingOverRequest(String uri);
-
-  @Message(level = MessageLevel.INFO, text = "Maximum attempts {0} to failover reached for service: {1}")
-  void maxFailoverAttemptsReached(int attempts, String service);
-
-  @Message(level = MessageLevel.INFO, text = "Error occurred while trying to sleep for failover : {0} {1}")
-  void failoverSleepFailed(String service, @StackTrace(level = MessageLevel.DEBUG) Exception e);
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaDescriptor.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaDescriptor.java
deleted file mode 100644
index e0b5b04..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaDescriptor.java
+++ /dev/null
@@ -1,34 +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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.ha.provider;
-
-import java.util.List;
-
-public interface HaDescriptor {
-
-   public void addServiceConfig(HaServiceConfig serviceConfig);
-
-   public HaServiceConfig getServiceConfig(String serviceName);
-
-   public List<String> getServiceNames();
-
-   public List<String> getEnabledServiceNames();
-
-   public List<HaServiceConfig> getServiceConfigs();
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaProvider.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaProvider.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaProvider.java
deleted file mode 100644
index 71d929d..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaProvider.java
+++ /dev/null
@@ -1,67 +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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.ha.provider;
-
-import java.util.List;
-
-public interface HaProvider {
-
-   public HaDescriptor getHaDescriptor();
-
-   /**
-    * Add a service name (role) as a HA service with the URLs that it is configured for
-    *
-    * @param serviceName the name of the service
-    * @param urls        the list of urls that can be used for that service
-    */
-   public void addHaService(String serviceName, List<String> urls);
-
-   /**
-    * Returns whether the service is enabled for HA
-    *
-    * @param serviceName the name of the service
-    * @return true if the service is enabled; false otherwise
-    */
-   public boolean isHaEnabled(String serviceName);
-
-   /**
-    * Returns the current URL that is known to be active for the service
-    *
-    * @param serviceName the name of the service
-    * @return the URL as a string or null if the service name is not found
-    */
-   public String getActiveURL(String serviceName);
-
-   /**
-    * Sets a given URL that is known to be active for the service
-    *
-    * @param serviceName the name of the service
-    * @param url the active url
-    */
-   public void setActiveURL(String serviceName, String url);
-
-   /**
-    * Mark the URL for the service as one that has failed. This method puts changes the active URL to
-    * the next available URL for the service.
-    *
-    * @param serviceName the name of the service
-    * @param url         the URL that has failed in some way
-    */
-   public void markFailedURL(String serviceName, String url);
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaServiceConfig.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaServiceConfig.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaServiceConfig.java
deleted file mode 100644
index 8c12b8e..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaServiceConfig.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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.ha.provider;
-
-public interface HaServiceConfig {
-
-   public void setServiceName(String name);
-
-   public String getServiceName();
-
-   public boolean isEnabled();
-
-   public void setEnabled(boolean enabled);
-
-   public void setMaxFailoverAttempts(int limit);
-
-   public int getMaxFailoverAttempts();
-
-   public void setFailoverSleep(int sleep);
-
-   public int getFailoverSleep();
-
-   public void setMaxRetryAttempts(int limit);
-
-   public int getMaxRetryAttempts();
-
-   public void setRetrySleep(int sleep);
-
-   public int getRetrySleep();
-
-   public String getZookeeperEnsemble();
-
-   public void setZookeeperEnsemble(String zookeeperEnsemble);
-
-   public String getZookeeperNamespace();
-
-   public void setZookeeperNamespace(String zookeeperNamespace);
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaServletContextListener.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaServletContextListener.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaServletContextListener.java
deleted file mode 100644
index b84e649..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/HaServletContextListener.java
+++ /dev/null
@@ -1,116 +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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.ha.provider;
-
-import org.apache.hadoop.gateway.ha.provider.impl.DefaultHaProvider;
-import org.apache.hadoop.gateway.ha.provider.impl.HaDescriptorManager;
-import org.apache.hadoop.gateway.ha.provider.impl.i18n.HaMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-
-import javax.servlet.ServletContext;
-import javax.servlet.ServletContextEvent;
-import javax.servlet.ServletContextListener;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.List;
-
-public class HaServletContextListener implements ServletContextListener {
-
-   public static final String PROVIDER_ATTRIBUTE_NAME = "haProvider";
-
-   public static final String DESCRIPTOR_LOCATION_INIT_PARAM_NAME = "haDescriptorLocation";
-
-   public static final String DESCRIPTOR_DEFAULT_FILE_NAME = "ha.xml";
-
-   public static final String DESCRIPTOR_DEFAULT_LOCATION = "/WEB-INF/" + DESCRIPTOR_DEFAULT_FILE_NAME;
-
-   private static final HaMessages LOG = MessagesFactory.get(HaMessages.class);
-
-
-   @Override
-   public void contextInitialized(ServletContextEvent event) {
-      HaDescriptor descriptor;
-      ServletContext servletContext = event.getServletContext();
-      try {
-         URL url = locateDescriptor(servletContext);
-         descriptor = loadDescriptor(url);
-      } catch (IOException e) {
-         throw new IllegalStateException(e);
-      }
-      setupHaProvider(descriptor, servletContext);
-   }
-
-   @Override
-   public void contextDestroyed(ServletContextEvent event) {
-      event.getServletContext().removeAttribute(PROVIDER_ATTRIBUTE_NAME);
-   }
-
-   public static HaProvider getHaProvider(ServletContext context) {
-      return (HaProvider) context.getAttribute(PROVIDER_ATTRIBUTE_NAME);
-   }
-
-   private void setupHaProvider(HaDescriptor descriptor, ServletContext servletContext) {
-      GatewayServices services = (GatewayServices) servletContext.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
-      String clusterName = (String) servletContext.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE);
-      ServiceRegistry serviceRegistry = services.getService(GatewayServices.SERVICE_REGISTRY_SERVICE);
-      HaProvider provider = new DefaultHaProvider(descriptor);
-      List<String> serviceNames = descriptor.getEnabledServiceNames();
-      for (String serviceName : serviceNames) {
-         provider.addHaService(serviceName, serviceRegistry.lookupServiceURLs(clusterName, serviceName));
-      }
-      servletContext.setAttribute(PROVIDER_ATTRIBUTE_NAME, provider);
-   }
-
-   private static URL locateDescriptor(ServletContext context) throws IOException {
-      String param = context.getInitParameter(DESCRIPTOR_LOCATION_INIT_PARAM_NAME);
-      if (param == null) {
-         param = DESCRIPTOR_DEFAULT_LOCATION;
-      }
-      URL url;
-      try {
-         url = context.getResource(param);
-      } catch (MalformedURLException e) {
-         // Ignore it and try using the value directly as a URL.
-         url = null;
-      }
-      if (url == null) {
-         url = new URL(param);
-      }
-      if (url == null) {
-         throw new FileNotFoundException(param);
-      }
-      return url;
-   }
-
-   private static HaDescriptor loadDescriptor(URL url) throws IOException {
-      InputStream stream = url.openStream();
-      HaDescriptor descriptor = HaDescriptorManager.load(stream);
-      try {
-         stream.close();
-      } catch (IOException e) {
-         LOG.failedToLoadHaDescriptor(e);
-      }
-      return descriptor;
-   }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/URLManager.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/URLManager.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/URLManager.java
deleted file mode 100644
index e9de8f0..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/URLManager.java
+++ /dev/null
@@ -1,37 +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.hadoop.gateway.ha.provider;
-
-import java.util.List;
-
-public interface URLManager {
-
-  public boolean supportsConfig(HaServiceConfig config);
-
-  public void setConfig(HaServiceConfig config);
-
-  public String getActiveURL();
-
-  public void setActiveURL(String url);
-
-  public List<String> getURLs();
-
-  public void setURLs(List<String> urls);
-
-  public void markFailed(String url);
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/URLManagerLoader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/URLManagerLoader.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/URLManagerLoader.java
deleted file mode 100644
index c92d0e5..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/URLManagerLoader.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.hadoop.gateway.ha.provider;
-
-import org.apache.hadoop.gateway.ha.provider.impl.DefaultURLManager;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-public class URLManagerLoader {
-
-  public static URLManager loadURLManager(HaServiceConfig config) {
-    if (config != null) {
-      ServiceLoader<URLManager> loader = ServiceLoader.load(URLManager.class);
-      if ( loader != null ) {
-        Iterator<URLManager> iterator = loader.iterator();
-        while ( iterator.hasNext() ) {
-          URLManager urlManager = iterator.next();
-          if ( urlManager.supportsConfig(config) ) {
-            urlManager.setConfig(config);
-            return urlManager;
-          }
-        }
-      }
-    }
-    return new DefaultURLManager();
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaDescriptor.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaDescriptor.java
deleted file mode 100644
index 7969439..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaDescriptor.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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.ha.provider.impl;
-
-import com.google.common.collect.Lists;
-import org.apache.hadoop.gateway.ha.provider.HaDescriptor;
-import org.apache.hadoop.gateway.ha.provider.HaServiceConfig;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-
-public class DefaultHaDescriptor implements HaDescriptor {
-
-   private ConcurrentHashMap<String, HaServiceConfig> serviceConfigs;
-
-   public DefaultHaDescriptor() {
-      serviceConfigs = new ConcurrentHashMap<>();
-   }
-
-   @Override
-   public void addServiceConfig(HaServiceConfig serviceConfig) {
-      if (serviceConfig == null) {
-         throw new IllegalArgumentException("Service config must not be null");
-      }
-      serviceConfigs.put(serviceConfig.getServiceName(), serviceConfig);
-   }
-
-   @Override
-   public HaServiceConfig getServiceConfig(String serviceName) {
-      return serviceConfigs.get(serviceName);
-   }
-
-   @Override
-   public List<HaServiceConfig> getServiceConfigs() {
-      return Lists.newArrayList(serviceConfigs.values());
-   }
-
-   @Override
-   public List<String> getServiceNames() {
-      return Lists.newArrayList(serviceConfigs.keySet());
-   }
-
-   @Override
-   public List<String> getEnabledServiceNames() {
-      ArrayList<String> services = new ArrayList<String>(serviceConfigs.size());
-      Collection<HaServiceConfig> configs = serviceConfigs.values();
-      for (HaServiceConfig config : configs) {
-         if (config.isEnabled()) {
-            services.add(config.getServiceName());
-         }
-      }
-      return services;
-   }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaProvider.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaProvider.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaProvider.java
deleted file mode 100644
index b1da180..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaProvider.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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.ha.provider.impl;
-
-import org.apache.hadoop.gateway.ha.provider.HaDescriptor;
-import org.apache.hadoop.gateway.ha.provider.HaProvider;
-import org.apache.hadoop.gateway.ha.provider.HaServiceConfig;
-import org.apache.hadoop.gateway.ha.provider.URLManager;
-import org.apache.hadoop.gateway.ha.provider.URLManagerLoader;
-import org.apache.hadoop.gateway.ha.provider.impl.i18n.HaMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-
-public class DefaultHaProvider implements HaProvider {
-
-  private static final HaMessages LOG = MessagesFactory.get(HaMessages.class);
-
-  private HaDescriptor descriptor;
-
-  private ConcurrentHashMap<String, URLManager> haServices;
-
-  public DefaultHaProvider(HaDescriptor descriptor) {
-    if ( descriptor == null ) {
-      throw new IllegalArgumentException("Descriptor can not be null");
-    }
-    this.descriptor = descriptor;
-    haServices = new ConcurrentHashMap<>();
-  }
-
-  @Override
-  public HaDescriptor getHaDescriptor() {
-    return descriptor;
-  }
-
-  @Override
-  public void addHaService(String serviceName, List<String> urls) {
-    HaServiceConfig haServiceConfig = descriptor.getServiceConfig(serviceName);
-    URLManager manager = URLManagerLoader.loadURLManager(haServiceConfig);
-    manager.setURLs(urls);
-    haServices.put(serviceName, manager);
-  }
-
-  @Override
-  public boolean isHaEnabled(String serviceName) {
-    HaServiceConfig config = descriptor.getServiceConfig(serviceName);
-    if ( config != null && config.isEnabled() ) {
-      return true;
-    }
-    return false;
-  }
-
-  @Override
-  public String getActiveURL(String serviceName) {
-    if ( haServices.containsKey(serviceName) ) {
-      return haServices.get(serviceName).getActiveURL();
-    }
-    LOG.noActiveUrlFound(serviceName);
-    return null;
-  }
-
-  @Override
-  public void setActiveURL(String serviceName, String url) {
-    if ( haServices.containsKey(serviceName) ) {
-      haServices.get(serviceName).setActiveURL(url);
-    } else {
-      LOG.noServiceFound(serviceName);
-    }
-
-  }
-
-  @Override
-  public void markFailedURL(String serviceName, String url) {
-    if ( haServices.containsKey(serviceName) ) {
-      haServices.get(serviceName).markFailed(url);
-    } else {
-      LOG.noServiceFound(serviceName);
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaServiceConfig.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaServiceConfig.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaServiceConfig.java
deleted file mode 100644
index e1d6937..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaServiceConfig.java
+++ /dev/null
@@ -1,124 +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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.ha.provider.impl;
-
-import org.apache.hadoop.gateway.ha.provider.HaServiceConfig;
-
-public class DefaultHaServiceConfig implements HaServiceConfig, HaServiceConfigConstants {
-
-  private String name;
-
-  private boolean enabled = DEFAULT_ENABLED;
-
-  private int maxFailoverAttempts = DEFAULT_MAX_FAILOVER_ATTEMPTS;
-
-  private int failoverSleep = DEFAULT_FAILOVER_SLEEP;
-
-  private int maxRetryAttempts = DEFAULT_MAX_RETRY_ATTEMPTS;
-
-  private int retrySleep = DEFAULT_RETRY_SLEEP;
-
-  private String zookeeperEnsemble;
-
-  private String zookeeperNamespace;
-
-  public DefaultHaServiceConfig(String name) {
-    this.name = name;
-  }
-
-  @Override
-
-  public String getServiceName() {
-    return name;
-  }
-
-  @Override
-  public void setServiceName(String name) {
-    this.name = name;
-  }
-
-  @Override
-  public boolean isEnabled() {
-    return enabled;
-  }
-
-  @Override
-  public void setEnabled(boolean enabled) {
-    this.enabled = enabled;
-  }
-
-  @Override
-  public int getMaxFailoverAttempts() {
-    return maxFailoverAttempts;
-  }
-
-  @Override
-  public void setMaxFailoverAttempts(int maxFailoverAttempts) {
-    this.maxFailoverAttempts = maxFailoverAttempts;
-  }
-
-  @Override
-  public int getFailoverSleep() {
-    return failoverSleep;
-  }
-
-  @Override
-  public void setFailoverSleep(int failoverSleep) {
-    this.failoverSleep = failoverSleep;
-  }
-
-  @Override
-  public int getMaxRetryAttempts() {
-    return maxRetryAttempts;
-  }
-
-  @Override
-  public void setMaxRetryAttempts(int maxRetryAttempts) {
-    this.maxRetryAttempts = maxRetryAttempts;
-  }
-
-  @Override
-  public int getRetrySleep() {
-    return retrySleep;
-  }
-
-  @Override
-  public void setRetrySleep(int retrySleep) {
-    this.retrySleep = retrySleep;
-  }
-
-  @Override
-  public String getZookeeperEnsemble() {
-    return zookeeperEnsemble;
-  }
-
-  @Override
-  public void setZookeeperEnsemble(String zookeeperEnsemble) {
-    this.zookeeperEnsemble = zookeeperEnsemble;
-  }
-
-  @Override
-  public String getZookeeperNamespace() {
-    return zookeeperNamespace;
-  }
-
-  @Override
-  public void setZookeeperNamespace(String zookeeperNamespace) {
-    this.zookeeperNamespace = zookeeperNamespace;
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultURLManager.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultURLManager.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultURLManager.java
deleted file mode 100644
index 484a580..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultURLManager.java
+++ /dev/null
@@ -1,101 +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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.ha.provider.impl;
-
-import com.google.common.collect.Lists;
-import org.apache.hadoop.gateway.ha.provider.HaServiceConfig;
-import org.apache.hadoop.gateway.ha.provider.URLManager;
-import org.apache.hadoop.gateway.ha.provider.impl.i18n.HaMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-
-import java.net.URI;
-import java.util.Iterator;
-import java.util.List;
-import java.util.concurrent.ConcurrentLinkedQueue;
-
-public class DefaultURLManager implements URLManager {
-
-  private static final HaMessages LOG = MessagesFactory.get(HaMessages.class);
-
-  private ConcurrentLinkedQueue<String> urls = new ConcurrentLinkedQueue<>();
-
-  public DefaultURLManager() {
-  }
-
-  @Override
-  public boolean supportsConfig(HaServiceConfig config) {
-    return true;
-  }
-
-  @Override
-  public void setConfig(HaServiceConfig config) {
-    //no-op
-  }
-
-  @Override
-  public String getActiveURL() {
-    return urls.peek();
-  }
-
-  @Override
-  public synchronized void setActiveURL(String url) {
-    String top = urls.peek();
-    if (top.equalsIgnoreCase(url)) {
-      return;
-    }
-    if (urls.contains(url)) {
-      urls.remove(url);
-      List<String> remainingList = getURLs();
-      urls.clear();
-      urls.add(url);
-      urls.addAll(remainingList);
-    }
-  }
-
-  @Override
-  public List<String> getURLs() {
-    return Lists.newArrayList(urls.iterator());
-  }
-
-  @Override
-  public synchronized void setURLs(List<String> urls) {
-    if ( urls != null && !urls.isEmpty()) {
-      this.urls.clear();
-      this.urls.addAll(urls);
-    }
-  }
-
-  @Override
-  public synchronized void markFailed(String url) {
-    String top = urls.peek();
-    boolean pushToBottom = false;
-    URI topUri = URI.create(top);
-    URI incomingUri = URI.create(url);
-    String topHostPort = topUri.getHost() + ":" + topUri.getPort();
-    String incomingHostPort = incomingUri.getHost() + ":" + incomingUri.getPort();
-    if ( topHostPort.equals(incomingHostPort) ) {
-      pushToBottom = true;
-    }
-    //put the failed url at the bottom
-    if ( pushToBottom ) {
-      String failed = urls.poll();
-      urls.offer(failed);
-      LOG.markedFailedUrl(failed, urls.peek());
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HS2ZookeeperURLManager.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HS2ZookeeperURLManager.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HS2ZookeeperURLManager.java
deleted file mode 100644
index 08b0590..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HS2ZookeeperURLManager.java
+++ /dev/null
@@ -1,145 +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.hadoop.gateway.ha.provider.impl;
-
-import org.apache.curator.framework.CuratorFramework;
-import org.apache.curator.framework.CuratorFrameworkFactory;
-import org.apache.curator.retry.ExponentialBackoffRetry;
-import org.apache.hadoop.gateway.ha.provider.HaServiceConfig;
-import org.apache.hadoop.gateway.ha.provider.impl.i18n.HaMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-
-import java.nio.charset.Charset;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class HS2ZookeeperURLManager extends DefaultURLManager {
-
-  private static final HaMessages LOG = MessagesFactory.get(HaMessages.class);
-
-  private static final Pattern kvPattern = Pattern.compile("([^=;]*)=([^;]*)[;]?");
-
-  private String zooKeeperEnsemble;
-
-  private String zooKeeperNamespace;
-
-  private HashSet<String> failedSet;
-
-  public HS2ZookeeperURLManager() {
-    failedSet = new LinkedHashSet<>();
-  }
-
-  @Override
-  public boolean supportsConfig(HaServiceConfig config) {
-    if (!config.getServiceName().equalsIgnoreCase("HIVE")) {
-      return false;
-    }
-    String zookeeperEnsemble = config.getZookeeperEnsemble();
-    String zookeeperNamespace = config.getZookeeperNamespace();
-    if ( zookeeperEnsemble != null && zookeeperNamespace != null && zookeeperEnsemble.trim().length() > 0 && zookeeperNamespace.trim().length() > 0) {
-      return true;
-    }
-    return false;
-  }
-
-  @Override
-  public void setConfig(HaServiceConfig config) {
-    zooKeeperEnsemble = config.getZookeeperEnsemble();
-    zooKeeperNamespace = config.getZookeeperNamespace();
-    setURLs(lookupURLs());
-  }
-
-  public List<String> lookupURLs() {
-    List<String> serverHosts = new ArrayList<>();
-    CuratorFramework zooKeeperClient =
-        CuratorFrameworkFactory.builder().connectString(zooKeeperEnsemble)
-            .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
-    try {
-      zooKeeperClient.start();
-      List<String> serverNodes = zooKeeperClient.getChildren().forPath("/" + zooKeeperNamespace);
-      for ( String serverNode : serverNodes ) {
-        String serverInfo =
-            new String(
-                zooKeeperClient.getData().forPath("/" + zooKeeperNamespace + "/" + serverNode),
-                Charset.forName("UTF-8"));
-        String serverURL = constructURL(serverInfo);
-        serverHosts.add(serverURL);
-      }
-    } catch ( Exception e ) {
-      LOG.failedToGetZookeeperUrls(e);
-      throw new RuntimeException(e);
-    } finally {
-      // Close the client connection with ZooKeeper
-      if ( zooKeeperClient != null ) {
-        zooKeeperClient.close();
-      }
-    }
-    return serverHosts;
-  }
-
-  private String constructURL(String serverInfo) {
-    Matcher matcher = kvPattern.matcher(serverInfo);
-    String scheme = "http";
-    String host = null;
-    String port = "10001";
-    String httpPath = "cliservice";
-    while (matcher.find()) {
-      if ( (matcher.group(1) != null) && matcher.group(2) != null ) {
-        switch ( matcher.group(1) ) {
-          case "hive.server2.thrift.bind.host" :
-            host = matcher.group(2);
-            break;
-          case "hive.server2.thrift.http.port" :
-            port = matcher.group(2);
-            break;
-          case "hive.server2.thrift.http.path" :
-            httpPath = matcher.group(2);
-            break;
-          case "hive.server2.use.SSL" :
-            if (Boolean.parseBoolean(matcher.group(2))) {
-              scheme = "https";
-            }
-        }
-      }
-    }
-    StringBuffer buffer = new StringBuffer();
-    buffer.append(scheme);
-    buffer.append("://");
-    buffer.append(host);
-    buffer.append(":");
-    buffer.append(port);
-    buffer.append("/");
-    buffer.append(httpPath);
-    return buffer.toString();
-  }
-
-  @Override
-  public synchronized void markFailed(String url) {
-    failedSet.add(url);
-    //refresh the list when we have hit all urls once
-    if (failedSet.size() >= getURLs().size()) {
-      failedSet.clear();
-      setURLs(lookupURLs());
-    }
-    super.markFailed(url);
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorConstants.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorConstants.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorConstants.java
deleted file mode 100644
index ce3e07d..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorConstants.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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.ha.provider.impl;
-
-/**
- * The constants for xml elements and attributes are meant to help render/consume the following:
- * <p/>
- * <ha>
- * <service name='foo' failoverLimit='3' enabled='true'/>
- * </ha>
- */
-public interface HaDescriptorConstants {
-
-   public static final String ROOT_ELEMENT = "ha";
-
-   public static final String SERVICE_ELEMENT = "service";
-
-   public static final String SERVICE_NAME_ATTRIBUTE = "name";
-
-   public static final String MAX_FAILOVER_ATTEMPTS = "maxFailoverAttempts";
-
-   public static final String FAILOVER_SLEEP = "failoverSleep";
-
-   public static final String MAX_RETRY_ATTEMPTS = "maxRetryAttempts";
-
-   public static final String RETRY_SLEEP = "retrySleep";
-
-   public static final String ENABLED_ATTRIBUTE = "enabled";
-
-   public static final String ZOOKEEPER_ENSEMBLE = "zookeeperEnsemble";
-
-   public static final String ZOOKEEPER_NAMESPACE = "zookeeperNamespace";
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorFactory.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorFactory.java
deleted file mode 100644
index aeb6716..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorFactory.java
+++ /dev/null
@@ -1,94 +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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.ha.provider.impl;
-
-import org.apache.hadoop.gateway.ha.provider.HaDescriptor;
-import org.apache.hadoop.gateway.ha.provider.HaServiceConfig;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public abstract class HaDescriptorFactory implements HaServiceConfigConstants {
-
-   public static HaDescriptor createDescriptor() {
-      return new DefaultHaDescriptor();
-   }
-
-   public static HaServiceConfig createServiceConfig(String serviceName, String config) {
-      Map<String, String> configMap = parseHaConfiguration(config);
-      String enabledValue = configMap.get(CONFIG_PARAM_ENABLED);
-      String maxFailoverAttempts = configMap.get(CONFIG_PARAM_MAX_FAILOVER_ATTEMPTS);
-      String failoverSleep = configMap.get(CONFIG_PARAM_FAILOVER_SLEEP);
-      String maxRetryAttempts = configMap.get(CONFIG_PARAM_MAX_RETRY_ATTEMPTS);
-      String retrySleep = configMap.get(CONFIG_PARAM_RETRY_SLEEP);
-      String zookeeperEnsemble = configMap.get(CONFIG_PARAM_ZOOKEEPER_ENSEMBLE);
-      String zookeeperNamespace = configMap.get(CONFIG_PARAM_ZOOKEEPER_NAMESPACE);
-      return createServiceConfig(serviceName, enabledValue, maxFailoverAttempts,
-          failoverSleep, maxRetryAttempts, retrySleep,
-          zookeeperEnsemble, zookeeperNamespace);
-   }
-
-   public static HaServiceConfig createServiceConfig(String serviceName, String enabledValue,
-                                                     String maxFailoverAttemptsValue, String failoverSleepValue,
-                                                     String maxRetryAttemptsValue, String retrySleepValue,
-                                                     String zookeeperEnsemble, String zookeeperNamespace) {
-      boolean enabled = DEFAULT_ENABLED;
-      int maxFailoverAttempts = DEFAULT_MAX_FAILOVER_ATTEMPTS;
-      int failoverSleep = DEFAULT_FAILOVER_SLEEP;
-      int maxRetryAttempts = DEFAULT_MAX_RETRY_ATTEMPTS;
-      int retrySleep = DEFAULT_RETRY_SLEEP;
-      if (enabledValue != null && enabledValue.trim().length() > 0) {
-         enabled = Boolean.parseBoolean(enabledValue);
-      }
-      if (maxFailoverAttemptsValue != null && maxFailoverAttemptsValue.trim().length() > 0) {
-         maxFailoverAttempts = Integer.parseInt(maxFailoverAttemptsValue);
-      }
-      if (failoverSleepValue != null && failoverSleepValue.trim().length() > 0) {
-         failoverSleep = Integer.parseInt(failoverSleepValue);
-      }
-      if (maxRetryAttemptsValue != null && maxRetryAttemptsValue.trim().length() > 0) {
-         maxRetryAttempts = Integer.parseInt(maxRetryAttemptsValue);
-      }
-      if (retrySleepValue != null && retrySleepValue.trim().length() > 0) {
-         retrySleep = Integer.parseInt(retrySleepValue);
-      }
-      DefaultHaServiceConfig serviceConfig = new DefaultHaServiceConfig(serviceName);
-      serviceConfig.setEnabled(enabled);
-      serviceConfig.setMaxFailoverAttempts(maxFailoverAttempts);
-      serviceConfig.setFailoverSleep(failoverSleep);
-      serviceConfig.setMaxRetryAttempts(maxRetryAttempts);
-      serviceConfig.setRetrySleep(retrySleep);
-      serviceConfig.setZookeeperEnsemble(zookeeperEnsemble);
-      serviceConfig.setZookeeperNamespace(zookeeperNamespace);
-      return serviceConfig;
-   }
-
-   private static Map<String, String> parseHaConfiguration(String configuration) {
-      Map<String, String> parameters = new HashMap<>();
-      if (configuration != null) {
-         String[] pairs = configuration.split(CONFIG_PAIRS_DELIMITER);
-         for (String pair : pairs) {
-            String[] tokens = pair.split(CONFIG_PAIR_DELIMITER);
-            if (tokens.length == 2) {
-               parameters.put(tokens[0], tokens[1]);
-            }
-         }
-      }
-      return parameters;
-   }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorManager.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorManager.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorManager.java
deleted file mode 100644
index f5e159f..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorManager.java
+++ /dev/null
@@ -1,109 +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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.ha.provider.impl;
-
-import org.apache.hadoop.gateway.ha.provider.HaDescriptor;
-import org.apache.hadoop.gateway.ha.provider.HaServiceConfig;
-import org.apache.hadoop.gateway.ha.provider.impl.i18n.HaMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.util.XmlUtils;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Writer;
-import java.util.List;
-
-public class HaDescriptorManager implements HaDescriptorConstants {
-
-   private static final HaMessages LOG = MessagesFactory.get(HaMessages.class);
-
-   public static void store(HaDescriptor descriptor, Writer writer) throws IOException {
-      try {
-         Document document = XmlUtils.createDocument();
-
-         Element root = document.createElement(ROOT_ELEMENT);
-         document.appendChild(root);
-
-         List<HaServiceConfig> serviceConfigs = descriptor.getServiceConfigs();
-         if (serviceConfigs != null && !serviceConfigs.isEmpty()) {
-            for (HaServiceConfig config : serviceConfigs) {
-               Element serviceElement = document.createElement(SERVICE_ELEMENT);
-               serviceElement.setAttribute(SERVICE_NAME_ATTRIBUTE, config.getServiceName());
-               serviceElement.setAttribute(MAX_FAILOVER_ATTEMPTS, Integer.toString(config.getMaxFailoverAttempts()));
-               serviceElement.setAttribute(FAILOVER_SLEEP, Integer.toString(config.getFailoverSleep()));
-               serviceElement.setAttribute(MAX_RETRY_ATTEMPTS, Integer.toString(config.getMaxRetryAttempts()));
-               serviceElement.setAttribute(RETRY_SLEEP, Integer.toString(config.getRetrySleep()));
-               serviceElement.setAttribute(ENABLED_ATTRIBUTE, Boolean.toString(config.isEnabled()));
-               if (config.getZookeeperEnsemble() != null) {
-                 serviceElement.setAttribute(ZOOKEEPER_ENSEMBLE, config.getZookeeperEnsemble());
-               }
-               if (config.getZookeeperNamespace() != null) {
-                 serviceElement.setAttribute(ZOOKEEPER_NAMESPACE, config.getZookeeperNamespace());
-               }
-               root.appendChild(serviceElement);
-            }
-         }
-
-         Transformer t = XmlUtils.getTransformer( true, true, 2, false );
-         XmlUtils.writeXml( document, writer, t );
-      } catch (ParserConfigurationException e) {
-         LOG.failedToWriteHaDescriptor(e);
-         throw new IOException(e);
-      } catch (TransformerException e) {
-         LOG.failedToWriteHaDescriptor(e);
-         throw new IOException(e);
-      }
-   }
-
-   public static HaDescriptor load(InputStream inputStream) throws IOException {
-      HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
-      try {
-         Document document = XmlUtils.readXml( inputStream );
-         NodeList nodeList = document.getElementsByTagName(SERVICE_ELEMENT);
-         if (nodeList != null && nodeList.getLength() > 0) {
-            for (int i = 0; i < nodeList.getLength(); i++) {
-               Element element = (Element) nodeList.item(i);
-               HaServiceConfig config = HaDescriptorFactory.createServiceConfig(element.getAttribute(SERVICE_NAME_ATTRIBUTE),
-                     element.getAttribute(ENABLED_ATTRIBUTE),
-                     element.getAttribute(MAX_FAILOVER_ATTEMPTS),
-                     element.getAttribute(FAILOVER_SLEEP),
-                     element.getAttribute(MAX_RETRY_ATTEMPTS),
-                     element.getAttribute(RETRY_SLEEP),
-                     element.getAttribute(ZOOKEEPER_ENSEMBLE),
-                     element.getAttribute(ZOOKEEPER_NAMESPACE));
-               descriptor.addServiceConfig(config);
-            }
-         }
-      } catch (ParserConfigurationException e) {
-         LOG.failedToLoadHaDescriptor(e);
-         throw new IOException(e);
-      } catch (SAXException e) {
-         LOG.failedToLoadHaDescriptor(e);
-         throw new IOException(e);
-      }
-      return descriptor;
-   }
-
-}


[59/64] knox git commit: Merge branch 'master' into KNOX-998-Package_Restructuring

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/912c5360/gateway-test/src/test/java/org/apache/knox/gateway/GatewayDeployFuncTest.java
----------------------------------------------------------------------
diff --cc gateway-test/src/test/java/org/apache/knox/gateway/GatewayDeployFuncTest.java
index aaae390,0000000..180f9dc
mode 100644,000000..100644
--- a/gateway-test/src/test/java/org/apache/knox/gateway/GatewayDeployFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/knox/gateway/GatewayDeployFuncTest.java
@@@ -1,353 -1,0 +1,337 @@@
 +/**
 + * Licensed to the Apache Software Foundation (ASF) under one
 + * or more contributor license agreements.  See the NOTICE file
 + * distributed with this work for additional information
 + * regarding copyright ownership.  The ASF licenses this file
 + * to you under the Apache License, Version 2.0 (the
 + * "License"); you may not use this file except in compliance
 + * with the License.  You may obtain a copy of the License at
 + *
 + *     http://www.apache.org/licenses/LICENSE-2.0
 + *
 + * Unless required by applicable law or agreed to in writing, software
 + * distributed under the License is distributed on an "AS IS" BASIS,
 + * WITHOUT 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.knox.gateway;
 +
 +import com.jayway.restassured.response.Response;
 +import com.mycila.xmltool.XMLDoc;
 +import com.mycila.xmltool.XMLTag;
 +import org.apache.commons.io.FileUtils;
 +import org.apache.directory.server.protocol.shared.transport.TcpTransport;
 +import org.apache.knox.gateway.config.GatewayConfig;
 +import org.apache.knox.gateway.security.ldap.SimpleLdapDirectoryServer;
 +import org.apache.knox.gateway.services.DefaultGatewayServices;
 +import org.apache.knox.gateway.services.ServiceLifecycleException;
 +import org.apache.hadoop.test.TestUtils;
 +import org.apache.hadoop.test.category.ReleaseTest;
 +import org.apache.http.HttpStatus;
 +import org.apache.log4j.Appender;
 +import org.hamcrest.MatcherAssert;
 +import org.hamcrest.Matchers;
 +import org.junit.After;
 +import org.junit.AfterClass;
 +import org.junit.Before;
 +import org.junit.BeforeClass;
 +import org.junit.Test;
 +import org.junit.experimental.categories.Category;
 +import org.slf4j.Logger;
 +import org.slf4j.LoggerFactory;
 +
 +import java.io.File;
 +import java.io.FileOutputStream;
 +import java.io.FilenameFilter;
 +import java.io.IOException;
 +import java.io.InputStream;
 +import java.net.URL;
- import java.nio.file.FileSystems;
- import java.nio.file.Path;
 +import java.util.Enumeration;
 +import java.util.HashMap;
 +import java.util.Map;
 +import java.util.UUID;
 +import java.util.regex.Pattern;
 +
 +import static com.jayway.restassured.RestAssured.given;
 +import static org.apache.hadoop.test.TestUtils.LOG_ENTER;
 +import static org.apache.hadoop.test.TestUtils.LOG_EXIT;
 +import static org.hamcrest.CoreMatchers.containsString;
 +import static org.hamcrest.CoreMatchers.is;
 +import static org.hamcrest.CoreMatchers.notNullValue;
 +import static org.hamcrest.Matchers.greaterThan;
 +import static org.junit.Assert.assertThat;
 +
 +@Category(ReleaseTest.class)
 +public class GatewayDeployFuncTest {
 +
 +  private static Class RESOURCE_BASE_CLASS = GatewayDeployFuncTest.class;
 +  private static Logger LOG = LoggerFactory.getLogger( GatewayDeployFuncTest.class );
 +
 +  public static Enumeration<Appender> appenders;
 +  public static GatewayConfig config;
 +  public static GatewayServer gateway;
 +  public static File gatewayHome;
 +  public static String gatewayUrl;
 +  public static String clusterUrl;
-   public static SimpleLdapDirectoryServer ldap;
-   public static TcpTransport ldapTransport;
++  private static GatewayTestDriver driver = new GatewayTestDriver();
 +
 +  @BeforeClass
 +  public static void setupSuite() throws Exception {
 +    LOG_ENTER();
 +    //appenders = NoOpAppender.setUp();
-     setupLdap();
++    driver.setupLdap(0);
 +    LOG_EXIT();
 +  }
 +
 +  @AfterClass
 +  public static void cleanupSuite() throws Exception {
 +    LOG_ENTER();
-     ldap.stop( true );
++    driver.cleanup();
 +    //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
 +    //NoOpAppender.tearDown( appenders );
 +    LOG_EXIT();
 +  }
 +
-   public static void setupLdap() throws Exception {
-     String basedir = System.getProperty("basedir");
-     if (basedir == null) {
-       basedir = new File(".").getCanonicalPath();
-     }
-     Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
- 
-     ldapTransport = new TcpTransport( 0 );
-     ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-     ldap.start();
-     LOG.info( "LDAP port = " + ldapTransport.getPort() );
-   }
- 
 +  @Before
 +  public void setupGateway() throws Exception {
 +
 +    File targetDir = new File( System.getProperty( "user.dir" ), "target" );
 +    File gatewayDir = new File( targetDir, "gateway-home-" + UUID.randomUUID() );
 +    gatewayDir.mkdirs();
 +    gatewayHome = gatewayDir;
 +
 +    GatewayTestConfig testConfig = new GatewayTestConfig();
 +    config = testConfig;
 +    testConfig.setGatewayHomeDir( gatewayDir.getAbsolutePath() );
 +
 +    File topoDir = new File( testConfig.getGatewayTopologyDir() );
 +    topoDir.mkdirs();
 +
 +    File deployDir = new File( testConfig.getGatewayDeploymentDir() );
 +    deployDir.mkdirs();
 +
 +    DefaultGatewayServices srvcs = new DefaultGatewayServices();
 +    Map<String,String> options = new HashMap<>();
 +    options.put( "persist-master", "false" );
 +    options.put( "master", "password" );
 +    try {
 +      srvcs.init( testConfig, options );
 +    } catch ( ServiceLifecycleException e ) {
 +      e.printStackTrace(); // I18N not required.
 +    }
 +    gateway = GatewayServer.startGateway( testConfig, srvcs );
 +    MatcherAssert.assertThat( "Failed to start gateway.", gateway, notNullValue() );
 +
 +    LOG.info( "Gateway port = " + gateway.getAddresses()[ 0 ].getPort() );
 +
 +    gatewayUrl = "http://localhost:" + gateway.getAddresses()[0].getPort() + "/" + config.getGatewayPath();
 +    clusterUrl = gatewayUrl + "/test-cluster";
 +  }
 +
 +  @After
 +  public void cleanupGateway() throws Exception {
 +    gateway.stop();
 +    FileUtils.deleteQuietly( gatewayHome );
 +  }
 +
 +  private static XMLTag createTopology() {
 +    XMLTag xml = XMLDoc.newDocument( true )
 +        .addRoot( "topology" )
 +        .addTag( "gateway" )
 +
 +        .addTag( "provider" )
 +        .addTag( "role" ).addText( "authentication" )
 +        .addTag( "name" ).addText( "ShiroProvider" )
 +        .addTag( "enabled" ).addText( "true" )
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm" )
-         .addTag( "value" ).addText( "KnoxLdapRealm" ).gotoParent()
++        .addTag( "value" ).addText( "org.apache.knox.gateway.shirorealm.KnoxLdapRealm" ).gotoParent()
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.userDnTemplate" )
 +        .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" ).gotoParent()
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
-         .addTag( "value" ).addText( "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() ).gotoParent()
++        .addTag( "value" ).addText( driver.getLdapUrl() ).gotoParent()
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.authenticationMechanism" )
 +        .addTag( "value" ).addText( "simple" ).gotoParent()
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "urls./**" )
 +        .addTag( "value" ).addText( "authcBasic" ).gotoParent().gotoParent()
 +        .addTag( "provider" )
 +        .addTag( "role" ).addText( "identity-assertion" )
 +        .addTag( "enabled" ).addText( "true" )
 +        .addTag( "name" ).addText( "Default" ).gotoParent()
 +        .addTag( "provider" )
 +        .gotoRoot()
 +        .addTag( "service" )
 +        .addTag( "role" ).addText( "test-service-role" )
 +        .gotoRoot();
 +    return xml;
 +  }
 +
 +  public static InputStream getResourceStream( String resource ) throws IOException {
 +    return getResourceUrl( resource ).openStream();
 +  }
 +
 +  public static URL getResourceUrl( String resource ) {
 +    URL url = ClassLoader.getSystemResource( getResourceName( resource ) );
 +    assertThat( "Failed to find test resource " + resource, url, Matchers.notNullValue() );
 +    return url;
 +  }
 +
 +  public static String getResourceName( String resource ) {
 +    return getResourceBaseName() + resource;
 +  }
 +
 +  public static String getResourceBaseName() {
 +    return RESOURCE_BASE_CLASS.getName().replaceAll( "\\.", "/" ) + "/";
 +  }
 +
 +  //@Test
 +  public void waitForManualTesting() throws IOException {
 +    System.in.read();
 +  }
 +
 +  @Test( timeout = TestUtils.LONG_TIMEOUT )
 +  public void testDeployRedeployUndeploy() throws InterruptedException, IOException {
 +    LOG_ENTER();
 +    long sleep = 200;
 +    int numFilesInWebInf = 4; // # files in WEB-INF (ie gateway.xml, rewrite.xml, shiro.ini, web.xml)
 +    String username = "guest";
 +    String password = "guest-password";
 +    String serviceUrl = clusterUrl + "/test-service-path/test-service-resource";
 +    long topoTimestampBefore, topoTimestampAfter;
 +
 +    File topoDir = new File( config.getGatewayTopologyDir() );
 +    File deployDir = new File( config.getGatewayDeploymentDir() );
 +    File earDir;
 +
 +    // Make sure deployment directory is empty.
 +    assertThat( topoDir.listFiles().length, is( 0 ) );
 +    assertThat( deployDir.listFiles().length, is( 0 ) );
 +
 +    File descriptor = writeTestTopology( "test-cluster", createTopology() );
 +    long writeTime = System.currentTimeMillis();
 +
 +    earDir = waitForFiles( deployDir, "test-cluster\\.topo\\.[0-9A-Fa-f]+", 1, 0, sleep );
 +    File warDir = new File( earDir, "%2F" );
 +    File webInfDir = new File( warDir, "WEB-INF" );
 +    waitForFiles( webInfDir, ".*", numFilesInWebInf, 0, sleep );
 +    waitForAccess( serviceUrl, username, password, sleep );
 +
 +    // Wait to make sure a second has passed to ensure the the file timestamps are different.
 +    waitForElapsed( writeTime, 1000, 100 );
 +
 +    // Redeploy and make sure the timestamp is updated.
 +    topoTimestampBefore = descriptor.lastModified();
 +    GatewayServer.redeployTopologies( null );
 +    writeTime = System.currentTimeMillis();
 +    topoTimestampAfter = descriptor.lastModified();
 +    assertThat( topoTimestampAfter, greaterThan( topoTimestampBefore ) );
 +
 +    // Check to make sure there are two war directories with the same root.
 +    earDir = waitForFiles( deployDir, "test-cluster\\.topo\\.[0-9A-Fa-f]+", 2, 1, sleep );
 +    warDir = new File( earDir, "%2F" );
 +    webInfDir = new File( warDir, "WEB-INF" );
 +    waitForFiles( webInfDir, ".*", numFilesInWebInf, 0, sleep );
 +    waitForAccess( serviceUrl, username, password, sleep );
 +
 +    // Wait to make sure a second has passed to ensure the the file timestamps are different.
 +    waitForElapsed( writeTime, 1000, 100 );
 +
 +    // Redeploy and make sure the timestamp is updated.
 +    topoTimestampBefore = descriptor.lastModified();
 +    GatewayServer.redeployTopologies( "test-cluster" );
 +    writeTime = System.currentTimeMillis();
 +    topoTimestampAfter = descriptor.lastModified();
 +    assertThat( topoTimestampAfter, greaterThan( topoTimestampBefore ) );
 +
 +    // Check to make sure there are two war directories with the same root.
 +    earDir = waitForFiles( deployDir, "test-cluster\\.topo\\.[0-9A-Fa-f]+", 3, 2, sleep );
 +    warDir = new File( earDir, "%2F" );
 +    webInfDir = new File( warDir, "WEB-INF" );
 +    waitForFiles( webInfDir, ".*", numFilesInWebInf, 0, sleep );
 +    waitForAccess( serviceUrl, username, password, sleep );
 +
 +    // Delete the test topology.
 +    assertThat( "Failed to delete the topology file.", descriptor.delete(), is( true ) );
 +
 +    // Wait to make sure a second has passed to ensure the the file timestamps are different.
 +    waitForElapsed( writeTime, 1000, 100 );
 +
 +    waitForFiles( deployDir, ".*", 0, -1, sleep );
 +
 +    // Wait a bit more to make sure undeployment finished.
 +    Thread.sleep( sleep );
 +
 +    // Make sure the test topology is not accessible.
 +    given().auth().preemptive().basic( username, password )
 +        .expect().statusCode( HttpStatus.SC_NOT_FOUND )
 +        .when().get( serviceUrl );
 +
 +    // Make sure deployment directory is empty.
 +    assertThat( topoDir.listFiles().length, is( 0 ) );
 +    assertThat( deployDir.listFiles().length, is( 0 ) );
 +    LOG_EXIT();
 +  }
 +
 +  private void waitForElapsed( long from, long total, long sleep ) throws InterruptedException {
 +    while( System.currentTimeMillis() - from < total ) {
 +      Thread.sleep( sleep );
 +    }
 +  }
 +
 +  private File writeTestTopology( String name, XMLTag xml ) throws IOException {
 +    // Create the test topology.
 +    File tempFile = new File( config.getGatewayTopologyDir(), name + ".xml." + UUID.randomUUID() );
 +    FileOutputStream stream = new FileOutputStream( tempFile );
 +    xml.toStream( stream );
 +    stream.close();
 +    File descriptor = new File( config.getGatewayTopologyDir(), name + ".xml" );
 +    tempFile.renameTo( descriptor );
 +    return descriptor;
 +  }
 +
 +  private File waitForFiles( File dir, String pattern, int count, int index, long sleep ) throws InterruptedException {
 +    RegexDirFilter filter = new RegexDirFilter( pattern );
 +    while( true ) {
 +      File[] files = dir.listFiles( filter );
 +      if( files.length == count ) {
 +        return ( index < 0 ) ? null : files[ index ];
 +      }
 +      Thread.sleep( sleep );
 +    }
 +  }
 +
 +  private void waitForAccess( String url, String username, String password, long sleep ) throws InterruptedException {
 +    while( true ) {
 +      Response response = given()
 +          .auth().preemptive().basic( username, password )
 +          .when().get( url ).andReturn();
 +      if( response.getStatusCode() == HttpStatus.SC_NOT_FOUND ) {
 +        Thread.sleep( sleep );
 +        continue;
 +      }
 +      assertThat( response.getContentType(), containsString( "text/plain" ) );
 +      assertThat( response.getBody().asString(), is( "test-service-response" ) );
 +      break;
 +    }
 +  }
 +
 +  private class RegexDirFilter implements FilenameFilter {
 +
 +    Pattern pattern;
 +
 +    RegexDirFilter( String regex ) {
 +      pattern = Pattern.compile( regex );
 +    }
 +
 +    @Override
 +    public boolean accept( File dir, String name ) {
 +      return pattern.matcher( name ).matches();
 +    }
 +  }
 +
 +}

http://git-wip-us.apache.org/repos/asf/knox/blob/912c5360/gateway-test/src/test/java/org/apache/knox/gateway/GatewayLdapDynamicGroupFuncTest.java
----------------------------------------------------------------------
diff --cc gateway-test/src/test/java/org/apache/knox/gateway/GatewayLdapDynamicGroupFuncTest.java
index d6863e5,0000000..2b0d28a
mode 100755,000000..100755
--- a/gateway-test/src/test/java/org/apache/knox/gateway/GatewayLdapDynamicGroupFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/knox/gateway/GatewayLdapDynamicGroupFuncTest.java
@@@ -1,323 -1,0 +1,311 @@@
 +/**
 + * Licensed to the Apache Software Foundation (ASF) under one
 + * or more contributor license agreements.  See the NOTICE file
 + * distributed with this work for additional information
 + * regarding copyright ownership.  The ASF licenses this file
 + * to you under the Apache License, Version 2.0 (the
 + * "License"); you may not use this file except in compliance
 + * with the License.  You may obtain a copy of the License at
 + *
 + *     http://www.apache.org/licenses/LICENSE-2.0
 + *
 + * Unless required by applicable law or agreed to in writing, software
 + * distributed under the License is distributed on an "AS IS" BASIS,
 + * WITHOUT 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.knox.gateway;
 +
 +import static com.jayway.restassured.RestAssured.given;
 +import static org.apache.hadoop.test.TestUtils.LOG_ENTER;
 +import static org.apache.hadoop.test.TestUtils.LOG_EXIT;
 +import static org.hamcrest.CoreMatchers.is;
 +import static org.hamcrest.CoreMatchers.notNullValue;
 +import static org.junit.Assert.assertThat;
 +
 +import java.io.File;
 +import java.io.FileOutputStream;
 +import java.io.IOException;
 +import java.io.InputStream;
- import java.net.InetSocketAddress;
 +import java.net.URL;
 +import java.nio.file.FileSystems;
 +import java.nio.file.Path;
 +import java.util.Enumeration;
 +import java.util.HashMap;
 +import java.util.Map;
 +import java.util.UUID;
 +
 +import org.apache.directory.server.protocol.shared.transport.TcpTransport;
 +import org.apache.knox.gateway.config.GatewayConfig;
 +import org.apache.knox.gateway.security.ldap.SimpleLdapDirectoryServer;
 +import org.apache.knox.gateway.services.DefaultGatewayServices;
 +import org.apache.knox.gateway.services.GatewayServices;
 +import org.apache.knox.gateway.services.ServiceLifecycleException;
 +import org.apache.knox.gateway.services.security.AliasService;
 +import org.apache.hadoop.test.TestUtils;
 +import org.apache.http.HttpStatus;
 +import org.apache.log4j.Appender;
 +import org.hamcrest.MatcherAssert;
 +import org.hamcrest.Matchers;
 +import org.junit.AfterClass;
 +import org.junit.BeforeClass;
 +import org.junit.Test;
 +import org.slf4j.Logger;
 +import org.slf4j.LoggerFactory;
 +
 +import com.mycila.xmltool.XMLDoc;
 +import com.mycila.xmltool.XMLTag;
 +
 +/**
 + * Functional test to verify : looking up ldap groups from directory
 + * and using them in acl authorization checks
 + *
 + */
 +public class GatewayLdapDynamicGroupFuncTest {
 +
 +  private static Class RESOURCE_BASE_CLASS = GatewayLdapDynamicGroupFuncTest.class;
 +  private static Logger LOG = LoggerFactory.getLogger( GatewayLdapDynamicGroupFuncTest.class );
 +
 +  public static Enumeration<Appender> appenders;
 +  public static GatewayConfig config;
 +  public static GatewayServer gateway;
 +  public static String gatewayUrl;
 +  public static String clusterUrl;
 +  public static String serviceUrl;
-   public static SimpleLdapDirectoryServer ldap;
-   public static TcpTransport ldapTransport;
++  private static GatewayTestDriver driver = new GatewayTestDriver();
 +
 +  @BeforeClass
 +  public static void setupSuite() throws Exception {
 +    LOG_ENTER();
 +    //appenders = NoOpAppender.setUp();
-     int port = setupLdap();
-     setupGateway(port);
-     TestUtils.awaitPortOpen( new InetSocketAddress( "localhost", port ), 10000, 100 );
++    String basedir = System.getProperty("basedir");
++    if (basedir == null) {
++      basedir = new File(".").getCanonicalPath();
++    }
++    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users-dynamic.ldif");
++    driver.setupLdap( 0, path.toFile() );
++    setupGateway();
 +    TestUtils.awaitNon404HttpStatus( new URL( serviceUrl ), 10000, 100 );
 +    LOG_EXIT();
 +  }
 +
 +  @AfterClass
 +  public static void cleanupSuite() throws Exception {
 +    LOG_ENTER();
 +    gateway.stop();
-     ldap.stop( true );
++    driver.cleanup();
 +    //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
 +    //NoOpAppender.tearDown( appenders );
 +    LOG_EXIT();
 +  }
 +
-   public static int setupLdap() throws Exception {
-     String basedir = System.getProperty("basedir");
-     if (basedir == null) {
-       basedir = new File(".").getCanonicalPath();
-     }
-     Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users-dynamic.ldif");
- 
-     ldapTransport = new TcpTransport( 0 );
-     ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-     ldap.start();
-     LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-     return ldapTransport.getAcceptor().getLocalAddress().getPort();
-   }
- 
-   public static void setupGateway(int ldapPort) throws IOException, Exception {
++  public static void setupGateway() throws IOException, Exception {
 +
 +    File targetDir = new File( System.getProperty( "user.dir" ), "target" );
 +    File gatewayDir = new File( targetDir, "gateway-home-" + UUID.randomUUID() );
 +    gatewayDir.mkdirs();
 +
 +    GatewayTestConfig testConfig = new GatewayTestConfig();
 +    config = testConfig;
 +    testConfig.setGatewayHomeDir( gatewayDir.getAbsolutePath() );
 +
 +    File topoDir = new File( testConfig.getGatewayTopologyDir() );
 +    topoDir.mkdirs();
 +
 +    File deployDir = new File( testConfig.getGatewayDeploymentDir() );
 +    deployDir.mkdirs();
 +
 +    DefaultGatewayServices srvcs = new DefaultGatewayServices();
 +    Map<String,String> options = new HashMap<>();
 +    options.put( "persist-master", "false" );
 +    options.put( "master", "password" );
 +    try {
 +      srvcs.init( testConfig, options );
 +    } catch ( ServiceLifecycleException e ) {
 +      e.printStackTrace(); // I18N not required.
 +    }
 +
 +    /*
 +    System.setProperty(GatewayConfig.GATEWAY_HOME_VAR, gatewayDir.getAbsolutePath());
 +    System.err.println("GH 10: " + System.getProperty(GatewayConfig.GATEWAY_HOME_VAR));
 +    ByteArrayOutputStream outContent = new ByteArrayOutputStream();
 +    System.setOut(new PrintStream(outContent));
 +    String[] argvals = {"create-alias", "ldcSystemPassword", "--value", "guest-password", "--master", "hadoop", "--cluster", "testdg-cluster"};
 +    KnoxCLI cli = new KnoxCLI();
 +    cli.setConf(new GatewayConfigImpl());
 +    cli.run(argvals);
 +
 +    outContent.reset();
 +    String[] args1 = {"list-alias", "--cluster", "testdg-cluster", "--master", "hadoop"};
 +    cli = new KnoxCLI();
 +    cli.run(args1);
 +    System.err.println("ALIAS LIST: " + outContent.toString());
 +
 +    AliasService as1 = cli.getGatewayServices().getService(GatewayServices.ALIAS_SERVICE);
 +    char[] passwordChars1 = as1.getPasswordFromAliasForCluster( "test-cluster", "ldcsystemPassword");
 +    System.err.println("ALIAS value1: " + new String(passwordChars1));
 +    */
 +
 +    gateway = GatewayServer.startGateway( testConfig, srvcs );
 +    MatcherAssert.assertThat( "Failed to start gateway.", gateway, notNullValue() );
 +
 +    LOG.info( "Gateway port = " + gateway.getAddresses()[ 0 ].getPort() );
 +
 +    gatewayUrl = "http://localhost:" + gateway.getAddresses()[0].getPort() + "/" + config.getGatewayPath();
 +    clusterUrl = gatewayUrl + "/testdg-cluster";
 +    serviceUrl = clusterUrl + "/test-service-path/test-service-resource";
 +
 +    ///*
 +    GatewayServices services = GatewayServer.getGatewayServices();
 +    AliasService aliasService = (AliasService)services.getService(GatewayServices.ALIAS_SERVICE);
 +    aliasService.addAliasForCluster("testdg-cluster", "ldcSystemPassword", "guest-password");
 +
 +    char[] password1 = aliasService.getPasswordFromAliasForCluster( "testdg-cluster", "ldcSystemPassword");
 +    //System.err.println("SETUP password 10: " + ((password1 == null) ? "NULL" : new String(password1)));
 +
 +    File descriptor = new File( topoDir, "testdg-cluster.xml" );
 +    FileOutputStream stream = new FileOutputStream( descriptor );
-     createTopology(ldapPort).toStream( stream );
++    createTopology().toStream( stream );
 +    stream.close();
 +
 +  }
 +
-   private static XMLTag createTopology(int ldapPort) {
++  private static XMLTag createTopology() {
 +    XMLTag xml = XMLDoc.newDocument( true )
 +        .addRoot( "topology" )
 +        .addTag( "gateway" )
 +
 +        .addTag( "provider" )
 +        .addTag( "role" ).addText( "authentication" )
 +        .addTag( "name" ).addText( "ShiroProvider" )
 +        .addTag( "enabled" ).addText( "true" )
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm" )
-         .addTag( "value" ).addText( "KnoxLdapRealm" )
++        .addTag( "value" ).addText( "org.apache.knox.gateway.shirorealm.KnoxLdapRealm" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapGroupContextFactory" )
-         .addTag( "value" ).addText( "KnoxLdapContextFactory" )
++        .addTag( "value" ).addText( "org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory" )
 +        .addTag( "value" ).addText( "$ldapGroupContextFactory" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.authenticationMechanism" )
 +        .addTag( "value" ).addText( "simple" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
-         .addTag( "value" ).addText( "ldap://localhost:"  + ldapPort)
++        .addTag( "value" ).addText( driver.getLdapUrl())
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.userDnTemplate" )
 +        .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.authorizationEnabled" )
 +        .addTag( "value" ).addText( "true" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.systemAuthenticationMechanism" )
 +        .addTag( "value" ).addText( "simple" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.searchBase" )
 +        .addTag( "value" ).addText( "ou=groups,dc=hadoop,dc=apache,dc=org" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.groupObjectClass" )
 +        .addTag( "value" ).addText( "groupofurls" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.memberAttribute" )
 +        .addTag( "value" ).addText( "memberurl" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.memberAttributeValueTemplate" )
 +        .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.systemUsername" )
 +        .addTag( "value" ).addText( "uid=guest,ou=people,dc=hadoop,dc=apache,dc=org" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.clusterName" )
 +        .addTag( "value" ).addText( "testdg-cluster" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.systemPassword" )
 +        .addTag( "value" ).addText( "S{ALIAS=ldcSystemPassword}" )
 +        // .addTag( "value" ).addText( "guest-password" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "urls./**" )
 +        .addTag( "value" ).addText( "authcBasic" )
 +
 +        .gotoParent().gotoParent().addTag( "provider" )
 +        .addTag( "role" ).addText( "authorization" )
 +        .addTag( "name" ).addText( "AclsAuthz" )
 +        .addTag( "enabled" ).addText( "true" )
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "test-service-role.acl" ) // FIXME[dilli]
 +        .addTag( "value" ).addText( "*;directors;*" )
 +
 +        .gotoParent().gotoParent().addTag( "provider" )
 +        .addTag( "role" ).addText( "identity-assertion" )
 +        .addTag( "enabled" ).addText( "true" )
 +        .addTag( "name" ).addText( "Default" ).gotoParent()
 +
 +        .gotoRoot()
 +        .addTag( "service" )
 +        .addTag( "role" ).addText( "test-service-role" )
 +        .gotoRoot();
 +         // System.out.println( "GATEWAY=" + xml.toString() );
 +    return xml;
 +  }
 +
 +  public static InputStream getResourceStream( String resource ) throws IOException {
 +    return getResourceUrl( resource ).openStream();
 +  }
 +
 +  public static URL getResourceUrl( String resource ) {
 +    URL url = ClassLoader.getSystemResource( getResourceName( resource ) );
 +    assertThat( "Failed to find test resource " + resource, url, Matchers.notNullValue() );
 +    return url;
 +  }
 +
 +  public static String getResourceName( String resource ) {
 +    return getResourceBaseName() + resource;
 +  }
 +
 +  public static String getResourceBaseName() {
 +    return RESOURCE_BASE_CLASS.getName().replaceAll( "\\.", "/" ) + "/";
 +  }
 +
 +  // @Test
 +  public void waitForManualTesting() throws IOException {
 +    System.in.read();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testGroupMember() throws ClassNotFoundException, Exception {
 +    LOG_ENTER();
 +    String username = "bob";
 +    String password = "bob-password";
 +    String serviceUrl = clusterUrl + "/test-service-path/test-service-resource";
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_OK )
 +        .contentType( "text/plain" )
 +        .body( is( "test-service-response" ) )
 +        .when().get( serviceUrl );
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testNonGroupMember() throws ClassNotFoundException {
 +    LOG_ENTER();
 +    String username = "guest";
 +    String password = "guest-password";
 +    String serviceUrl = clusterUrl + "/test-service-path/test-service-resource";
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_FORBIDDEN )
 +        .when().get( serviceUrl );
 +    LOG_EXIT();
 +  }
-   
++
 +}

http://git-wip-us.apache.org/repos/asf/knox/blob/912c5360/gateway-test/src/test/java/org/apache/knox/gateway/GatewayLdapGroupFuncTest.java
----------------------------------------------------------------------
diff --cc gateway-test/src/test/java/org/apache/knox/gateway/GatewayLdapGroupFuncTest.java
index ffe0f89,0000000..cb166b3
mode 100644,000000..100644
--- a/gateway-test/src/test/java/org/apache/knox/gateway/GatewayLdapGroupFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/knox/gateway/GatewayLdapGroupFuncTest.java
@@@ -1,324 -1,0 +1,308 @@@
 +/**
 + * Licensed to the Apache Software Foundation (ASF) under one
 + * or more contributor license agreements.  See the NOTICE file
 + * distributed with this work for additional information
 + * regarding copyright ownership.  The ASF licenses this file
 + * to you under the Apache License, Version 2.0 (the
 + * "License"); you may not use this file except in compliance
 + * with the License.  You may obtain a copy of the License at
 + *
 + *     http://www.apache.org/licenses/LICENSE-2.0
 + *
 + * Unless required by applicable law or agreed to in writing, software
 + * distributed under the License is distributed on an "AS IS" BASIS,
 + * WITHOUT 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.knox.gateway;
 +
 +import static com.jayway.restassured.RestAssured.given;
 +import static org.apache.hadoop.test.TestUtils.LOG_ENTER;
 +import static org.apache.hadoop.test.TestUtils.LOG_EXIT;
 +import static org.hamcrest.CoreMatchers.is;
 +import static org.hamcrest.CoreMatchers.notNullValue;
 +import static org.junit.Assert.assertThat;
 +
 +import java.io.File;
 +import java.io.FileOutputStream;
 +import java.io.IOException;
 +import java.io.InputStream;
 +import java.net.InetSocketAddress;
 +import java.net.URL;
 +import java.nio.file.FileSystems;
 +import java.nio.file.Path;
 +import java.util.Enumeration;
 +import java.util.HashMap;
 +import java.util.Map;
 +import java.util.UUID;
 +
 +import org.apache.directory.server.protocol.shared.transport.TcpTransport;
 +import org.apache.knox.gateway.config.GatewayConfig;
 +import org.apache.knox.gateway.security.ldap.SimpleLdapDirectoryServer;
 +import org.apache.knox.gateway.services.DefaultGatewayServices;
 +import org.apache.knox.gateway.services.GatewayServices;
 +import org.apache.knox.gateway.services.ServiceLifecycleException;
 +import org.apache.knox.gateway.services.security.AliasService;
 +import org.apache.hadoop.test.TestUtils;
 +import org.apache.http.HttpStatus;
 +import org.apache.log4j.Appender;
 +import org.hamcrest.MatcherAssert;
 +import org.hamcrest.Matchers;
 +import org.junit.AfterClass;
 +import org.junit.BeforeClass;
 +import org.junit.Ignore;
 +import org.junit.Test;
 +import org.slf4j.Logger;
 +import org.slf4j.LoggerFactory;
 +
 +import com.mycila.xmltool.XMLDoc;
 +import com.mycila.xmltool.XMLTag;
 +
 +/**
 + * Functional test to verify : looking up ldap groups from directory
 + * and using them in acl authorization checks
 + *
 + */
 +public class GatewayLdapGroupFuncTest {
 +
 +  private static Class RESOURCE_BASE_CLASS = GatewayLdapGroupFuncTest.class;
 +  private static Logger LOG = LoggerFactory.getLogger( GatewayLdapGroupFuncTest.class );
 +
 +  public static Enumeration<Appender> appenders;
 +  public static GatewayConfig config;
 +  public static GatewayServer gateway;
 +  public static String gatewayUrl;
 +  public static String clusterUrl;
 +  public static String serviceUrl;
-   public static SimpleLdapDirectoryServer ldap;
-   public static TcpTransport ldapTransport;
++  private static GatewayTestDriver driver = new GatewayTestDriver();
 +
 +  @BeforeClass
 +  public static void setupSuite() throws Exception {
 +    LOG_ENTER();
 +    //appenders = NoOpAppender.setUp();
-     int port = setupLdap();
-     setupGateway(port);
-     TestUtils.awaitPortOpen( new InetSocketAddress( "localhost", port ), 10000, 100 );
++    driver.setupLdap(0);
++    setupGateway();
 +    TestUtils.awaitNon404HttpStatus( new URL( serviceUrl ), 10000, 100 );
 +    LOG_EXIT();
 +  }
 +
 +  @AfterClass
 +  public static void cleanupSuite() throws Exception {
 +    LOG_ENTER();
 +    gateway.stop();
-     ldap.stop( true );
++    driver.cleanup();
 +    //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
 +    //NoOpAppender.tearDown( appenders );
 +    LOG_EXIT();
 +  }
 +
-   public static int setupLdap() throws Exception {
-     String basedir = System.getProperty("basedir");
-     if (basedir == null) {
-       basedir = new File(".").getCanonicalPath();
-     }
-     Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
- 
-     ldapTransport = new TcpTransport( 0 );
-     ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-     ldap.start();
-     LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-     return ldapTransport.getAcceptor().getLocalAddress().getPort();
-   }
- 
-   public static void setupGateway(int ldapPort) throws Exception {
++  public static void setupGateway() throws Exception {
 +
 +    File targetDir = new File( System.getProperty( "user.dir" ), "target" );
 +    File gatewayDir = new File( targetDir, "gateway-home-" + UUID.randomUUID() );
 +    gatewayDir.mkdirs();
 +
 +    GatewayTestConfig testConfig = new GatewayTestConfig();
 +    config = testConfig;
 +    testConfig.setGatewayHomeDir( gatewayDir.getAbsolutePath() );
 +
 +    File topoDir = new File( testConfig.getGatewayTopologyDir() );
 +    topoDir.mkdirs();
 +
 +    File deployDir = new File( testConfig.getGatewayDeploymentDir() );
 +    deployDir.mkdirs();
 +
 +    DefaultGatewayServices srvcs = new DefaultGatewayServices();
 +    Map<String,String> options = new HashMap<>();
 +    options.put( "persist-master", "true" );
 +    options.put( "master", "hadoop" );
 +
 +    try {
 +      srvcs.init( testConfig, options );
 +    } catch ( ServiceLifecycleException e ) {
 +      e.printStackTrace(); // I18N not required.
 +    }
 +
 +    /*
 +    System.setProperty(GatewayConfig.GATEWAY_HOME_VAR, gatewayDir.getAbsolutePath());
 +    System.err.println("GH 10: " + System.getProperty(GatewayConfig.GATEWAY_HOME_VAR));
 +    ByteArrayOutputStream outContent = new ByteArrayOutputStream();
 +    System.setOut(new PrintStream(outContent));
 +    String[] argvals = {"create-alias", "ldcSystemPassword", "--value", "guest-password", "--master", "hadoop", "--cluster", "test-cluster"};
 +    KnoxCLI cli = new KnoxCLI();
 +    cli.setConf(new GatewayConfigImpl());
 +    cli.run(argvals);
 +
 +    outContent.reset();
 +    String[] args1 = {"list-alias", "--cluster", "test-cluster", "--master", "hadoop"};
 +    cli = new KnoxCLI();
 +    cli.run(args1);
 +    System.err.println("ALIAS LIST: " + outContent.toString());
 +
 +    AliasService as1 = cli.getGatewayServices().getService(GatewayServices.ALIAS_SERVICE);
 +    char[] passwordChars1 = as1.getPasswordFromAliasForCluster( "test-cluster", "ldcsystemPassword");
 +    System.err.println("ALIAS value1: " + new String(passwordChars1));
 +    */
 +
 +    gateway = GatewayServer.startGateway( testConfig, srvcs );
 +    MatcherAssert.assertThat( "Failed to start gateway.", gateway, notNullValue() );
 +
 +    LOG.info( "Gateway port = " + gateway.getAddresses()[ 0 ].getPort() );
 +
 +    gatewayUrl = "http://localhost:" + gateway.getAddresses()[0].getPort() + "/" + config.getGatewayPath();
 +    clusterUrl = gatewayUrl + "/test-cluster";
 +    serviceUrl = clusterUrl + "/test-service-path/test-service-resource";
 +
 +    ///*
 +    GatewayServices services = GatewayServer.getGatewayServices();
 +    AliasService aliasService = (AliasService)services.getService(GatewayServices.ALIAS_SERVICE);
 +    aliasService.addAliasForCluster("test-cluster", "ldcSystemPassword", "guest-password");
 +
 +    char[] password1 = aliasService.getPasswordFromAliasForCluster( "test-cluster", "ldcSystemPassword");
 +    //System.err.println("SETUP password 10: " + ((password1 == null) ? "NULL" : new String(password1)));
 +
 +    File descriptor = new File( topoDir, "test-cluster.xml" );
 +    FileOutputStream stream = new FileOutputStream( descriptor );
-     createTopology(ldapPort).toStream( stream );
++    createTopology().toStream( stream );
 +    stream.close();
 +  }
 +
-   private static XMLTag createTopology(int ldapPort) {
++  private static XMLTag createTopology() {
 +    XMLTag xml = XMLDoc.newDocument( true )
 +        .addRoot( "topology" )
 +        .addTag( "gateway" )
 +
 +        .addTag( "provider" )
 +        .addTag( "role" ).addText( "authentication" )
 +        .addTag( "name" ).addText( "ShiroProvider" )
 +        .addTag( "enabled" ).addText( "true" )
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm" )
-         .addTag( "value" ).addText( "KnoxLdapRealm" )
++        .addTag( "value" ).addText( "org.apache.knox.gateway.shirorealm.KnoxLdapRealm" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapGroupContextFactory" )
-         .addTag( "value" ).addText( "KnoxLdapContextFactory" )
++        .addTag( "value" ).addText( "org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory" )
 +        .addTag( "value" ).addText( "$ldapGroupContextFactory" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.authenticationMechanism" )
 +        .addTag( "value" ).addText( "simple" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
-         .addTag( "value" ).addText( "ldap://localhost:"  + ldapPort)
++        .addTag( "value" ).addText( driver.getLdapUrl())
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.userDnTemplate" )
 +        .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.authorizationEnabled" )
 +        .addTag( "value" ).addText( "true" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.systemAuthenticationMechanism" )
 +        .addTag( "value" ).addText( "simple" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.searchBase" )
 +        .addTag( "value" ).addText( "ou=groups,dc=hadoop,dc=apache,dc=org" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.groupObjectClass" )
 +        .addTag( "value" ).addText( "groupofnames" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.memberAttribute" )
 +        .addTag( "value" ).addText( "member" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.memberAttributeValueTemplate" )
 +        .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.clusterName" )
 +        .addTag( "value" ).addText( "test-cluster" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.systemUsername" )
 +        .addTag( "value" ).addText( "uid=guest,ou=people,dc=hadoop,dc=apache,dc=org" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.systemPassword" )
 +        .addTag( "value" ).addText( "S{ALIAS=ldcSystemPassword}" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "urls./**" )
 +        .addTag( "value" ).addText( "authcBasic" )
 +
 +        .gotoParent().gotoParent().addTag( "provider" )
 +        .addTag( "role" ).addText( "authorization" )
 +        .addTag( "name" ).addText( "AclsAuthz" )
 +        .addTag( "enabled" ).addText( "true" )
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "test-service-role.acl" ) // FIXME[dilli]
 +        .addTag( "value" ).addText( "*;analyst;*" )
 +
 +        .gotoParent().gotoParent().addTag( "provider" )
 +        .addTag( "role" ).addText( "identity-assertion" )
 +        .addTag( "enabled" ).addText( "true" )
 +        .addTag( "name" ).addText( "Default" ).gotoParent()
 +
 +        .gotoRoot()
 +        .addTag( "service" )
 +        .addTag( "role" ).addText( "test-service-role" )
 +        .gotoRoot();
 +         // System.out.println( "GATEWAY=" + xml.toString() );
 +    return xml;
 +  }
 +
 +  public static InputStream getResourceStream( String resource ) throws IOException {
 +    return getResourceUrl( resource ).openStream();
 +  }
 +
 +  public static URL getResourceUrl( String resource ) {
 +    URL url = ClassLoader.getSystemResource( getResourceName( resource ) );
 +    assertThat( "Failed to find test resource " + resource, url, Matchers.notNullValue() );
 +    return url;
 +  }
 +
 +  public static String getResourceName( String resource ) {
 +    return getResourceBaseName() + resource;
 +  }
 +
 +  public static String getResourceBaseName() {
 +    return RESOURCE_BASE_CLASS.getName().replaceAll( "\\.", "/" ) + "/";
 +  }
 +
 +  @Ignore
 +  // @Test
 +  public void waitForManualTesting() throws IOException {
 +    System.in.read();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testGroupMember() throws ClassNotFoundException, Exception {
 +    LOG_ENTER();
 +    String username = "sam";
 +    String password = "sam-password";
 +    String serviceUrl = clusterUrl + "/test-service-path/test-service-resource";
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_OK )
 +        .contentType( "text/plain" )
 +        .body( is( "test-service-response" ) )
 +        .when().get( serviceUrl );
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testNonGroupMember() throws ClassNotFoundException {
 +    LOG_ENTER();
 +    String username = "guest";
 +    String password = "guest-password";
 +    String serviceUrl = clusterUrl + "/test-service-path/test-service-resource";
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_FORBIDDEN )
 +        .when().get( serviceUrl );
 +    LOG_EXIT();
 +  }
 +
 +}

http://git-wip-us.apache.org/repos/asf/knox/blob/912c5360/gateway-test/src/test/java/org/apache/knox/gateway/GatewayLdapPosixGroupFuncTest.java
----------------------------------------------------------------------
diff --cc gateway-test/src/test/java/org/apache/knox/gateway/GatewayLdapPosixGroupFuncTest.java
index 044c048,0000000..64d1ba7
mode 100644,000000..100644
--- a/gateway-test/src/test/java/org/apache/knox/gateway/GatewayLdapPosixGroupFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/knox/gateway/GatewayLdapPosixGroupFuncTest.java
@@@ -1,297 -1,0 +1,287 @@@
 +/**
 + * Licensed to the Apache Software Foundation (ASF) under one
 + * or more contributor license agreements.  See the NOTICE file
 + * distributed with this work for additional information
 + * regarding copyright ownership.  The ASF licenses this file
 + * to you under the Apache License, Version 2.0 (the
 + * "License"); you may not use this file except in compliance
 + * with the License.  You may obtain a copy of the License at
 + *
 + *     http://www.apache.org/licenses/LICENSE-2.0
 + *
 + * Unless required by applicable law or agreed to in writing, software
 + * distributed under the License is distributed on an "AS IS" BASIS,
 + * WITHOUT 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.knox.gateway;
 +
 +import com.mycila.xmltool.XMLDoc;
 +import com.mycila.xmltool.XMLTag;
 +import org.apache.directory.server.protocol.shared.transport.TcpTransport;
 +import org.apache.knox.gateway.config.GatewayConfig;
 +import org.apache.knox.gateway.security.ldap.SimpleLdapDirectoryServer;
 +import org.apache.knox.gateway.services.DefaultGatewayServices;
 +import org.apache.knox.gateway.services.GatewayServices;
 +import org.apache.knox.gateway.services.ServiceLifecycleException;
 +import org.apache.knox.gateway.services.security.AliasService;
 +import org.apache.hadoop.test.TestUtils;
 +import org.apache.hadoop.test.category.ReleaseTest;
 +import org.apache.http.HttpStatus;
 +import org.apache.log4j.Appender;
 +import org.hamcrest.MatcherAssert;
 +import org.hamcrest.Matchers;
 +import org.junit.AfterClass;
 +import org.junit.BeforeClass;
 +import org.junit.Ignore;
 +import org.junit.Test;
 +import org.junit.experimental.categories.Category;
 +import org.slf4j.Logger;
 +import org.slf4j.LoggerFactory;
 +
 +import java.io.File;
 +import java.io.FileOutputStream;
 +import java.io.IOException;
 +import java.io.InputStream;
 +import java.io.OutputStream;
 +import java.net.InetSocketAddress;
 +import java.net.URL;
 +import java.util.Enumeration;
 +import java.util.HashMap;
 +import java.util.Map;
 +import java.util.UUID;
 +
 +import static com.jayway.restassured.RestAssured.given;
 +import static org.apache.hadoop.test.TestUtils.LOG_ENTER;
 +import static org.apache.hadoop.test.TestUtils.LOG_EXIT;
 +import static org.hamcrest.CoreMatchers.is;
 +import static org.hamcrest.CoreMatchers.notNullValue;
 +import static org.junit.Assert.assertThat;
 +import static org.junit.Assert.fail;
 +
 +/**
-  * Functional test to verify : looking up ldap groups from directory 
++ * Functional test to verify : looking up ldap groups from directory
 + * and using them in acl authorization checks
 + *
 + */
 +@Category(ReleaseTest.class)
 +public class GatewayLdapPosixGroupFuncTest {
 +
 +  private static Class RESOURCE_BASE_CLASS = GatewayLdapPosixGroupFuncTest.class;
 +  private static Logger LOG = LoggerFactory.getLogger( GatewayLdapPosixGroupFuncTest.class );
 +
 +  public static Enumeration<Appender> appenders;
 +  public static GatewayConfig config;
 +  public static GatewayServer gateway;
 +  public static String gatewayUrl;
 +  public static String clusterUrl;
 +  public static String serviceUrl;
-   public static SimpleLdapDirectoryServer ldap;
-   public static TcpTransport ldapTransport;
++  private static GatewayTestDriver driver = new GatewayTestDriver();
 +
 +  @BeforeClass
 +  public static void setupSuite() throws Exception {
 +    LOG_ENTER();
 +    //appenders = NoOpAppender.setUp();
-     int port = setupLdap();
-     setupGateway(port);
-     TestUtils.awaitPortOpen( new InetSocketAddress( "localhost", port ), 10000, 100 );
++    URL usersUrl = getResourceUrl( "users.ldif" );
++    driver.setupLdap( 0, new File( usersUrl.toURI() ) );
++    setupGateway();
 +    TestUtils.awaitNon404HttpStatus( new URL( serviceUrl ), 10000, 100 );
 +    LOG_EXIT();
 +  }
 +
 +  @AfterClass
 +  public static void cleanupSuite() throws Exception {
 +    LOG_ENTER();
 +    gateway.stop();
-     ldap.stop( true );
++    driver.cleanup();
 +    //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
 +    //NoOpAppender.tearDown( appenders );
 +    LOG_EXIT();
 +  }
 +
-   public static int setupLdap() throws Exception {
-     URL usersUrl = getResourceUrl( "users.ldif" );
-     ldapTransport = new TcpTransport( 0 );
-     ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", new File( usersUrl.toURI() ), ldapTransport );
-     ldap.start();
-     LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-     return ldapTransport.getAcceptor().getLocalAddress().getPort();
-   }
- 
-   public static void setupGateway(int ldapPort) throws Exception {
++  public static void setupGateway() throws Exception {
 +
 +    File targetDir = new File( System.getProperty( "user.dir" ), "target" );
 +    File gatewayDir = new File( targetDir, "gateway-home-" + UUID.randomUUID() );
 +    gatewayDir.mkdirs();
 +
 +    GatewayTestConfig testConfig = new GatewayTestConfig();
 +    config = testConfig;
 +    testConfig.setGatewayHomeDir( gatewayDir.getAbsolutePath() );
 +
 +    File topoDir = new File( testConfig.getGatewayTopologyDir() );
 +    topoDir.mkdirs();
 +
 +    File deployDir = new File( testConfig.getGatewayDeploymentDir() );
 +    deployDir.mkdirs();
 +
 +    DefaultGatewayServices srvcs = new DefaultGatewayServices();
 +    Map<String,String> options = new HashMap<>();
 +    options.put( "persist-master", "true" );
 +    options.put( "master", "hadoop" );
 +
 +    try {
 +      srvcs.init( testConfig, options );
 +    } catch ( ServiceLifecycleException e ) {
 +      e.printStackTrace(); // I18N not required.
 +    }
 +
 +    gateway = GatewayServer.startGateway( testConfig, srvcs );
 +    MatcherAssert.assertThat( "Failed to start gateway.", gateway, notNullValue() );
 +
 +    LOG.info( "Gateway port = " + gateway.getAddresses()[ 0 ].getPort() );
 +
 +    gatewayUrl = "http://localhost:" + gateway.getAddresses()[0].getPort() + "/" + config.getGatewayPath();
 +    clusterUrl = gatewayUrl + "/test-cluster";
 +    serviceUrl = clusterUrl + "/test-service-path/test-service-resource";
 +
 +    GatewayServices services = GatewayServer.getGatewayServices();
 +    AliasService aliasService = (AliasService)services.getService(GatewayServices.ALIAS_SERVICE);
 +    aliasService.addAliasForCluster("test-cluster", "ldcSystemPassword", "guest-password");
 +
 +    char[] password1 = aliasService.getPasswordFromAliasForCluster( "test-cluster", "ldcSystemPassword");
 +
 +    File descriptor = new File( topoDir, "test-cluster.xml" );
 +    OutputStream stream = new FileOutputStream( descriptor );
-     createTopology(ldapPort).toStream( stream );
++    createTopology().toStream( stream );
 +    stream.close();
 +
 +  }
 +
-   private static XMLTag createTopology(int ldapPort) {
++  private static XMLTag createTopology() {
 +    XMLTag xml = XMLDoc.newDocument( true )
 +        .addRoot( "topology" )
 +        .addTag( "gateway" )
 +
 +        .addTag( "provider" )
 +        .addTag( "role" ).addText( "authentication" )
 +        .addTag( "name" ).addText( "ShiroProvider" )
 +        .addTag( "enabled" ).addText( "true" )
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm" )
-         .addTag( "value" ).addText( "KnoxLdapRealm" )
++        .addTag( "value" ).addText( "org.apache.knox.gateway.shirorealm.KnoxLdapRealm" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapGroupContextFactory" )
-         .addTag( "value" ).addText( "KnoxLdapContextFactory" )
++        .addTag( "value" ).addText( "org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory" )
 +        .addTag( "value" ).addText( "$ldapGroupContextFactory" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.authenticationMechanism" )
 +        .addTag( "value" ).addText( "simple" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
-         .addTag( "value" ).addText( "ldap://localhost:" + ldapPort )
++        .addTag( "value" ).addText( driver.getLdapUrl() )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.userDnTemplate" )
 +        .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.authorizationEnabled" )
 +        .addTag( "value" ).addText( "true" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.systemAuthenticationMechanism" )
 +        .addTag( "value" ).addText( "simple" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.searchBase" )
 +        .addTag( "value" ).addText( "ou=groups,dc=hadoop,dc=apache,dc=org" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.groupObjectClass" )
 +        .addTag( "value" ).addText( "posixGroup" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.memberAttribute" )
 +        .addTag( "value" ).addText( "memberUid" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.memberAttributeValueTemplate" )
 +        .addTag( "value" ).addText( "uid={0}" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.clusterName" )
 +        .addTag( "value" ).addText( "test-cluster" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.systemUsername" )
 +        .addTag( "value" ).addText( "uid=guest,ou=people,dc=hadoop,dc=apache,dc=org" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.systemPassword" )
 +        .addTag( "value" ).addText( "S{ALIAS=ldcSystemPassword}" )
 +        .gotoParent().addTag( "param" )
 +        .addTag( "name" ).addText( "urls./**" )
 +        .addTag( "value" ).addText( "authcBasic" )
 +
 +        .gotoParent().gotoParent().addTag( "provider" )
 +        .addTag( "role" ).addText( "authorization" )
 +        .addTag( "name" ).addText( "AclsAuthz" )
 +        .addTag( "enabled" ).addText( "true" )
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "test-service-role.acl" )
 +        .addTag( "value" ).addText( "*;analyst;*" )
 +
 +        .gotoParent().gotoParent().addTag( "provider" )
 +        .addTag( "role" ).addText( "identity-assertion" )
 +        .addTag( "enabled" ).addText( "true" )
 +        .addTag( "name" ).addText( "Default" ).gotoParent()
 +
 +        .gotoRoot()
 +        .addTag( "service" )
 +        .addTag( "role" ).addText( "test-service-role" )
 +        .gotoRoot();
 +
 +    return xml;
 +  }
 +
 +  public static InputStream getResourceStream( String resource ) throws IOException {
 +    return getResourceUrl( resource ).openStream();
 +  }
 +
 +  public static URL getResourceUrl( String resource ) {
 +    URL url = ClassLoader.getSystemResource( getResourceName( resource ) );
 +    assertThat( "Failed to find test resource " + resource, url, Matchers.notNullValue() );
 +    return url;
 +  }
 +
 +  public static String getResourceName( String resource ) {
 +    return getResourceBaseName() + resource;
 +  }
 +
 +  public static String getResourceBaseName() {
 +    return RESOURCE_BASE_CLASS.getName().replaceAll( "\\.", "/" ) + "/";
 +  }
 +
 +  @Ignore
 +  // @Test
 +  public void waitForManualTesting() throws IOException {
 +    System.in.read();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testGroupMember() throws ClassNotFoundException, Exception {
 +    LOG_ENTER();
 +    String username = "sam";
 +    String password = "sam-password";
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_OK )
 +        .contentType( "text/plain" )
 +        .body( is( "test-service-response" ) )
 +        .when().get( serviceUrl );
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testNonGroupMember() throws ClassNotFoundException {
 +    LOG_ENTER();
 +    String username = "guest";
 +    String password = "guest-password";
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_FORBIDDEN )
 +        .when().get( serviceUrl );
 +    LOG_EXIT();
 +  }
 +
 +}

http://git-wip-us.apache.org/repos/asf/knox/blob/912c5360/gateway-test/src/test/java/org/apache/knox/gateway/GatewayLocalServiceFuncTest.java
----------------------------------------------------------------------
diff --cc gateway-test/src/test/java/org/apache/knox/gateway/GatewayLocalServiceFuncTest.java
index d667a64,0000000..116793c
mode 100644,000000..100644
--- a/gateway-test/src/test/java/org/apache/knox/gateway/GatewayLocalServiceFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/knox/gateway/GatewayLocalServiceFuncTest.java
@@@ -1,224 -1,0 +1,208 @@@
 +/**
 + * Licensed to the Apache Software Foundation (ASF) under one
 + * or more contributor license agreements.  See the NOTICE file
 + * distributed with this work for additional information
 + * regarding copyright ownership.  The ASF licenses this file
 + * to you under the Apache License, Version 2.0 (the
 + * "License"); you may not use this file except in compliance
 + * with the License.  You may obtain a copy of the License at
 + *
 + *     http://www.apache.org/licenses/LICENSE-2.0
 + *
 + * Unless required by applicable law or agreed to in writing, software
 + * distributed under the License is distributed on an "AS IS" BASIS,
 + * WITHOUT 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.knox.gateway;
 +
 +import com.mycila.xmltool.XMLDoc;
 +import com.mycila.xmltool.XMLTag;
 +import org.apache.commons.io.FileUtils;
 +import org.apache.directory.server.protocol.shared.transport.TcpTransport;
 +import org.apache.knox.gateway.config.GatewayConfig;
 +import org.apache.knox.gateway.security.ldap.SimpleLdapDirectoryServer;
 +import org.apache.knox.gateway.services.DefaultGatewayServices;
 +import org.apache.knox.gateway.services.ServiceLifecycleException;
 +import org.apache.hadoop.test.TestUtils;
 +import org.apache.hadoop.test.log.NoOpAppender;
 +import org.apache.http.HttpStatus;
 +import org.apache.log4j.Appender;
 +import org.hamcrest.MatcherAssert;
 +import org.hamcrest.Matchers;
 +import org.junit.AfterClass;
 +import org.junit.BeforeClass;
 +import org.junit.Test;
 +import org.slf4j.Logger;
 +import org.slf4j.LoggerFactory;
 +
 +import java.io.File;
 +import java.io.FileOutputStream;
 +import java.io.IOException;
 +import java.io.InputStream;
 +import java.net.URL;
- import java.nio.file.FileSystems;
- import java.nio.file.Path;
 +import java.util.Enumeration;
 +import java.util.HashMap;
 +import java.util.Map;
 +import java.util.UUID;
 +
 +import static com.jayway.restassured.RestAssured.given;
 +import static org.apache.hadoop.test.TestUtils.LOG_ENTER;
 +import static org.apache.hadoop.test.TestUtils.LOG_EXIT;
 +import static org.hamcrest.CoreMatchers.is;
 +import static org.hamcrest.CoreMatchers.notNullValue;
 +import static org.junit.Assert.assertThat;
 +
 +public class GatewayLocalServiceFuncTest {
 +
 +  private static Class RESOURCE_BASE_CLASS = GatewayLocalServiceFuncTest.class;
 +  private static Logger LOG = LoggerFactory.getLogger( GatewayTestDriver.class );
 +
 +  public static Enumeration<Appender> appenders;
 +  public static GatewayConfig config;
 +  public static GatewayServer gateway;
 +  public static String gatewayUrl;
 +  public static String clusterUrl;
-   public static SimpleLdapDirectoryServer ldap;
-   public static TcpTransport ldapTransport;
++  private static GatewayTestDriver driver = new GatewayTestDriver();
 +
 +  @BeforeClass
 +  public static void setupSuite() throws Exception {
 +    LOG_ENTER();
 +    appenders = NoOpAppender.setUp();
-     setupLdap();
++    driver.setupLdap(0);
 +    setupGateway();
 +    LOG_EXIT();
 +  }
 +
 +  @AfterClass
 +  public static void cleanupSuite() throws Exception {
 +    LOG_ENTER();
 +    gateway.stop();
-     ldap.stop( true );
++    driver.cleanup();
 +    FileUtils.deleteQuietly( new File( config.getGatewayConfDir() ) );
 +    FileUtils.deleteQuietly( new File( config.getGatewayDataDir() ) );
 +    NoOpAppender.tearDown( appenders );
 +    LOG_EXIT();
 +  }
 +
-   public static void setupLdap() throws Exception {
-     String basedir = System.getProperty("basedir");
-     if (basedir == null) {
-       basedir = new File(".").getCanonicalPath();
-     }
-     Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
- 
-     ldapTransport = new TcpTransport( 0 );
-     ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-     ldap.start();
-     LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-   }
- 
 +  public static void setupGateway() throws Exception {
 +
 +    File targetDir = new File( System.getProperty( "user.dir" ), "target" );
 +    File gatewayDir = new File( targetDir, "gateway-home-" + UUID.randomUUID() );
 +    gatewayDir.mkdirs();
 +
 +    GatewayTestConfig testConfig = new GatewayTestConfig();
 +    config = testConfig;
 +    testConfig.setGatewayHomeDir( gatewayDir.getAbsolutePath() );
 +
 +    File topoDir = new File( testConfig.getGatewayTopologyDir() );
 +    topoDir.mkdirs();
 +
 +    File deployDir = new File( testConfig.getGatewayDeploymentDir() );
 +    deployDir.mkdirs();
 +
 +    File descriptor = new File( topoDir, "cluster.xml" );
 +    FileOutputStream stream = new FileOutputStream( descriptor );
 +    createTopology().toStream( stream );
 +    stream.close();
 +
 +    DefaultGatewayServices srvcs = new DefaultGatewayServices();
 +    Map<String,String> options = new HashMap<>();
 +    options.put( "persist-master", "false" );
 +    options.put( "master", "password" );
 +    try {
 +      srvcs.init( testConfig, options );
 +    } catch ( ServiceLifecycleException e ) {
 +      e.printStackTrace(); // I18N not required.
 +    }
 +    gateway = GatewayServer.startGateway( testConfig, srvcs );
 +    MatcherAssert.assertThat( "Failed to start gateway.", gateway, notNullValue() );
 +
 +    LOG.info( "Gateway port = " + gateway.getAddresses()[ 0 ].getPort() );
 +
 +    gatewayUrl = "http://localhost:" + gateway.getAddresses()[0].getPort() + "/" + config.getGatewayPath();
 +    clusterUrl = gatewayUrl + "/cluster";
 +  }
 +
 +  private static XMLTag createTopology() {
 +    XMLTag xml = XMLDoc.newDocument( true )
 +        .addRoot( "topology" )
 +        .addTag( "gateway" )
 +        .addTag( "provider" )
 +        .addTag( "role" ).addText( "authentication" )
 +        .addTag( "name" ).addText( "ShiroProvider" )
 +        .addTag( "enabled" ).addText( "true" )
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm" )
-         .addTag( "value" ).addText( "KnoxLdapRealm" ).gotoParent()
++        .addTag( "value" ).addText( "org.apache.knox.gateway.shirorealm.KnoxLdapRealm" ).gotoParent()
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.userDnTemplate" )
 +        .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" ).gotoParent()
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
-         .addTag( "value" ).addText( "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() ).gotoParent()
++        .addTag( "value" ).addText( driver.getLdapUrl() ).gotoParent()
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "main.ldapRealm.contextFactory.authenticationMechanism" )
 +        .addTag( "value" ).addText( "simple" ).gotoParent()
 +        .addTag( "param" )
 +        .addTag( "name" ).addText( "urls./**" )
 +        .addTag( "value" ).addText( "authcBasic" ).gotoParent().gotoParent()
 +        .addTag( "provider" )
 +        .addTag( "role" ).addText( "identity-assertion" )
 +        .addTag( "enabled" ).addText( "true" )
 +        .addTag( "name" ).addText( "Default" ).gotoParent()
 +        .addTag( "provider" )
 +        .gotoRoot()
 +        .addTag( "service" )
 +        .addTag( "role" ).addText( "test-jersey-service-role" )
 +        .gotoRoot();
 +    // System.out.println( "GATEWAY=" + xml.toString() );
 +    return xml;
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testJerseyService() throws ClassNotFoundException {
 +    LOG_ENTER();
 +    assertThat( ClassLoader.getSystemClassLoader().loadClass( "org.glassfish.jersey.servlet.ServletContainer" ), notNullValue() );
 +    assertThat( ClassLoader.getSystemClassLoader().loadClass(
 +        "org.apache.knox.gateway.jersey.JerseyDispatchDeploymentContributor"), notNullValue() );
 +    assertThat( ClassLoader.getSystemClassLoader().loadClass(
 +        "org.apache.knox.gateway.jersey.JerseyServiceDeploymentContributorBase"), notNullValue() );
 +    assertThat( ClassLoader.getSystemClassLoader().loadClass(
 +        "org.apache.knox.gateway.TestJerseyService"), notNullValue() );
 +
 +    String username = "guest";
 +    String password = "guest-password";
 +    String serviceUrl = clusterUrl + "/test-jersey-service/test-jersey-resource-path";
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_OK )
 +        .contentType( "text/plain" )
 +        .body( is( "test-jersey-resource-response" ) )
 +        .when().get( serviceUrl );
 +    LOG_EXIT();
 +  }
 +
 +  public static InputStream getResourceStream( String resource ) throws IOException {
 +    return getResourceUrl( resource ).openStream();
 +  }
 +
 +  public static URL getResourceUrl( String resource ) {
 +    URL url = ClassLoader.getSystemResource( getResourceName( resource ) );
 +    assertThat( "Failed to find test resource " + resource, url, Matchers.notNullValue() );
 +    return url;
 +  }
 +
 +  public static String getResourceName( String resource ) {
 +    return getResourceBaseName() + resource;
 +  }
 +
 +  public static String getResourceBaseName() {
 +    return RESOURCE_BASE_CLASS.getName().replaceAll( "\\.", "/" ) + "/";
 +  }
 +
 +}

http://git-wip-us.apache.org/repos/asf/knox/blob/912c5360/gateway-test/src/test/java/org/apache/knox/gateway/GatewayMultiFuncTest.java
----------------------------------------------------------------------
diff --cc gateway-test/src/test/java/org/apache/knox/gateway/GatewayMultiFuncTest.java
index 656acf3,0000000..1b01d73
mode 100644,000000..100644
--- a/gateway-test/src/test/java/org/apache/knox/gateway/GatewayMultiFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/knox/gateway/GatewayMultiFuncTest.java
@@@ -1,459 -1,0 +1,444 @@@
 +/**
 + * Licensed to the Apache Software Foundation (ASF) under one
 + * or more contributor license agreements.  See the NOTICE file
 + * distributed with this work for additional information
 + * regarding copyright ownership.  The ASF licenses this file
 + * to you under the Apache License, Version 2.0 (the
 + * "License"); you may not use this file except in compliance
 + * with the License.  You may obtain a copy of the License at
 + *
 + *     http://www.apache.org/licenses/LICENSE-2.0
 + *
 + * Unless required by applicable law or agreed to in writing, software
 + * distributed under the License is distributed on an "AS IS" BASIS,
 + * WITHOUT 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.knox.gateway;
 +
 +import java.io.File;
 +import java.net.URL;
 +import java.nio.charset.Charset;
- import java.nio.file.FileSystems;
- import java.nio.file.Path;
 +import java.util.Enumeration;
 +import java.util.HashMap;
 +import java.util.Map;
 +import java.util.Properties;
 +import java.util.UUID;
 +
 +import org.apache.commons.io.FileUtils;
 +import org.apache.commons.io.IOUtils;
 +import org.apache.directory.server.protocol.shared.transport.TcpTransport;
 +import org.apache.knox.gateway.security.ldap.SimpleLdapDirectoryServer;
 +import org.apache.knox.gateway.services.DefaultGatewayServices;
 +import org.apache.knox.gateway.services.GatewayServices;
 +import org.apache.knox.gateway.services.ServiceLifecycleException;
 +import org.apache.knox.gateway.services.topology.TopologyService;
 +import org.apache.hadoop.test.TestUtils;
 +import org.apache.hadoop.test.category.ReleaseTest;
 +import org.apache.hadoop.test.mock.MockServer;
 +import org.apache.http.HttpHost;
 +import org.apache.http.HttpStatus;
 +import org.apache.http.auth.AuthScope;
 +import org.apache.http.auth.UsernamePasswordCredentials;
 +import org.apache.http.client.AuthCache;
 +import org.apache.http.client.CredentialsProvider;
 +import org.apache.http.client.methods.CloseableHttpResponse;
 +import org.apache.http.client.methods.HttpPut;
 +import org.apache.http.client.protocol.HttpClientContext;
 +import org.apache.http.impl.auth.BasicScheme;
 +import org.apache.http.impl.client.BasicAuthCache;
 +import org.apache.http.impl.client.BasicCredentialsProvider;
 +import org.apache.http.impl.client.CloseableHttpClient;
 +import org.apache.http.impl.client.HttpClients;
 +import org.apache.log4j.Appender;
 +import org.hamcrest.MatcherAssert;
 +import org.junit.AfterClass;
 +import org.junit.BeforeClass;
 +import org.junit.Test;
 +import org.junit.experimental.categories.Category;
 +import org.slf4j.Logger;
 +import org.slf4j.LoggerFactory;
 +
 +import static com.jayway.restassured.RestAssured.given;
 +import static org.apache.hadoop.test.TestUtils.LOG_ENTER;
 +import static org.apache.hadoop.test.TestUtils.LOG_EXIT;
 +import static org.hamcrest.CoreMatchers.endsWith;
 +import static org.hamcrest.CoreMatchers.equalTo;
 +import static org.hamcrest.CoreMatchers.not;
 +import static org.hamcrest.CoreMatchers.notNullValue;
 +import static org.hamcrest.core.Is.is;
 +import static org.junit.Assert.assertThat;
 +import static org.xmlmatchers.XmlMatchers.hasXPath;
 +import static org.xmlmatchers.transform.XmlConverters.the;
 +
 +@Category(ReleaseTest.class)
 +public class GatewayMultiFuncTest {
 +
 +  private static Logger LOG = LoggerFactory.getLogger( GatewayMultiFuncTest.class );
 +  private static Class DAT = GatewayMultiFuncTest.class;
 +
 +  private static Enumeration<Appender> appenders;
 +  private static GatewayTestConfig config;
 +  private static DefaultGatewayServices services;
 +  private static GatewayServer gateway;
 +  private static int gatewayPort;
 +  private static String gatewayUrl;
-   private static SimpleLdapDirectoryServer ldap;
 +  private static TcpTransport ldapTransport;
 +  private static Properties params;
 +  private static TopologyService topos;
++  private static GatewayTestDriver driver = new GatewayTestDriver();
 +
 +  @BeforeClass
 +  public static void setupSuite() throws Exception {
 +    LOG_ENTER();
 +    //appenders = NoOpAppender.setUp();
-     setupLdap();
++    driver.setupLdap(0);
 +    setupGateway();
 +    LOG_EXIT();
 +  }
 +
 +  @AfterClass
 +  public static void cleanupSuite() throws Exception {
 +    LOG_ENTER();
 +    gateway.stop();
-     ldap.stop( true );
++    driver.cleanup();
 +    FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
 +    //NoOpAppender.tearDown( appenders );
 +    LOG_EXIT();
 +  }
 +
-   public static void setupLdap() throws Exception {
-     String basedir = System.getProperty("basedir");
-     if (basedir == null) {
-       basedir = new File(".").getCanonicalPath();
-     }
-     Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
- 
-     ldapTransport = new TcpTransport( 0 );
-     ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-     ldap.start();
-     LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-   }
- 
 +  public static void setupGateway() throws Exception {
 +
 +    File targetDir = new File( System.getProperty( "user.dir" ), "target" );
 +    File gatewayDir = new File( targetDir, "gateway-home-" + UUID.randomUUID() );
 +    gatewayDir.mkdirs();
 +
 +    config = new GatewayTestConfig();
 +    config.setGatewayHomeDir( gatewayDir.getAbsolutePath() );
 +
 +    URL svcsFileUrl = TestUtils.getResourceUrl( DAT, "services/readme.txt" );
 +    File svcsFile = new File( svcsFileUrl.getFile() );
 +    File svcsDir = svcsFile.getParentFile();
 +    config.setGatewayServicesDir( svcsDir.getAbsolutePath() );
 +
 +    URL appsFileUrl = TestUtils.getResourceUrl( DAT, "applications/readme.txt" );
 +    File appsFile = new File( appsFileUrl.getFile() );
 +    File appsDir = appsFile.getParentFile();
 +    config.setGatewayApplicationsDir( appsDir.getAbsolutePath() );
 +
 +    File topoDir = new File( config.getGatewayTopologyDir() );
 +    topoDir.mkdirs();
 +
 +    File deployDir = new File( config.getGatewayDeploymentDir() );
 +    deployDir.mkdirs();
 +
 +    startGatewayServer();
 +  }
 +
 +  public static void startGatewayServer() throws Exception {
 +    services = new DefaultGatewayServices();
 +    Map<String,String> options = new HashMap<>();
 +    options.put( "persist-master", "false" );
 +    options.put( "master", "password" );
 +    try {
 +      services.init( config, options );
 +    } catch ( ServiceLifecycleException e ) {
 +      e.printStackTrace(); // I18N not required.
 +    }
 +    topos = services.getService(GatewayServices.TOPOLOGY_SERVICE);
 +
 +    gateway = GatewayServer.startGateway( config, services );
 +    MatcherAssert.assertThat( "Failed to start gateway.", gateway, notNullValue() );
 +
 +    gatewayPort = gateway.getAddresses()[0].getPort();
 +    gatewayUrl = "http://localhost:" + gatewayPort + "/" + config.getGatewayPath();
 +
 +    LOG.info( "Gateway port = " + gateway.getAddresses()[ 0 ].getPort() );
 +
 +    params = new Properties();
-     params.put( "LDAP_URL", "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() );
++    params.put( "LDAP_URL", driver.getLdapUrl() );
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testDefaultJsonMimeTypeHandlingKnox678() throws Exception {
 +    LOG_ENTER();
 +
 +    MockServer mock = new MockServer( "REPEAT", true );
 +
 +    params = new Properties();
-     params.put( "LDAP_URL", "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() );
++    params.put( "LDAP_URL", driver.getLdapUrl() );
 +    params.put( "MOCK_SERVER_PORT", mock.getPort() );
 +
 +    String topoStr = TestUtils.merge( DAT, "topologies/test-knox678-utf8-chars-topology.xml", params );
 +    File topoFile = new File( config.getGatewayTopologyDir(), "knox678.xml" );
 +    FileUtils.writeStringToFile( topoFile, topoStr );
 +
 +    topos.reloadTopologies();
 +
 +    String uname = "guest";
 +    String pword = uname + "-password";
 +
 +    mock.expect().method( "GET" )
 +        .respond().contentType( "application/json" ).contentLength( -1 ).content( "{\"msg\":\"H\u00eallo\"}", Charset.forName( "UTF-8" ) );
 +    String json = given()
 +        //.log().all()
 +        .auth().preemptive().basic( uname, pword )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_OK )
 +        .contentType( "application/json; charset=UTF-8" )
 +        .when().log().ifError().get( gatewayUrl + "/knox678/repeat" ).andReturn().asString();
 +    assertThat( json, is("{\"msg\":\"H\u00eallo\"}") );
 +    assertThat( mock.isEmpty(), is(true) );
 +
 +    mock.expect().method( "GET" )
 +        .respond().contentType( "application/octet-stream" ).contentLength( -1 ).content( "H\u00eallo".getBytes() );
 +    byte[] bytes = given()
 +        //.log().all()
 +        .auth().preemptive().basic( uname, pword )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_OK )
 +        .contentType( "application/octet-stream" )
 +        .when().log().ifError().get( gatewayUrl + "/knox678/repeat" ).andReturn().asByteArray();
 +    assertThat( bytes, is(equalTo("H\u00eallo".getBytes())) );
 +    assertThat( mock.isEmpty(), is(true) );
 +
 +    mock.stop();
 +
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testPostWithContentTypeKnox681() throws Exception {
 +    LOG_ENTER();
 +
 +    MockServer mock = new MockServer( "REPEAT", true );
 +
 +    params = new Properties();
 +    params.put( "MOCK_SERVER_PORT", mock.getPort() );
-     params.put( "LDAP_URL", "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() );
++    params.put( "LDAP_URL", driver.getLdapUrl() );
 +
 +    String topoStr = TestUtils.merge( DAT, "topologies/test-knox678-utf8-chars-topology.xml", params );
 +    File topoFile = new File( config.getGatewayTopologyDir(), "knox681.xml" );
 +    FileUtils.writeStringToFile( topoFile, topoStr );
 +
 +    topos.reloadTopologies();
 +
 +    mock
 +        .expect()
 +        .method( "PUT" )
 +        .pathInfo( "/repeat-context/" )
 +        .respond()
 +        .status( HttpStatus.SC_CREATED )
 +        .content( "{\"name\":\"value\"}".getBytes() )
 +        .contentLength( -1 )
 +        .contentType( "application/json; charset=UTF-8" )
 +        .header( "Location", gatewayUrl + "/knox681/repeat" );
 +
 +    String uname = "guest";
 +    String pword = uname + "-password";
 +
 +    HttpHost targetHost = new HttpHost( "localhost", gatewayPort, "http" );
 +    CredentialsProvider credsProvider = new BasicCredentialsProvider();
 +    credsProvider.setCredentials(
 +        new AuthScope( targetHost.getHostName(), targetHost.getPort() ),
 +        new UsernamePasswordCredentials( uname, pword ) );
 +
 +    AuthCache authCache = new BasicAuthCache();
 +    BasicScheme basicAuth = new BasicScheme();
 +    authCache.put( targetHost, basicAuth );
 +
 +    HttpClientContext context = HttpClientContext.create();
 +    context.setCredentialsProvider( credsProvider );
 +    context.setAuthCache( authCache );
 +
 +    CloseableHttpClient client = HttpClients.createDefault();
 +    HttpPut request = new HttpPut( gatewayUrl + "/knox681/repeat" );
 +    request.addHeader( "X-XSRF-Header", "jksdhfkhdsf" );
 +    request.addHeader( "Content-Type", "application/json" );
 +    CloseableHttpResponse response = client.execute( request, context );
 +    assertThat( response.getStatusLine().getStatusCode(), is( HttpStatus.SC_CREATED ) );
 +    assertThat( response.getFirstHeader( "Location" ).getValue(), endsWith("/gateway/knox681/repeat" ) );
 +    assertThat( response.getFirstHeader( "Content-Type" ).getValue(), is("application/json; charset=UTF-8") );
 +    String body = new String( IOUtils.toByteArray( response.getEntity().getContent() ), Charset.forName( "UTF-8" ) );
 +    assertThat( body, is( "{\"name\":\"value\"}" ) );
 +    response.close();
 +    client.close();
 +
 +    mock
 +        .expect()
 +        .method( "PUT" )
 +        .pathInfo( "/repeat-context/" )
 +        .respond()
 +        .status( HttpStatus.SC_CREATED )
 +        .content( "<test-xml/>".getBytes() )
 +        .contentType( "application/xml; charset=UTF-8" )
 +        .header( "Location", gatewayUrl + "/knox681/repeat" );
 +
 +    client = HttpClients.createDefault();
 +    request = new HttpPut( gatewayUrl + "/knox681/repeat" );
 +    request.addHeader( "X-XSRF-Header", "jksdhfkhdsf" );
 +    request.addHeader( "Content-Type", "application/xml" );
 +    response = client.execute( request, context );
 +    assertThat( response.getStatusLine().getStatusCode(), is( HttpStatus.SC_CREATED ) );
 +    assertThat( response.getFirstHeader( "Location" ).getValue(), endsWith("/gateway/knox681/repeat" ) );
 +    assertThat( response.getFirstHeader( "Content-Type" ).getValue(), is("application/xml; charset=UTF-8") );
 +    body = new String( IOUtils.toByteArray( response.getEntity().getContent() ), Charset.forName( "UTF-8" ) );
 +    assertThat( the(body), hasXPath( "/test-xml" ) );
 +    response.close();
 +    client.close();
 +
 +    mock.stop();
 +
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testLdapSearchConfigEnhancementsKnox694() throws Exception {
 +    LOG_ENTER();
 +
 +    String topoStr;
 +    File topoFile;
 +
 +    String adminUName = "uid=admin,ou=people,dc=hadoop,dc=apache,dc=org";
 +    String adminPWord = "admin-password";
 +    String uname = "people\\guest";
 +    String pword = "guest-password";
 +    String invalidPword = "invalid-guest-password";
 +
 +    params = new Properties();
-     params.put( "LDAP_URL", "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() );
++    params.put( "LDAP_URL", driver.getLdapUrl() );
 +    params.put( "LDAP_SYSTEM_USERNAME", adminUName );
 +    params.put( "LDAP_SYSTEM_PASSWORD", adminPWord );
 +
 +    topoStr = TestUtils.merge( DAT, "topologies/test-knox694-principal-regex-user-dn-template.xml", params );
 +    topoFile = new File( config.getGatewayTopologyDir(), "knox694-1.xml" );
 +    FileUtils.writeStringToFile( topoFile, topoStr );
 +    topos.reloadTopologies();
 +
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( uname, pword )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_OK )
 +        .contentType( "text/plain" )
 +        .body( is( "test-service-response" ) )
 +        .when().log().ifError().get( gatewayUrl + "/knox694-1/test-service-path/test-resource-path" );
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( uname, invalidPword )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_UNAUTHORIZED )
 +        .when().get( gatewayUrl + "/knox694-1/test-service-path/test-resource-path" );
 +
 +    topoStr = TestUtils.merge( DAT, "topologies/test-knox694-principal-regex-search-attribute.xml", params );
 +    topoFile = new File( config.getGatewayTopologyDir(), "knox694-2.xml" );
 +    FileUtils.writeStringToFile( topoFile, topoStr );
 +    topos.reloadTopologies();
 +
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( uname, pword )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_OK )
 +        .contentType( "text/plain" )
 +        .body( is( "test-service-response" ) )
 +        .when().log().ifError().get( gatewayUrl + "/knox694-2/test-service-path/test-resource-path" );
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( uname, invalidPword )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_UNAUTHORIZED )
 +        .when().get( gatewayUrl + "/knox694-2/test-service-path/test-resource-path" );
 +
 +    topoStr = TestUtils.merge( DAT, "topologies/test-knox694-principal-regex-search-filter.xml", params );
 +    topoFile = new File( config.getGatewayTopologyDir(), "knox694-3.xml" );
 +    FileUtils.writeStringToFile( topoFile, topoStr );
 +    topos.reloadTopologies();
 +
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( uname, pword )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_OK )
 +        .contentType( "text/plain" )
 +        .body( is( "test-service-response" ) )
 +        .when().log().ifError().get( gatewayUrl + "/knox694-3/test-service-path/test-resource-path" );
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( uname, invalidPword )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_UNAUTHORIZED )
 +        .when().get( gatewayUrl + "/knox694-3/test-service-path/test-resource-path" );
 +
 +    topoStr = TestUtils.merge( DAT, "topologies/test-knox694-principal-regex-search-scope-object.xml", params );
 +    topoFile = new File( config.getGatewayTopologyDir(), "knox694-4.xml" );
 +    FileUtils.writeStringToFile( topoFile, topoStr );
 +    topos.reloadTopologies();
 +
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( uname, pword )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_OK )
 +        .contentType( "text/plain" )
 +        .body( is( "test-service-response" ) )
 +        .when().log().ifError().get( gatewayUrl + "/knox694-4/test-service-path/test-resource-path" );
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( uname, invalidPword )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_UNAUTHORIZED )
 +        .when().get( gatewayUrl + "/knox694-4/test-service-path/test-resource-path" );
 +
 +    topoStr = TestUtils.merge( DAT, "topologies/test-knox694-principal-regex-search-scope-onelevel-positive.xml", params );
 +    topoFile = new File( config.getGatewayTopologyDir(), "knox694-5.xml" );
 +    FileUtils.writeStringToFile( topoFile, topoStr );
 +    topos.reloadTopologies();
 +
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( uname, pword )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_OK )
 +        .contentType( "text/plain" )
 +        .body( is( "test-service-response" ) )
 +        .when().log().ifError().get( gatewayUrl + "/knox694-5/test-service-path/test-resource-path" );
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( uname, invalidPword )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_UNAUTHORIZED )
 +        .when().get( gatewayUrl + "/knox694-5/test-service-path/test-resource-path" );
 +
 +    topoStr = TestUtils.merge( DAT, "topologies/test-knox694-principal-regex-search-scope-onelevel-negative.xml", params );
 +    topoFile = new File( config.getGatewayTopologyDir(), "knox694-6.xml" );
 +    FileUtils.writeStringToFile( topoFile, topoStr );
 +    topos.reloadTopologies();
 +
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( uname, pword )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_UNAUTHORIZED )
 +        .when().get( gatewayUrl + "/knox694-6/test-service-path/test-resource-path" );
 +
 +    LOG_EXIT();
 +  }
 +
 +}
 +
 +


[09/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/filter/Pac4jDispatcherFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/filter/Pac4jDispatcherFilter.java b/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/filter/Pac4jDispatcherFilter.java
new file mode 100644
index 0000000..a87c8d0
--- /dev/null
+++ b/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/filter/Pac4jDispatcherFilter.java
@@ -0,0 +1,215 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.pac4j.filter;
+
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.pac4j.Pac4jMessages;
+import org.apache.knox.gateway.pac4j.session.KnoxSessionStore;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.KeystoreService;
+import org.apache.knox.gateway.services.security.MasterService;
+import org.apache.knox.gateway.services.security.AliasService;
+import org.apache.knox.gateway.services.security.AliasServiceException;
+import org.apache.knox.gateway.services.security.CryptoService;
+import org.pac4j.config.client.PropertiesConfigFactory;
+import org.pac4j.core.client.Client;
+import org.pac4j.core.config.Config;
+import org.pac4j.core.config.ConfigSingleton;
+import org.pac4j.core.context.J2EContext;
+import org.pac4j.core.context.Pac4jConstants;
+import org.pac4j.core.util.CommonHelper;
+import org.pac4j.http.client.indirect.IndirectBasicAuthClient;
+import org.pac4j.http.credentials.authenticator.test.SimpleTestUsernamePasswordAuthenticator;
+import org.pac4j.j2e.filter.CallbackFilter;
+import org.pac4j.j2e.filter.RequiresAuthenticationFilter;
+
+import javax.servlet.*;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * <p>This is the main filter for the pac4j provider. The pac4j provider module heavily relies on the j2e-pac4j library (https://github.com/pac4j/j2e-pac4j).</p>
+ * <p>This filter dispatches the HTTP calls between the j2e-pac4j filters:</p>
+ * <ul>
+ *     <li>to the {@link CallbackFilter} if the <code>client_name</code> parameter exists: it finishes the authentication process</li>
+ *     <li>to the {@link RequiresAuthenticationFilter} otherwise: it starts the authentication process (redirection to the identity provider) if the user is not authenticated</li>
+ * </ul>
+ * <p>It uses the {@link KnoxSessionStore} to manage session data. The generated cookies are defined on a domain name
+ * which can be configured via the domain suffix parameter: <code>pac4j.cookie.domain.suffix</code>.</p>
+ * <p>The callback url must be defined to the current protected url (KnoxSSO service for example) via the parameter: <code>pac4j.callbackUrl</code>.</p>
+ *
+ * @since 0.8.0
+ */
+public class Pac4jDispatcherFilter implements Filter {
+
+  private static Pac4jMessages log = MessagesFactory.get(Pac4jMessages.class);
+
+  public static final String TEST_BASIC_AUTH = "testBasicAuth";
+
+  public static final String PAC4J_CALLBACK_URL = "pac4j.callbackUrl";
+
+  public static final String PAC4J_CALLBACK_PARAMETER = "pac4jCallback";
+
+  private static final String PAC4J_COOKIE_DOMAIN_SUFFIX_PARAM = "pac4j.cookie.domain.suffix";
+
+  private CallbackFilter callbackFilter;
+
+  private RequiresAuthenticationFilter requiresAuthenticationFilter;
+  private MasterService masterService = null;
+  private KeystoreService keystoreService = null;
+  private AliasService aliasService = null;
+
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+    // JWT service
+    final ServletContext context = filterConfig.getServletContext();
+    CryptoService cryptoService = null;
+    String clusterName = null;
+    if (context != null) {
+      GatewayServices services = (GatewayServices) context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
+      clusterName = (String) context.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE);
+      if (services != null) {
+        keystoreService = (KeystoreService) services.getService(GatewayServices.KEYSTORE_SERVICE);
+        cryptoService = (CryptoService) services.getService(GatewayServices.CRYPTO_SERVICE);
+        aliasService = (AliasService) services.getService(GatewayServices.ALIAS_SERVICE);
+        masterService = (MasterService) services.getService("MasterService");
+      }
+    }
+    // crypto service, alias service and cluster name are mandatory
+    if (cryptoService == null || aliasService == null || clusterName == null) {
+      log.cryptoServiceAndAliasServiceAndClusterNameRequired();
+      throw new ServletException("The crypto service, alias service and cluster name are required.");
+    }
+    try {
+      aliasService.getPasswordFromAliasForCluster(clusterName, KnoxSessionStore.PAC4J_PASSWORD, true);
+    } catch (AliasServiceException e) {
+      log.unableToGenerateAPasswordForEncryption(e);
+      throw new ServletException("Unable to generate a password for encryption.");
+    }
+
+    // url to SSO authentication provider
+    String pac4jCallbackUrl = filterConfig.getInitParameter(PAC4J_CALLBACK_URL);
+    if (pac4jCallbackUrl == null) {
+      log.ssoAuthenticationProviderUrlRequired();
+      throw new ServletException("Required pac4j callback URL is missing.");
+    }
+    // add the callback parameter to know it's a callback
+    pac4jCallbackUrl = CommonHelper.addParameter(pac4jCallbackUrl, PAC4J_CALLBACK_PARAMETER, "true");
+
+    final Config config;
+    final String clientName;
+    // client name from servlet parameter (mandatory)
+    final String clientNameParameter = filterConfig.getInitParameter(Pac4jConstants.CLIENT_NAME);
+    if (clientNameParameter == null) {
+      log.clientNameParameterRequired();
+      throw new ServletException("Required pac4j clientName parameter is missing.");
+    }
+    if (TEST_BASIC_AUTH.equalsIgnoreCase(clientNameParameter)) {
+      // test configuration
+      final IndirectBasicAuthClient indirectBasicAuthClient = new IndirectBasicAuthClient(new SimpleTestUsernamePasswordAuthenticator());
+      indirectBasicAuthClient.setRealmName("Knox TEST");
+      config = new Config(pac4jCallbackUrl, indirectBasicAuthClient);
+      clientName = "IndirectBasicAuthClient";
+    } else {
+      // get clients from the init parameters
+      final Map<String, String> properties = new HashMap<>();
+      final Enumeration<String> names = filterConfig.getInitParameterNames();
+      addDefaultConfig(clientNameParameter, properties);
+      while (names.hasMoreElements()) {
+        final String key = names.nextElement();
+        properties.put(key, filterConfig.getInitParameter(key));
+      }
+      final PropertiesConfigFactory propertiesConfigFactory = new PropertiesConfigFactory(pac4jCallbackUrl, properties);
+      config = propertiesConfigFactory.build();
+      final List<Client> clients = config.getClients().getClients();
+      if (clients == null || clients.size() == 0) {
+        log.atLeastOnePac4jClientMustBeDefined();
+        throw new ServletException("At least one pac4j client must be defined.");
+      }
+      if (CommonHelper.isBlank(clientNameParameter)) {
+        clientName = clients.get(0).getName();
+      } else {
+        clientName = clientNameParameter;
+      }
+    }
+
+    callbackFilter = new CallbackFilter();
+    requiresAuthenticationFilter = new RequiresAuthenticationFilter();
+    requiresAuthenticationFilter.setClientName(clientName);
+    requiresAuthenticationFilter.setConfig(config);
+
+    final String domainSuffix = filterConfig.getInitParameter(PAC4J_COOKIE_DOMAIN_SUFFIX_PARAM);
+    config.setSessionStore(new KnoxSessionStore(cryptoService, clusterName, domainSuffix));
+    ConfigSingleton.setConfig(config);
+  }
+
+  private void addDefaultConfig(String clientNameParameter, Map<String, String> properties) {
+    // add default saml params
+    if (clientNameParameter.contains("SAML2Client")) {
+      properties.put(PropertiesConfigFactory.SAML_KEYSTORE_PATH,
+          keystoreService.getKeystorePath());
+
+      properties.put(PropertiesConfigFactory.SAML_KEYSTORE_PASSWORD,
+          new String(masterService.getMasterSecret()));
+
+      // check for provisioned alias for private key
+      char[] gip = null;
+      try {
+        gip = aliasService.getGatewayIdentityPassphrase();
+      }
+      catch(AliasServiceException ase) {
+        log.noPrivateKeyPasshraseProvisioned(ase);
+      }
+      if (gip != null) {
+        properties.put(PropertiesConfigFactory.SAML_PRIVATE_KEY_PASSWORD,
+            new String(gip));
+      }
+      else {
+        // no alias provisioned then use the master
+        properties.put(PropertiesConfigFactory.SAML_PRIVATE_KEY_PASSWORD,
+            new String(masterService.getMasterSecret()));
+      }
+    }
+  }
+
+  @Override
+  public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
+
+    final HttpServletRequest request = (HttpServletRequest) servletRequest;
+    final HttpServletResponse response = (HttpServletResponse) servletResponse;
+    final J2EContext context = new J2EContext(request, response, ConfigSingleton.getConfig().getSessionStore());
+
+    // it's a callback from an identity provider
+    if (request.getParameter(PAC4J_CALLBACK_PARAMETER) != null) {
+      // apply CallbackFilter
+      callbackFilter.doFilter(servletRequest, servletResponse, filterChain);
+    } else {
+      // otherwise just apply security and requires authentication
+      // apply RequiresAuthenticationFilter
+      requiresAuthenticationFilter.doFilter(servletRequest, servletResponse, filterChain);
+    }
+  }
+
+  @Override
+  public void destroy() { }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/filter/Pac4jIdentityAdapter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/filter/Pac4jIdentityAdapter.java b/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/filter/Pac4jIdentityAdapter.java
new file mode 100644
index 0000000..87d0e8e
--- /dev/null
+++ b/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/filter/Pac4jIdentityAdapter.java
@@ -0,0 +1,138 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.pac4j.filter;
+
+import org.apache.hadoop.gateway.audit.api.*;
+import org.apache.knox.gateway.audit.api.Action;
+import org.apache.knox.gateway.audit.api.ActionOutcome;
+import org.apache.knox.gateway.audit.api.Auditor;
+import org.apache.knox.gateway.audit.api.ResourceType;
+import org.apache.knox.gateway.audit.log4j.audit.AuditConstants;
+import org.apache.knox.gateway.filter.AbstractGatewayFilter;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.apache.knox.gateway.audit.api.AuditService;
+import org.apache.knox.gateway.audit.api.AuditServiceFactory;
+import org.pac4j.core.config.ConfigSingleton;
+import org.pac4j.core.context.J2EContext;
+import org.pac4j.core.profile.ProfileManager;
+import org.pac4j.core.profile.UserProfile;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.security.auth.Subject;
+import javax.servlet.*;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+
+/**
+ * <p>This filter retrieves the authenticated user saved by the pac4j provider and injects it into the J2E HTTP request.</p>
+ *
+ * @since 0.8.0
+ */
+public class Pac4jIdentityAdapter implements Filter {
+
+  private static final Logger logger = LoggerFactory.getLogger(Pac4jIdentityAdapter.class);
+
+  private static AuditService auditService = AuditServiceFactory.getAuditService();
+  private static Auditor auditor = auditService.getAuditor(
+      AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
+      AuditConstants.KNOX_COMPONENT_NAME );
+
+  private String testIdentifier;
+
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+  }
+
+  public void destroy() {
+  }
+
+  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
+      throws IOException, ServletException {
+
+    final HttpServletRequest request = (HttpServletRequest) servletRequest;
+    final HttpServletResponse response = (HttpServletResponse) servletResponse;
+    final J2EContext context = new J2EContext(request, response, ConfigSingleton.getConfig().getSessionStore());
+    final ProfileManager manager = new ProfileManager(context);
+    final UserProfile profile = manager.get(true);
+    logger.debug("User authenticated as: {}", profile);
+    manager.remove(true);
+    final String id = profile.getId();
+    testIdentifier = id;
+    PrimaryPrincipal pp = new PrimaryPrincipal(id);
+    Subject subject = new Subject();
+    subject.getPrincipals().add(pp);
+    auditService.getContext().setUsername(id);
+    String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
+    auditor.audit(Action.AUTHENTICATION, sourceUri, ResourceType.URI, ActionOutcome.SUCCESS);
+    
+    doAs(request, response, chain, subject);
+  }
+  
+  private void doAs(final ServletRequest request,
+      final ServletResponse response, final FilterChain chain, Subject subject)
+      throws IOException, ServletException {
+    try {
+      Subject.doAs(
+          subject,
+          new PrivilegedExceptionAction<Object>() {
+            public Object run() throws Exception {
+              chain.doFilter(request, response);
+              return null;
+            }
+          }
+          );
+    }
+    catch (PrivilegedActionException e) {
+      Throwable t = e.getCause();
+      if (t instanceof IOException) {
+        throw (IOException) t;
+      }
+      else if (t instanceof ServletException) {
+        throw (ServletException) t;
+      }
+      else {
+        throw new ServletException(t);
+      }
+    }
+  }
+
+  /**
+   * For tests only.
+   */
+  public static void setAuditService(AuditService auditService) {
+    Pac4jIdentityAdapter.auditService = auditService;
+  }
+
+  /**
+   * For tests only.
+   */
+  public static void setAuditor(Auditor auditor) {
+    Pac4jIdentityAdapter.auditor = auditor;
+  }
+
+  /**
+   * For tests only.
+     */
+  public String getTestIdentifier() {
+    return testIdentifier;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/session/KnoxSessionStore.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/session/KnoxSessionStore.java b/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/session/KnoxSessionStore.java
new file mode 100644
index 0000000..6ce002c
--- /dev/null
+++ b/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/session/KnoxSessionStore.java
@@ -0,0 +1,120 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.pac4j.session;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.knox.gateway.services.security.CryptoService;
+import org.apache.knox.gateway.services.security.EncryptionResult;
+import org.apache.knox.gateway.util.Urls;
+import org.pac4j.core.context.ContextHelper;
+import org.pac4j.core.context.Cookie;
+import org.pac4j.core.context.WebContext;
+import org.pac4j.core.context.session.SessionStore;
+import org.pac4j.core.exception.TechnicalException;
+import org.pac4j.core.util.JavaSerializationHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.Serializable;
+
+/**
+ * Specific session store where data are saved into cookies (and not in memory).
+ * Each data is encrypted and base64 encoded before being saved as a cookie (for security reasons).
+ *
+ * @since 0.8.0
+ */
+public class KnoxSessionStore implements SessionStore {
+
+    private static final Logger logger = LoggerFactory.getLogger(KnoxSessionStore.class);
+
+    public static final String PAC4J_PASSWORD = "pac4j.password";
+
+    public static final String PAC4J_SESSION_PREFIX = "pac4j.session.";
+
+    private final JavaSerializationHelper javaSerializationHelper;
+
+    private final CryptoService cryptoService;
+
+    private final String clusterName;
+
+    private final String domainSuffix;
+
+    public KnoxSessionStore(final CryptoService cryptoService, final String clusterName, final String domainSuffix) {
+        javaSerializationHelper = new JavaSerializationHelper();
+        this.cryptoService = cryptoService;
+        this.clusterName = clusterName;
+        this.domainSuffix = domainSuffix;
+    }
+
+    public String getOrCreateSessionId(WebContext context) {
+        return null;
+    }
+
+    private Serializable decryptBase64(final String v) {
+        if (v != null && v.length() > 0) {
+            byte[] bytes = Base64.decodeBase64(v);
+            EncryptionResult result = EncryptionResult.fromByteArray(bytes);
+            byte[] clear = cryptoService.decryptForCluster(this.clusterName,
+                    PAC4J_PASSWORD,
+                    result.cipher,
+                    result.iv,
+                    result.salt);
+            if (clear != null) {
+                return javaSerializationHelper.unserializeFromBytes(clear);
+            }
+        }
+        return null;
+    }
+
+    public Object get(WebContext context, String key) {
+        final Cookie cookie = ContextHelper.getCookie(context, PAC4J_SESSION_PREFIX + key);
+        Object value = null;
+        if (cookie != null) {
+            value = decryptBase64(cookie.getValue());
+        }
+        logger.debug("Get from session: {} = {}", key, value);
+        return value;
+    }
+
+    private String encryptBase64(final Object o) {
+        if (o == null || o.equals("")) {
+            return null;
+        } else {
+            final byte[] bytes = javaSerializationHelper.serializeToBytes((Serializable) o);
+            EncryptionResult result = cryptoService.encryptForCluster(this.clusterName, PAC4J_PASSWORD, bytes);
+            return Base64.encodeBase64String(result.toByteAray());
+        }
+    }
+
+    public void set(WebContext context, String key, Object value) {
+        logger.debug("Save in session: {} = {}", key, value);
+        final Cookie cookie = new Cookie(PAC4J_SESSION_PREFIX + key, encryptBase64(value));
+        try {
+            String domain = Urls.getDomainName(context.getFullRequestURL(), this.domainSuffix);
+            if (domain == null) {
+                domain = context.getServerName();
+            }
+            cookie.setDomain(domain);
+        } catch (final Exception e) {
+            throw new TechnicalException(e);
+        }
+        cookie.setHttpOnly(true);
+        cookie.setSecure(ContextHelper.isHttpsOrSecure(context));
+        context.addResponseCookie(cookie);
+    }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-pac4j/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index 8cde74f..0000000
--- a/gateway-provider-security-pac4j/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.pac4j.deploy.Pac4jFederationProviderContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-pac4j/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..a195d77
--- /dev/null
+++ b/gateway-provider-security-pac4j/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.pac4j.deploy.Pac4jFederationProviderContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/test/java/org/apache/hadoop/gateway/pac4j/MockHttpServletRequest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/test/java/org/apache/hadoop/gateway/pac4j/MockHttpServletRequest.java b/gateway-provider-security-pac4j/src/test/java/org/apache/hadoop/gateway/pac4j/MockHttpServletRequest.java
deleted file mode 100644
index b09adc9..0000000
--- a/gateway-provider-security-pac4j/src/test/java/org/apache/hadoop/gateway/pac4j/MockHttpServletRequest.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.hadoop.gateway.pac4j;
-
-import javax.servlet.http.*;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.mockito.Mockito.*;
-
-public class MockHttpServletRequest extends HttpServletRequestWrapper {
-
-    private String requestUrl;
-    private Cookie[] cookies;
-    private String serverName;
-    private Map<String, String> parameters = new HashMap<>();
-    private Map<String, String> headers = new HashMap<>();
-
-    public MockHttpServletRequest() {
-        super(mock(HttpServletRequest.class));
-    }
-
-    @Override
-    public Cookie[] getCookies() {
-        return cookies;
-    }
-
-    public void setCookies(final Cookie[] cookies) {
-        this.cookies = cookies;
-    }
-
-    @Override
-    public StringBuffer getRequestURL() {
-        return new StringBuffer(requestUrl);
-    }
-
-    public void setRequestURL(final String requestUrl) {
-        this.requestUrl = requestUrl;
-    }
-
-    @Override
-    public String getServerName() {
-        return serverName;
-    }
-
-    public void setServerName(final String serverName) {
-        this.serverName = serverName;
-    }
-
-    @Override
-    public String getParameter(String name) {
-        return parameters.get(name);
-    }
-
-    public void addParameter(String key, String value) {
-        parameters.put(key, value);
-    }
-
-    @Override
-    public String getHeader(String name) {
-        return headers.get(name);
-    }
-
-    public void addHeader(String key, String value) {
-        headers.put(key, value);
-    }
-
-    @Override
-    public Object getAttribute(String name) {
-        return null;
-    }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/test/java/org/apache/hadoop/gateway/pac4j/MockHttpServletResponse.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/test/java/org/apache/hadoop/gateway/pac4j/MockHttpServletResponse.java b/gateway-provider-security-pac4j/src/test/java/org/apache/hadoop/gateway/pac4j/MockHttpServletResponse.java
deleted file mode 100644
index 11d104c..0000000
--- a/gateway-provider-security-pac4j/src/test/java/org/apache/hadoop/gateway/pac4j/MockHttpServletResponse.java
+++ /dev/null
@@ -1,82 +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.hadoop.gateway.pac4j;
-
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpServletResponseWrapper;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import static org.mockito.Mockito.*;
-
-public class MockHttpServletResponse extends HttpServletResponseWrapper {
-
-    private List<Cookie> cookies = new ArrayList<>();
-    private String location;
-    private int status = 0;
-    private Map<String, String> headers = new HashMap<>();
-
-    public MockHttpServletResponse() {
-        super(mock(HttpServletResponse.class));
-    }
-
-    @Override
-    public void setHeader(String name, String value) {
-        headers.put(name, value);
-    }
-
-    @Override
-    public void addHeader(String name, String value) {
-        headers.put(name, value);
-    }
-
-    public Map<String, String> getHeaders() {
-        return headers;
-    }
-
-    @Override
-    public void addCookie(Cookie cookie) {
-        cookies.add(cookie);
-    }
-
-    public List<Cookie> getCookies() {
-        return cookies;
-    }
-
-    @Override
-    public void sendRedirect(String location) throws IOException {
-        setStatus(302);
-        setHeader("Location", location);
-    }
-
-    @Override
-    public void setStatus(int sc) {
-        status = sc;
-    }
-
-    @Override
-    public int getStatus() {
-        return status;
-    }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/test/java/org/apache/hadoop/gateway/pac4j/Pac4jProviderTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/test/java/org/apache/hadoop/gateway/pac4j/Pac4jProviderTest.java b/gateway-provider-security-pac4j/src/test/java/org/apache/hadoop/gateway/pac4j/Pac4jProviderTest.java
deleted file mode 100644
index 60bf6f8..0000000
--- a/gateway-provider-security-pac4j/src/test/java/org/apache/hadoop/gateway/pac4j/Pac4jProviderTest.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.
- */
-package org.apache.hadoop.gateway.pac4j;
-
-import org.apache.hadoop.gateway.audit.api.AuditContext;
-import org.apache.hadoop.gateway.audit.api.AuditService;
-import org.apache.hadoop.gateway.audit.api.Auditor;
-import org.apache.hadoop.gateway.pac4j.filter.Pac4jDispatcherFilter;
-import org.apache.hadoop.gateway.pac4j.filter.Pac4jIdentityAdapter;
-import org.apache.hadoop.gateway.pac4j.session.KnoxSessionStore;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.security.AliasService;
-import org.apache.hadoop.gateway.services.security.impl.DefaultCryptoService;
-import org.junit.Test;
-import org.pac4j.core.client.Clients;
-import org.pac4j.core.context.Pac4jConstants;
-import org.pac4j.http.client.indirect.IndirectBasicAuthClient;
-
-import javax.servlet.*;
-import javax.servlet.http.*;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import static org.mockito.Mockito.*;
-import static org.junit.Assert.*;
-
-/**
- * This class simulates a full authentication process using pac4j.
- */
-public class Pac4jProviderTest {
-
-    private static final String LOCALHOST = "127.0.0.1";
-    private static final String HADOOP_SERVICE_URL = "https://" + LOCALHOST + ":8443/gateway/sandox/webhdfs/v1/tmp?op=LISTSTATUS";
-    private static final String KNOXSSO_SERVICE_URL = "https://" + LOCALHOST + ":8443/gateway/idp/api/v1/websso";
-    private static final String PAC4J_CALLBACK_URL = KNOXSSO_SERVICE_URL;
-    private static final String ORIGINAL_URL = "originalUrl";
-    private static final String CLUSTER_NAME = "knox";
-    private static final String PAC4J_PASSWORD = "pwdfortest";
-    private static final String CLIENT_CLASS = IndirectBasicAuthClient.class.getSimpleName();
-    private static final String USERNAME = "jleleu";
-
-    @Test
-    public void test() throws Exception {
-        final AliasService aliasService = mock(AliasService.class);
-        when(aliasService.getPasswordFromAliasForCluster(CLUSTER_NAME, KnoxSessionStore.PAC4J_PASSWORD, true)).thenReturn(PAC4J_PASSWORD.toCharArray());
-        when(aliasService.getPasswordFromAliasForCluster(CLUSTER_NAME, KnoxSessionStore.PAC4J_PASSWORD)).thenReturn(PAC4J_PASSWORD.toCharArray());
-
-        final DefaultCryptoService cryptoService = new DefaultCryptoService();
-        cryptoService.setAliasService(aliasService);
-
-        final GatewayServices services = mock(GatewayServices.class);
-        when(services.getService(GatewayServices.CRYPTO_SERVICE)).thenReturn(cryptoService);
-        when(services.getService(GatewayServices.ALIAS_SERVICE)).thenReturn(aliasService);
-
-        final ServletContext context = mock(ServletContext.class);
-        when(context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE)).thenReturn(services);
-        when(context.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE)).thenReturn(CLUSTER_NAME);
-
-        final FilterConfig config = mock(FilterConfig.class);
-        when(config.getServletContext()).thenReturn(context);
-        when(config.getInitParameter(Pac4jDispatcherFilter.PAC4J_CALLBACK_URL)).thenReturn(PAC4J_CALLBACK_URL);
-        when(config.getInitParameter(Pac4jConstants.CLIENT_NAME)).thenReturn(Pac4jDispatcherFilter.TEST_BASIC_AUTH);
-
-        final Pac4jDispatcherFilter dispatcher = new Pac4jDispatcherFilter();
-        dispatcher.init(config);
-        final Pac4jIdentityAdapter adapter = new Pac4jIdentityAdapter();
-        adapter.init(config);
-        adapter.setAuditor(mock(Auditor.class));
-        final AuditService auditService = mock(AuditService.class);
-        when(auditService.getContext()).thenReturn(mock(AuditContext.class));
-        adapter.setAuditService(auditService);
-
-        // step 1: call the KnoxSSO service with an original url pointing to an Hadoop service (redirected by the SSOCookieProvider)
-        MockHttpServletRequest request = new MockHttpServletRequest();
-        request.setRequestURL(KNOXSSO_SERVICE_URL + "?" + ORIGINAL_URL + "=" + HADOOP_SERVICE_URL);
-        request.setCookies(new Cookie[0]);
-        request.setServerName(LOCALHOST);
-        MockHttpServletResponse response = new MockHttpServletResponse();
-        FilterChain filterChain = mock(FilterChain.class);
-        dispatcher.doFilter(request, response, filterChain);
-        // it should be a redirection to the idp topology
-        assertEquals(302, response.getStatus());
-        assertEquals(PAC4J_CALLBACK_URL + "?" + Pac4jDispatcherFilter.PAC4J_CALLBACK_PARAMETER + "=true&" + Clients.DEFAULT_CLIENT_NAME_PARAMETER + "=" + CLIENT_CLASS, response.getHeaders().get("Location"));
-        // we should have one cookie for the saved requested url
-        List<Cookie> cookies = response.getCookies();
-        assertEquals(1, cookies.size());
-        final Cookie requestedUrlCookie = cookies.get(0);
-        assertEquals(KnoxSessionStore.PAC4J_SESSION_PREFIX + Pac4jConstants.REQUESTED_URL, requestedUrlCookie.getName());
-
-        // step 2: send credentials to the callback url (callback from the identity provider)
-        request = new MockHttpServletRequest();
-        request.setCookies(new Cookie[]{requestedUrlCookie});
-        request.setRequestURL(PAC4J_CALLBACK_URL + "?" + Pac4jDispatcherFilter.PAC4J_CALLBACK_PARAMETER + "=true&" + Clients.DEFAULT_CLIENT_NAME_PARAMETER + "=" + Clients.DEFAULT_CLIENT_NAME_PARAMETER + "=" + CLIENT_CLASS);
-        request.addParameter(Pac4jDispatcherFilter.PAC4J_CALLBACK_PARAMETER, "true");
-        request.addParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER, CLIENT_CLASS);
-        request.addHeader("Authorization", "Basic amxlbGV1OmpsZWxldQ==");
-        request.setServerName(LOCALHOST);
-        response = new MockHttpServletResponse();
-        filterChain = mock(FilterChain.class);
-        dispatcher.doFilter(request, response, filterChain);
-        // it should be a redirection to the original url
-        assertEquals(302, response.getStatus());
-        assertEquals(KNOXSSO_SERVICE_URL + "?" + ORIGINAL_URL + "=" + HADOOP_SERVICE_URL, response.getHeaders().get("Location"));
-        // we should have 3 cookies among with the user profile
-        cookies = response.getCookies();
-        Map<String, String> mapCookies = new HashMap<>();
-        assertEquals(3, cookies.size());
-        for (final Cookie cookie : cookies) {
-            mapCookies.put(cookie.getName(), cookie.getValue());
-        }
-        assertNull(mapCookies.get(KnoxSessionStore.PAC4J_SESSION_PREFIX + CLIENT_CLASS + "$attemptedAuthentication"));
-        assertNotNull(mapCookies.get(KnoxSessionStore.PAC4J_SESSION_PREFIX + Pac4jConstants.USER_PROFILE));
-        assertNull(mapCookies.get(KnoxSessionStore.PAC4J_SESSION_PREFIX + Pac4jConstants.REQUESTED_URL));
-
-        // step 3: turn pac4j identity into KnoxSSO identity
-        request = new MockHttpServletRequest();
-        request.setCookies(cookies.toArray(new Cookie[cookies.size()]));
-        request.setRequestURL(KNOXSSO_SERVICE_URL + "?" + ORIGINAL_URL + "=" + HADOOP_SERVICE_URL);
-        request.setServerName(LOCALHOST);
-        response = new MockHttpServletResponse();
-        filterChain = mock(FilterChain.class);
-        dispatcher.doFilter(request, response, filterChain);
-        assertEquals(0, response.getStatus());
-        adapter.doFilter(request, response, filterChain);
-        cookies = response.getCookies();
-        assertEquals(1, cookies.size());
-        final Cookie userProfileCookie = cookies.get(0);
-        // the user profile has been cleaned
-        assertEquals(KnoxSessionStore.PAC4J_SESSION_PREFIX + Pac4jConstants.USER_PROFILE, userProfileCookie.getName());
-        assertNull(userProfileCookie.getValue());
-        assertEquals(USERNAME, adapter.getTestIdentifier());
-    }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/test/java/org/apache/knox/gateway/pac4j/MockHttpServletRequest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/test/java/org/apache/knox/gateway/pac4j/MockHttpServletRequest.java b/gateway-provider-security-pac4j/src/test/java/org/apache/knox/gateway/pac4j/MockHttpServletRequest.java
new file mode 100644
index 0000000..7a3a833
--- /dev/null
+++ b/gateway-provider-security-pac4j/src/test/java/org/apache/knox/gateway/pac4j/MockHttpServletRequest.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.knox.gateway.pac4j;
+
+import javax.servlet.http.*;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.mockito.Mockito.*;
+
+public class MockHttpServletRequest extends HttpServletRequestWrapper {
+
+    private String requestUrl;
+    private Cookie[] cookies;
+    private String serverName;
+    private Map<String, String> parameters = new HashMap<>();
+    private Map<String, String> headers = new HashMap<>();
+
+    public MockHttpServletRequest() {
+        super(mock(HttpServletRequest.class));
+    }
+
+    @Override
+    public Cookie[] getCookies() {
+        return cookies;
+    }
+
+    public void setCookies(final Cookie[] cookies) {
+        this.cookies = cookies;
+    }
+
+    @Override
+    public StringBuffer getRequestURL() {
+        return new StringBuffer(requestUrl);
+    }
+
+    public void setRequestURL(final String requestUrl) {
+        this.requestUrl = requestUrl;
+    }
+
+    @Override
+    public String getServerName() {
+        return serverName;
+    }
+
+    public void setServerName(final String serverName) {
+        this.serverName = serverName;
+    }
+
+    @Override
+    public String getParameter(String name) {
+        return parameters.get(name);
+    }
+
+    public void addParameter(String key, String value) {
+        parameters.put(key, value);
+    }
+
+    @Override
+    public String getHeader(String name) {
+        return headers.get(name);
+    }
+
+    public void addHeader(String key, String value) {
+        headers.put(key, value);
+    }
+
+    @Override
+    public Object getAttribute(String name) {
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/test/java/org/apache/knox/gateway/pac4j/MockHttpServletResponse.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/test/java/org/apache/knox/gateway/pac4j/MockHttpServletResponse.java b/gateway-provider-security-pac4j/src/test/java/org/apache/knox/gateway/pac4j/MockHttpServletResponse.java
new file mode 100644
index 0000000..07dd255
--- /dev/null
+++ b/gateway-provider-security-pac4j/src/test/java/org/apache/knox/gateway/pac4j/MockHttpServletResponse.java
@@ -0,0 +1,82 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.pac4j;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpServletResponseWrapper;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.mockito.Mockito.*;
+
+public class MockHttpServletResponse extends HttpServletResponseWrapper {
+
+    private List<Cookie> cookies = new ArrayList<>();
+    private String location;
+    private int status = 0;
+    private Map<String, String> headers = new HashMap<>();
+
+    public MockHttpServletResponse() {
+        super(mock(HttpServletResponse.class));
+    }
+
+    @Override
+    public void setHeader(String name, String value) {
+        headers.put(name, value);
+    }
+
+    @Override
+    public void addHeader(String name, String value) {
+        headers.put(name, value);
+    }
+
+    public Map<String, String> getHeaders() {
+        return headers;
+    }
+
+    @Override
+    public void addCookie(Cookie cookie) {
+        cookies.add(cookie);
+    }
+
+    public List<Cookie> getCookies() {
+        return cookies;
+    }
+
+    @Override
+    public void sendRedirect(String location) throws IOException {
+        setStatus(302);
+        setHeader("Location", location);
+    }
+
+    @Override
+    public void setStatus(int sc) {
+        status = sc;
+    }
+
+    @Override
+    public int getStatus() {
+        return status;
+    }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/test/java/org/apache/knox/gateway/pac4j/Pac4jProviderTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/test/java/org/apache/knox/gateway/pac4j/Pac4jProviderTest.java b/gateway-provider-security-pac4j/src/test/java/org/apache/knox/gateway/pac4j/Pac4jProviderTest.java
new file mode 100644
index 0000000..606d042
--- /dev/null
+++ b/gateway-provider-security-pac4j/src/test/java/org/apache/knox/gateway/pac4j/Pac4jProviderTest.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.
+ */
+package org.apache.knox.gateway.pac4j;
+
+import org.apache.knox.gateway.audit.api.AuditContext;
+import org.apache.knox.gateway.audit.api.AuditService;
+import org.apache.knox.gateway.audit.api.Auditor;
+import org.apache.knox.gateway.pac4j.filter.Pac4jDispatcherFilter;
+import org.apache.knox.gateway.pac4j.filter.Pac4jIdentityAdapter;
+import org.apache.knox.gateway.pac4j.session.KnoxSessionStore;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.AliasService;
+import org.apache.knox.gateway.services.security.impl.DefaultCryptoService;
+import org.junit.Test;
+import org.pac4j.core.client.Clients;
+import org.pac4j.core.context.Pac4jConstants;
+import org.pac4j.http.client.indirect.IndirectBasicAuthClient;
+
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.mockito.Mockito.*;
+import static org.junit.Assert.*;
+
+/**
+ * This class simulates a full authentication process using pac4j.
+ */
+public class Pac4jProviderTest {
+
+    private static final String LOCALHOST = "127.0.0.1";
+    private static final String HADOOP_SERVICE_URL = "https://" + LOCALHOST + ":8443/gateway/sandox/webhdfs/v1/tmp?op=LISTSTATUS";
+    private static final String KNOXSSO_SERVICE_URL = "https://" + LOCALHOST + ":8443/gateway/idp/api/v1/websso";
+    private static final String PAC4J_CALLBACK_URL = KNOXSSO_SERVICE_URL;
+    private static final String ORIGINAL_URL = "originalUrl";
+    private static final String CLUSTER_NAME = "knox";
+    private static final String PAC4J_PASSWORD = "pwdfortest";
+    private static final String CLIENT_CLASS = IndirectBasicAuthClient.class.getSimpleName();
+    private static final String USERNAME = "jleleu";
+
+    @Test
+    public void test() throws Exception {
+        final AliasService aliasService = mock(AliasService.class);
+        when(aliasService.getPasswordFromAliasForCluster(CLUSTER_NAME, KnoxSessionStore.PAC4J_PASSWORD, true)).thenReturn(PAC4J_PASSWORD.toCharArray());
+        when(aliasService.getPasswordFromAliasForCluster(CLUSTER_NAME, KnoxSessionStore.PAC4J_PASSWORD)).thenReturn(PAC4J_PASSWORD.toCharArray());
+
+        final DefaultCryptoService cryptoService = new DefaultCryptoService();
+        cryptoService.setAliasService(aliasService);
+
+        final GatewayServices services = mock(GatewayServices.class);
+        when(services.getService(GatewayServices.CRYPTO_SERVICE)).thenReturn(cryptoService);
+        when(services.getService(GatewayServices.ALIAS_SERVICE)).thenReturn(aliasService);
+
+        final ServletContext context = mock(ServletContext.class);
+        when(context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE)).thenReturn(services);
+        when(context.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE)).thenReturn(CLUSTER_NAME);
+
+        final FilterConfig config = mock(FilterConfig.class);
+        when(config.getServletContext()).thenReturn(context);
+        when(config.getInitParameter(Pac4jDispatcherFilter.PAC4J_CALLBACK_URL)).thenReturn(PAC4J_CALLBACK_URL);
+        when(config.getInitParameter(Pac4jConstants.CLIENT_NAME)).thenReturn(Pac4jDispatcherFilter.TEST_BASIC_AUTH);
+
+        final Pac4jDispatcherFilter dispatcher = new Pac4jDispatcherFilter();
+        dispatcher.init(config);
+        final Pac4jIdentityAdapter adapter = new Pac4jIdentityAdapter();
+        adapter.init(config);
+        adapter.setAuditor(mock(Auditor.class));
+        final AuditService auditService = mock(AuditService.class);
+        when(auditService.getContext()).thenReturn(mock(AuditContext.class));
+        adapter.setAuditService(auditService);
+
+        // step 1: call the KnoxSSO service with an original url pointing to an Hadoop service (redirected by the SSOCookieProvider)
+        MockHttpServletRequest request = new MockHttpServletRequest();
+        request.setRequestURL(KNOXSSO_SERVICE_URL + "?" + ORIGINAL_URL + "=" + HADOOP_SERVICE_URL);
+        request.setCookies(new Cookie[0]);
+        request.setServerName(LOCALHOST);
+        MockHttpServletResponse response = new MockHttpServletResponse();
+        FilterChain filterChain = mock(FilterChain.class);
+        dispatcher.doFilter(request, response, filterChain);
+        // it should be a redirection to the idp topology
+        assertEquals(302, response.getStatus());
+        assertEquals(PAC4J_CALLBACK_URL + "?" + Pac4jDispatcherFilter.PAC4J_CALLBACK_PARAMETER + "=true&" + Clients.DEFAULT_CLIENT_NAME_PARAMETER + "=" + CLIENT_CLASS, response.getHeaders().get("Location"));
+        // we should have one cookie for the saved requested url
+        List<Cookie> cookies = response.getCookies();
+        assertEquals(1, cookies.size());
+        final Cookie requestedUrlCookie = cookies.get(0);
+        assertEquals(KnoxSessionStore.PAC4J_SESSION_PREFIX + Pac4jConstants.REQUESTED_URL, requestedUrlCookie.getName());
+
+        // step 2: send credentials to the callback url (callback from the identity provider)
+        request = new MockHttpServletRequest();
+        request.setCookies(new Cookie[]{requestedUrlCookie});
+        request.setRequestURL(PAC4J_CALLBACK_URL + "?" + Pac4jDispatcherFilter.PAC4J_CALLBACK_PARAMETER + "=true&" + Clients.DEFAULT_CLIENT_NAME_PARAMETER + "=" + Clients.DEFAULT_CLIENT_NAME_PARAMETER + "=" + CLIENT_CLASS);
+        request.addParameter(Pac4jDispatcherFilter.PAC4J_CALLBACK_PARAMETER, "true");
+        request.addParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER, CLIENT_CLASS);
+        request.addHeader("Authorization", "Basic amxlbGV1OmpsZWxldQ==");
+        request.setServerName(LOCALHOST);
+        response = new MockHttpServletResponse();
+        filterChain = mock(FilterChain.class);
+        dispatcher.doFilter(request, response, filterChain);
+        // it should be a redirection to the original url
+        assertEquals(302, response.getStatus());
+        assertEquals(KNOXSSO_SERVICE_URL + "?" + ORIGINAL_URL + "=" + HADOOP_SERVICE_URL, response.getHeaders().get("Location"));
+        // we should have 3 cookies among with the user profile
+        cookies = response.getCookies();
+        Map<String, String> mapCookies = new HashMap<>();
+        assertEquals(3, cookies.size());
+        for (final Cookie cookie : cookies) {
+            mapCookies.put(cookie.getName(), cookie.getValue());
+        }
+        assertNull(mapCookies.get(KnoxSessionStore.PAC4J_SESSION_PREFIX + CLIENT_CLASS + "$attemptedAuthentication"));
+        assertNotNull(mapCookies.get(KnoxSessionStore.PAC4J_SESSION_PREFIX + Pac4jConstants.USER_PROFILE));
+        assertNull(mapCookies.get(KnoxSessionStore.PAC4J_SESSION_PREFIX + Pac4jConstants.REQUESTED_URL));
+
+        // step 3: turn pac4j identity into KnoxSSO identity
+        request = new MockHttpServletRequest();
+        request.setCookies(cookies.toArray(new Cookie[cookies.size()]));
+        request.setRequestURL(KNOXSSO_SERVICE_URL + "?" + ORIGINAL_URL + "=" + HADOOP_SERVICE_URL);
+        request.setServerName(LOCALHOST);
+        response = new MockHttpServletResponse();
+        filterChain = mock(FilterChain.class);
+        dispatcher.doFilter(request, response, filterChain);
+        assertEquals(0, response.getStatus());
+        adapter.doFilter(request, response, filterChain);
+        cookies = response.getCookies();
+        assertEquals(1, cookies.size());
+        final Cookie userProfileCookie = cookies.get(0);
+        // the user profile has been cleaned
+        assertEquals(KnoxSessionStore.PAC4J_SESSION_PREFIX + Pac4jConstants.USER_PROFILE, userProfileCookie.getName());
+        assertNull(userProfileCookie.getValue());
+        assertEquals(USERNAME, adapter.getTestIdentifier());
+    }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/PicketlinkMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/PicketlinkMessages.java b/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/PicketlinkMessages.java
deleted file mode 100644
index c49030f..0000000
--- a/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/PicketlinkMessages.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.hadoop.gateway.picketlink;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-import org.apache.hadoop.gateway.i18n.messages.StackTrace;
-
-@Messages(logger="org.apache.hadoop.gateway.picketlink")
-public interface PicketlinkMessages {
-
-  @Message( level = MessageLevel.DEBUG, text = "Found Original URL in reequest: {0}")
-  public void foundOriginalURLInRequest(String url);
-
-  @Message( level = MessageLevel.DEBUG, text = "setting cookie for original-url")
-  public void settingCookieForOriginalURL();
-
-  @Message( level = MessageLevel.DEBUG, text = "Secure Flag is set to False for cookie")
-  public void secureFlagFalseForCookie();
-
-  @Message( level = MessageLevel.ERROR, text = "Unable to get the gateway identity passphrase: {0}")
-  public void unableToGetGatewayIdentityPassphrase(@StackTrace( level = MessageLevel.DEBUG) Exception e);
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/deploy/PicketlinkConf.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/deploy/PicketlinkConf.java b/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/deploy/PicketlinkConf.java
deleted file mode 100644
index 59203c6..0000000
--- a/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/deploy/PicketlinkConf.java
+++ /dev/null
@@ -1,194 +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.hadoop.gateway.picketlink.deploy;
-
-/**
- * Provides a serializable configuration file for adding to
- * the webapp as an XML string for picketlink.xml
- *
- */
-public class PicketlinkConf {
-  public static final String INDENT = "    ";
-  public static final String LT_OPEN = "<";
-  public static final String LT_CLOSE = "</";
-  public static final String GT = ">";
-  public static final String GT_CLOSE = "/>";
-  public static final String NL = "\n";
-  public static final String PICKETLINK_XMLNS = "urn:picketlink:identity-federation:config:2.1";
-  public static final String PICKETLINK_SP_XMLNS = "urn:picketlink:identity-federation:config:1.0";
-  public static final String C14N_METHOD = "http://www.w3.org/2001/10/xml-exc-c14n#";
-  public static final String KEYPROVIDER_ELEMENT = "KeyProvider";
-  public static final String KEYPROVIDER_CLASSNAME = "org.picketlink.identity.federation.core.impl.KeyStoreKeyManager";
-  public static final String AUTH_HANDLER_CLASSNAME = "org.picketlink.identity.federation.web.handlers.saml2.SAML2AuthenticationHandler";
-  public static final String ROLE_GEN_HANDLER_CLASSNAME = "org.picketlink.identity.federation.web.handlers.saml2.RolesGenerationHandler";
-  public static final String PICKETLINK_ELEMENT = "PicketLink";
-  public static final String PICKETLINKSP_ELEMENT = "PicketLinkSP";
-  public static final String HANDLERS_ELEMENT = "Handlers";
-  public static final String HANDLER_ELEMENT = "Handler";
-  public static final String OPTION_ELEMENT = "Option";
-  public static final String VAL_ALIAS_ELEMENT = "ValidatingAlias";
-  public static final String AUTH_ELEMENT = "Auth";
-
-  private String serverEnvironment = "jetty";
-  private String bindingType = "POST";
-  private String idpUsesPostingBinding = "true";
-  private String supportsSignatures = "true";
-  private String identityURL = null;
-  private String serviceURL = null;
-  private String keystoreURL = null;
-  private String keystorePass = null;
-  private String signingKeyAlias = null;
-  private String signingKeyPass = null;
-  private String validatingKeyAlias = null;
-  private String validatingKeyValue = null;
-  private String nameIDFormat = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent";
-  private String clockSkewMilis = null;
-  private String assertionSessionAttributeName = "org.picketlink.sp.assertion";
-  
-  public String getServerEnvironment() {
-    return serverEnvironment;
-  }
-  public void setServerEnvironment(String serverEnvironment) {
-    this.serverEnvironment = serverEnvironment;
-  }
-  public String getBindingType() {
-    return bindingType;
-  }
-  public void setBindingType(String bindingType) {
-    this.bindingType = bindingType;
-  }
-  public String getIdpUsesPostingBinding() {
-    return idpUsesPostingBinding;
-  }
-  public void setIdpUsesPostingBinding(String idpUsesPostingBinding) {
-    this.idpUsesPostingBinding = idpUsesPostingBinding;
-  }
-  public String getSupportsSignatures() {
-    return supportsSignatures;
-  }
-  public void setSupportsSignatures(String supportsSignatures) {
-    this.supportsSignatures = supportsSignatures;
-  }
-  public String getIdentityURL() {
-    return identityURL;
-  }
-  public void setIdentityURL(String identityURL) {
-    this.identityURL = identityURL;
-  }
-  public String getServiceURL() {
-    return serviceURL;
-  }
-  public void setServiceURL(String serviceURL) {
-    this.serviceURL = serviceURL;
-  }
-  public String getKeystoreURL() {
-    return keystoreURL;
-  }
-  public void setKeystoreURL(String keystoreURL) {
-    this.keystoreURL = keystoreURL;
-  }
-  public String getKeystorePass() {
-    return keystorePass;
-  }
-  public void setKeystorePass(String keystorePass) {
-    this.keystorePass = keystorePass;
-  }
-  public String getSigningKeyAlias() {
-    return signingKeyAlias;
-  }
-  public void setSigningKeyAlias(String signingKeyAlias) {
-    this.signingKeyAlias = signingKeyAlias;
-  }
-  public String getSigningKeyPass() {
-    return signingKeyPass;
-  }
-  public void setSigningKeyPass(String signingKeyPass) {
-    this.signingKeyPass = signingKeyPass;
-  }
-  public String getValidatingKeyAlias() {
-    return validatingKeyAlias;
-  }
-  public void setValidatingAliasKey(String validatingKeyAlias) {
-    this.validatingKeyAlias = validatingKeyAlias;
-  }
-  public String getValidatingKeyValue() {
-    return validatingKeyValue;
-  }
-  public void setValidatingAliasValue(String validatingKeyValue) {
-    this.validatingKeyValue = validatingKeyValue;
-  }
-  public String getNameIDFormat() {
-    return nameIDFormat;
-  }
-  public void setNameIDFormat(String nameIDFormat) {
-    this.nameIDFormat = nameIDFormat;
-  }
-  public String getClockSkewMilis() {
-    return clockSkewMilis;
-  }
-  public void setClockSkewMilis(String clockSkewMilis) {
-    this.clockSkewMilis = clockSkewMilis;
-  }
-  public String getAssertionSessionAttributeName() {
-    return assertionSessionAttributeName;
-  }
-  public void setAssertionSessionAttributeName(
-      String assertionSessionAttributeName) {
-    this.assertionSessionAttributeName = assertionSessionAttributeName;
-  }
-  @Override
-  public String toString() {
-    // THIS IS HORRID REPLACE WITH DOM+TRANSFORM
-    StringBuffer xml = new StringBuffer();
-    xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>").append(NL)
-    .append(LT_OPEN).append(PICKETLINK_ELEMENT).append(" xmlns=\"").append(PICKETLINK_XMLNS).append("\"" + GT).append(NL)
-      .append(INDENT).append(LT_OPEN).append(PICKETLINKSP_ELEMENT).append(" xmlns=\"").append(PICKETLINK_SP_XMLNS + "\"").append(NL)
-      .append(INDENT).append(INDENT).append("ServerEnvironment").append("=\"").append(serverEnvironment).append("\"").append(NL)
-      .append(INDENT).append(INDENT).append("BindingType").append("=\"").append(bindingType).append("\"").append(NL)
-      .append(INDENT).append(INDENT).append("IDPUsesPostBinding").append("=\"").append(idpUsesPostingBinding).append("\"").append(NL)
-      .append(INDENT).append(INDENT).append("SupportsSignatures").append("=\"").append(supportsSignatures).append("\"").append(NL)
-      .append(INDENT).append(INDENT).append("CanonicalizationMethod").append("=\"").append(C14N_METHOD).append("\"").append(GT).append(NL).append(NL)
-      .append(INDENT).append(INDENT).append(LT_OPEN).append("IdentityURL").append(GT).append(identityURL).append(LT_CLOSE).append("IdentityURL").append(GT).append(NL)
-      .append(INDENT).append(INDENT).append(LT_OPEN).append("ServiceURL").append(GT).append(serviceURL).append(LT_CLOSE).append("ServiceURL").append(GT).append(NL)
-      .append(INDENT).append(INDENT).append(LT_OPEN).append(KEYPROVIDER_ELEMENT).append(" ").append("ClassName=\"").append(KEYPROVIDER_CLASSNAME + "\"" + GT).append(NL)
-        .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(AUTH_ELEMENT).append(" Key=\"KeyStoreURL\" Value=\"").append(keystoreURL).append("\"").append(GT_CLOSE).append(NL)
-        .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(AUTH_ELEMENT).append(" Key=\"KeyStorePass\" Value=\"").append(keystorePass).append("\"").append(GT_CLOSE).append(NL)
-        .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(AUTH_ELEMENT).append(" Key=\"SigningKeyAlias\" Value=\"").append(signingKeyAlias).append("\"").append(GT_CLOSE).append(NL)
-        .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(AUTH_ELEMENT).append(" Key=\"SigningKeyPass\" Value=\"").append(signingKeyPass).append("\"").append(GT_CLOSE).append(NL)
-        .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(VAL_ALIAS_ELEMENT).append(" Key=\"").append(validatingKeyAlias).append("\" Value=\"").append(validatingKeyValue).append("\"").append(GT_CLOSE).append(NL)
-      .append(INDENT).append(INDENT).append(LT_CLOSE).append(KEYPROVIDER_ELEMENT).append(GT).append(NL)
-      .append(INDENT).append(LT_CLOSE).append(PICKETLINKSP_ELEMENT).append(GT).append(NL)
-      .append(INDENT).append(LT_OPEN).append(HANDLERS_ELEMENT).append(GT).append(NL)
-        .append(INDENT).append(INDENT).append(LT_OPEN).append(HANDLER_ELEMENT).append(" class=\"").append(AUTH_HANDLER_CLASSNAME).append("\">").append(NL)
-          .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(OPTION_ELEMENT).append(" Key=\"NAMEID_FORMAT\" Value=\"").append(nameIDFormat).append("\"").append(GT_CLOSE).append(NL)
-          .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(OPTION_ELEMENT).append(" Key=\"CLOCK_SKEW_MILIS\" Value=\"").append(clockSkewMilis).append("\"").append(GT_CLOSE).append(NL)
-          .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(OPTION_ELEMENT).append(" Key=\"ASSERTION_SESSION_ATTRIBUTE_NAME\" Value=\"").append(assertionSessionAttributeName).append("\"").append(GT_CLOSE).append(NL)
-        .append(INDENT).append(INDENT).append(LT_CLOSE).append(HANDLER_ELEMENT).append(GT).append(NL)
-        .append(INDENT).append(INDENT).append(LT_OPEN).append(HANDLER_ELEMENT).append(" class=\"").append(ROLE_GEN_HANDLER_CLASSNAME).append("\"/>").append(NL)
-      .append(INDENT).append(LT_CLOSE).append(HANDLERS_ELEMENT).append(GT).append(NL)
-    .append(LT_CLOSE).append(PICKETLINK_ELEMENT).append(GT).append(NL);
-     
-    return xml.toString();
-  }
-  
-  public static void main(String[] args) {
-    PicketlinkConf conf = new PicketlinkConf();
-    System.out.println(conf.toString());
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/deploy/PicketlinkFederationProviderContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/deploy/PicketlinkFederationProviderContributor.java b/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/deploy/PicketlinkFederationProviderContributor.java
deleted file mode 100644
index 4f90a41..0000000
--- a/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/deploy/PicketlinkFederationProviderContributor.java
+++ /dev/null
@@ -1,132 +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.hadoop.gateway.picketlink.deploy;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.picketlink.PicketlinkMessages;
-import org.apache.hadoop.gateway.services.security.AliasService;
-import org.apache.hadoop.gateway.services.security.AliasServiceException;
-import org.apache.hadoop.gateway.services.security.MasterService;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-import org.jboss.shrinkwrap.api.asset.StringAsset;
-import org.picketlink.identity.federation.web.filters.ServiceProviderContextInitializer;
-
-public class PicketlinkFederationProviderContributor extends
-    ProviderDeploymentContributorBase {
-  private static final String ROLE = "federation";
-  private static final String NAME = "Picketlink";
-  private static final String PICKETLINK_FILTER_CLASSNAME = "org.picketlink.identity.federation.web.filters.SPFilter";
-  private static final String CAPTURE_URL_FILTER_CLASSNAME = "org.apache.hadoop.gateway.picketlink.filter.CaptureOriginalURLFilter";
-  private static final String IDENTITY_ADAPTER_CLASSNAME = "org.apache.hadoop.gateway.picketlink.filter.PicketlinkIdentityAdapter";
-  private static final String IDENTITY_URL_PARAM = "identity.url";
-  private static final String SERVICE_URL_PARAM = "service.url";
-  private static final String KEYSTORE_URL_PARAM = "keystore.url";
-  private static final String SIGNINGKEY_ALIAS = "gateway-identity";
-  private static final String VALIDATING_ALIAS_KEY = "validating.alias.key";
-  private static final String VALIDATING_ALIAS_VALUE = "validating.alias.value";
-  private static final String CLOCK_SKEW_MILIS = "clock.skew.milis";
-  private static PicketlinkMessages log = MessagesFactory.get( PicketlinkMessages.class );
-
-  private MasterService ms = null;
-  private AliasService as = null;
-
-  @Override
-  public String getRole() {
-    return ROLE;
-  }
-
-  @Override
-  public String getName() {
-    return NAME;
-  }
-  
-  public void setMasterService(MasterService ms) {
-    this.ms = ms;
-  }
-
-  public void setAliasService(AliasService as) {
-    this.as = as;
-  }
-
-  @Override
-  public void initializeContribution(DeploymentContext context) {
-    super.initializeContribution(context);
-  }
-
-  @Override
-  public void contributeProvider(DeploymentContext context, Provider provider) {
-    // LJM TODO: consider creating a picketlink configuration provider to
-    // handle the keystore secrets without putting them in a config file directly.
-    // Once that is done then we can remove the unneeded gateway services from those
-    // that are available to providers.
-    context.getWebAppDescriptor().createListener().listenerClass( ServiceProviderContextInitializer.class.getName());
-
-    PicketlinkConf config = new PicketlinkConf( );
-    Map<String,String> params = provider.getParams();
-    config.setIdentityURL(params.get(IDENTITY_URL_PARAM));
-    config.setServiceURL(params.get(SERVICE_URL_PARAM));
-    config.setKeystoreURL(params.get(KEYSTORE_URL_PARAM));
-    if (ms != null) {
-      config.setKeystorePass(new String(ms.getMasterSecret()));
-    }
-    config.setSigningKeyAlias(SIGNINGKEY_ALIAS);
-    if (as != null) {
-      char[] passphrase = null;
-      try {
-        passphrase = as.getGatewayIdentityPassphrase();
-        config.setSigningKeyPass(new String(passphrase));
-      } catch (AliasServiceException e) {
-        log.unableToGetGatewayIdentityPassphrase(e);
-      }
-    }
-    config.setValidatingAliasKey(params.get(VALIDATING_ALIAS_KEY));
-    config.setValidatingAliasValue(params.get(VALIDATING_ALIAS_VALUE));
-    config.setClockSkewMilis(params.get(CLOCK_SKEW_MILIS));
-    String configStr = config.toString();
-    if( config != null ) {
-      context.getWebArchive().addAsWebInfResource( new StringAsset( configStr ), "picketlink.xml" );
-    }
-  }
-
-  @Override
-  public void contributeFilter(DeploymentContext context, Provider provider, Service service, 
-      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
-    // blindly add all the provider params as filter init params
-    if (params == null) {
-      params = new ArrayList<FilterParamDescriptor>();
-    }
-    Map<String, String> providerParams = provider.getParams();
-    for(Entry<String, String> entry : providerParams.entrySet()) {
-      params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
-    }
-    resource.addFilter().name( getName() ).role( getRole() ).impl( CAPTURE_URL_FILTER_CLASSNAME ).params( params );
-    resource.addFilter().name( getName() ).role( getRole() ).impl( PICKETLINK_FILTER_CLASSNAME ).params( params );
-    resource.addFilter().name( getName() ).role( getRole() ).impl( IDENTITY_ADAPTER_CLASSNAME ).params( params );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/filter/CaptureOriginalURLFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/filter/CaptureOriginalURLFilter.java b/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/filter/CaptureOriginalURLFilter.java
deleted file mode 100644
index 66da6c4..0000000
--- a/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/filter/CaptureOriginalURLFilter.java
+++ /dev/null
@@ -1,89 +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.hadoop.gateway.picketlink.filter;
-
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.picketlink.PicketlinkMessages;
-
-import java.io.IOException;
-
-public class CaptureOriginalURLFilter implements Filter {
-  private static PicketlinkMessages log = MessagesFactory.get( PicketlinkMessages.class );
-  private static final String COOKIE_PATH = "cookie.path";
-  private static final String COOKIE_SECURE = "cookie.secure";
-  private String cookiePath = null;
-  private String cookieSecure = null;
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-    cookiePath = filterConfig.getInitParameter(COOKIE_PATH);
-    if (cookiePath == null) {
-      cookiePath = "/gateway/idp/knoxsso/api/v1/websso";
-    }
-    cookieSecure = filterConfig.getInitParameter(COOKIE_SECURE);
-    if (cookieSecure == null) {
-      cookieSecure = "true";
-    }
-  }
-
-  @Override
-  public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) throws IOException, ServletException {
-    String original = null;
-    HttpServletRequest request = (HttpServletRequest)servletRequest;
-    String url = request.getParameter("originalUrl");
-    if (url != null) {
-      log.foundOriginalURLInRequest(url);
-      original = request.getParameter("originalUrl");
-      log.settingCookieForOriginalURL();
-      addCookie(servletResponse, original);
-    }
-    filterChain.doFilter(request, servletResponse);
-  }
-
-  @Override
-  public void destroy() {
-
-  }
-
-  private void addCookie(ServletResponse servletResponse, String original) {
-    Cookie c = new Cookie("original-url", original);
-    c.setPath(cookiePath);
-    c.setHttpOnly(true);
-    boolean secureOnly = true;
-    if (cookieSecure != null) {
-      secureOnly = ("false".equals(cookieSecure) ? false : true);
-      if (!secureOnly) {
-        log.secureFlagFalseForCookie();
-      }
-    }
-    c.setSecure(secureOnly);
-    c.setMaxAge(60);
-    ((HttpServletResponse)servletResponse).addCookie(c);
-  }
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/filter/PicketlinkIdentityAdapter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/filter/PicketlinkIdentityAdapter.java b/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/filter/PicketlinkIdentityAdapter.java
deleted file mode 100644
index 333f91d..0000000
--- a/gateway-provider-security-picketlink/src/main/java/org/apache/hadoop/gateway/picketlink/filter/PicketlinkIdentityAdapter.java
+++ /dev/null
@@ -1,102 +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.hadoop.gateway.picketlink.filter;
-
-import java.io.IOException;
-import java.security.Principal;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import javax.security.auth.Subject;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.hadoop.gateway.audit.api.Action;
-import org.apache.hadoop.gateway.audit.api.ActionOutcome;
-import org.apache.hadoop.gateway.audit.api.AuditService;
-import org.apache.hadoop.gateway.audit.api.AuditServiceFactory;
-import org.apache.hadoop.gateway.audit.api.Auditor;
-import org.apache.hadoop.gateway.audit.api.ResourceType;
-import org.apache.hadoop.gateway.audit.log4j.audit.AuditConstants;
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-
-public class PicketlinkIdentityAdapter implements Filter {
-  
-  private static AuditService auditService = AuditServiceFactory.getAuditService();
-  private static Auditor auditor = auditService.getAuditor(
-      AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
-      AuditConstants.KNOX_COMPONENT_NAME );
-  
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-  }
-
-  public void destroy() {
-  }
-
-  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
-      throws IOException, ServletException {
-    
-    HttpServletRequest httpRequest = (HttpServletRequest) request;
-    String username = httpRequest.getUserPrincipal().getName();
-    PrimaryPrincipal pp = new PrimaryPrincipal(username);
-    Subject subject = new Subject();
-    subject.getPrincipals().add(pp);
-    
-    Principal principal = (Principal) subject.getPrincipals(PrimaryPrincipal.class);
-    auditService.getContext().setUsername( principal.getName() );
-    String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
-    auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
-
-    doAs(request, response, chain, subject);
-  }
-  
-  private void doAs(final ServletRequest request,
-      final ServletResponse response, final FilterChain chain, Subject subject)
-      throws IOException, ServletException {
-    try {
-      Subject.doAs(
-          subject,
-          new PrivilegedExceptionAction<Object>() {
-            public Object run() throws Exception {
-              chain.doFilter(request, response);
-              return null;
-            }
-          }
-          );
-    }
-    catch (PrivilegedActionException e) {
-      Throwable t = e.getCause();
-      if (t instanceof IOException) {
-        throw (IOException) t;
-      }
-      else if (t instanceof ServletException) {
-        throw (ServletException) t;
-      }
-      else {
-        throw new ServletException(t);
-      }
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/PicketlinkMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/PicketlinkMessages.java b/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/PicketlinkMessages.java
new file mode 100644
index 0000000..bcb347c
--- /dev/null
+++ b/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/PicketlinkMessages.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.knox.gateway.picketlink;
+
+import org.apache.knox.gateway.i18n.messages.Message;
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.Messages;
+import org.apache.knox.gateway.i18n.messages.StackTrace;
+
+@Messages(logger="org.apache.hadoop.gateway.picketlink")
+public interface PicketlinkMessages {
+
+  @Message( level = MessageLevel.DEBUG, text = "Found Original URL in reequest: {0}")
+  public void foundOriginalURLInRequest(String url);
+
+  @Message( level = MessageLevel.DEBUG, text = "setting cookie for original-url")
+  public void settingCookieForOriginalURL();
+
+  @Message( level = MessageLevel.DEBUG, text = "Secure Flag is set to False for cookie")
+  public void secureFlagFalseForCookie();
+
+  @Message( level = MessageLevel.ERROR, text = "Unable to get the gateway identity passphrase: {0}")
+  public void unableToGetGatewayIdentityPassphrase(@StackTrace( level = MessageLevel.DEBUG) Exception e);
+
+}


[14/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/noop.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/noop.xml b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/noop.xml
deleted file mode 100644
index a716582..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/noop.xml
+++ /dev/null
@@ -1,18 +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.
--->
-<rules/>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/simple.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/simple.xml b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/simple.xml
deleted file mode 100644
index 729a2d4..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/simple.xml
+++ /dev/null
@@ -1,19 +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.
--->
-<rules>
-</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest/rewrite.xml b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest/rewrite.xml
deleted file mode 100644
index 2e1d5af..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest/rewrite.xml
+++ /dev/null
@@ -1,18 +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.
--->
-<rules>
-</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletFilterTest/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletFilterTest/rewrite.xml b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletFilterTest/rewrite.xml
deleted file mode 100644
index 3b77eb3..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletFilterTest/rewrite.xml
+++ /dev/null
@@ -1,109 +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.
--->
-<rules>
-
-    <rule name="test-rule-1" url="{scheme=*}://{host=*}:{port=*}/{path=**}">
-        <rewrite template="{scheme}://{host}:{port}/test-output-path-1"/>
-    </rule>
-
-    <rule name="test-rule-2" url="{scheme=*}://{host=*}:{port=*}/{path=**}">
-        <rewrite template="{scheme}://{host}:{port}/test-output-path-2"/>
-    </rule>
-
-    <rule name="test-rule-username">
-        <match pattern="*://{host}:{port}/{path=**}?{**}"/>
-        <rewrite template="test-output-scheme://{host}:{port}/test-output-path/{path=**}?user.name={$username}?{**}?test-output-query-name=test-output-query-value"/>
-    </rule>
-
-    <rule name="test-rule-scvreg-all">
-        <match pattern="{*}://{*}:{*}/{**}?{**}"/>
-        <rewrite template="{$serviceScheme[NAMENODE]}://{$serviceHost[NAMENODE]:{$servicePort[NAMENOCE]}/{$servicePath[NAMENODE]}"/>
-    </rule>
-
-    <rule name="test-rule-scvreg-url">
-        <match pattern="{*}://{*}:{*}/{**}?{**}"/>
-        <rewrite template="{$serviceScheme[NAMENODE]}://{$serviceHost[NAMENODE]:{$servicePort[NAMENOCE]}/{$servicePath[NAMENODE]}"/>
-    </rule>
-
-    <rule name="test-rule-scvreg-addr">
-        <match pattern="{*}://{*}:{*}/{**}?{**}"/>
-        <rewrite template="{$serviceUrl[NAMENODE]}"/>
-    </rule>
-
-    <rule name="test-rule-scvreg-addr">
-        <match pattern="{*}://{*}:{*}/{**}?{**}"/>
-        <rewrite template="test-protocol://{$serviceAddr[NAMENODE]}/test-path"/>
-    </rule>
-
-    <rule name="test-rule-html-attribute">
-        <rewrite template="http://someotherhost/stylesheets/pretty.css"/>
-    </rule>
-
-    <rule name="test-rule-html-import-attribute">
-        <rewrite template="{$import[&quot;, url]}/stylesheets/pretty.css&quot;;"/>
-    </rule>
-
-    <!-- HTML Prefix attribute tests, since 0.14.0 -->
-    <rule dir="OUT" name="test-rule-html-prefix-attribute-prefix/1" pattern="'components/{**}?{**}">
-        <rewrite template="{$prefix[&#39;,url]}/zeppelin/components/{**}?{**}"/>
-    </rule>
-
-    <filter name="test-filter-1">
-        <content type="application/json">
-            <apply path="$.url" rule="test-rule-1"/>
-        </content>
-        <content type="*/xml">
-            <apply path="/root/@url" rule="test-rule-1"/>
-            <apply path="/root/url" rule="test-rule-1"/>
-        </content>
-    </filter>
-
-    <filter name="test-filter-2">
-        <content type="application/x-http-headers">
-            <apply path="Location" rule="test-rule-2"/>
-        </content>
-        <content type="application/x-www-form-urlencoded">
-            <apply path="url" rule="test-rule-2"/>
-        </content>
-        <content type="application/json">
-            <apply path="$.url" rule="test-rule-2"/>
-        </content>
-        <content type="*/xml">
-            <apply path="/root/@url" rule="test-rule-2"/>
-            <apply path="/root/url" rule="test-rule-2"/>
-        </content>
-    </filter>
-
-    <filter name="test-filter-3">
-        <content type="*/xml">
-            <apply path="$.url" rule="test-rule-2"/>
-        </content>
-    </filter>
-
-    <filter name="test-filter-4">
-        <content type="*/html">
-            <apply path="pretty.css" rule="test-rule-html-attribute"/>
-        </content>
-    </filter>
-
-    <filter name="test-filter-5">
-        <content type="*/html">
-            <apply path="(@import)+ .*css.*" rule="test-rule-html-import-attribute"/>
-        </content>
-    </filter>
-
-</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/rewrite.xml b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/rewrite.xml
deleted file mode 100644
index c55eb77..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/rewrite.xml
+++ /dev/null
@@ -1,64 +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.
--->
-<rules>
-
-    <rule name="test-rule-frontend-url">
-        <rewrite template="{$frontend[url]}"/>
-    </rule>
-
-    <rule name="test-rule-frontend-scheme">
-        <rewrite template="{$frontend[scheme]}"/>
-    </rule>
-
-    <rule name="test-rule-frontend-host">
-        <rewrite template="{$frontend[host]}"/>
-    </rule>
-
-    <rule name="test-rule-frontend-port">
-        <rewrite template="{$frontend[port]}"/>
-    </rule>
-
-    <rule name="test-rule-frontend-addr">
-        <rewrite template="{$frontend[addr]}"/>
-    </rule>
-
-    <rule name="test-rule-frontend-address">
-        <rewrite template="{$frontend[address]}"/>
-    </rule>
-
-    <rule name="test-rule-frontend-path">
-        <rewrite template="{$frontend[path]}"/>
-    </rule>
-
-    <rule name="test-rule-frontend-topology">
-        <rewrite template="{$frontend[topology]}"/>
-    </rule>
-
-    <filter name="test-filter">
-        <content type="application/json">
-            <apply path="$.url" rule="test-rule-frontend-url"/>
-            <apply path="$.scheme" rule="test-rule-frontend-scheme"/>
-            <apply path="$.host" rule="test-rule-frontend-host"/>
-            <apply path="$.port" rule="test-rule-frontend-port"/>
-            <apply path="$.addr" rule="test-rule-frontend-addr"/>
-            <apply path="$.address" rule="test-rule-frontend-address"/>
-            <apply path="$.path" rule="test-rule-frontend-path"/>
-            <apply path="$.topology" rule="test-rule-frontend-topology"/>
-        </content>
-    </filter>
-
-</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/test-input-body.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/test-input-body.json b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/test-input-body.json
deleted file mode 100644
index ef625d3..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/test-input-body.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
-    "url":"test-input-url",
-    "scheme":"test-input-scheme",
-    "host":"test-input-host",
-    "port":"test-input-port",
-    "addr":"test-input-addr",
-    "address":"test-input-address",
-    "path":"test-input-path",
-    "topology":"test-input-topology"
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/array.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/array.json b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/array.json
deleted file mode 100644
index d42309d..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/array.json
+++ /dev/null
@@ -1,4 +0,0 @@
-[
-  { "obj1-fld1" : "obj1-val1" },
-  { "obj2-fld1" : "obj2-val1" }
-]
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/complex.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/complex.json b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/complex.json
deleted file mode 100644
index b9fcf6b..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/complex.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
-  "test-str": "text",
-  "test-int": 42,
-  "test-flt": 3.1415927,
-  "test-bool": true,
-  "test-null": null,
-  "test-obj-empty": {},
-  "test-ary-empty": [],
-  "test-obj-simple": { "obj-inner-name" : "obj-inner-value" },
-  "test-ary-simple": [ "ary-inner-value" ],
-  "test-obj-nest": { "nested-name": { "obj-inner-name" : "obj-inner-value" } },
-  "test-ary-nest": [["nested-value"]],
-  "test-ary-obj": [ { "obj-inner-name": "obj-inner-value" } ],
-  "test-ary-multi": [ "text", 3.14, { "obj-inner-name": "obj-inner-value" }, [ "arry-inner-value" ] ],
-  "test-obj-multi": { "val":"text", "obj": { "obj-inner-name": "obj-inner-value" }, "ary": [ "arry-inner-value" ] }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/dotted-field-name.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/dotted-field-name.json b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/dotted-field-name.json
deleted file mode 100644
index bb18642..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/dotted-field-name.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
-  "testField": "testField value",
-  "test_field": "test_field value",
-  "test-field": "test-field value",
-  "test.field": "test.field value"
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-array-value.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-array-value.json b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-array-value.json
deleted file mode 100644
index a7f5fb8..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-array-value.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
-  "empty-array" : []
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-object-value.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-object-value.json b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-object-value.json
deleted file mode 100644
index 414f014..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-object-value.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
-  "empty-object" : {}
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/properties.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/properties.json b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/properties.json
deleted file mode 100644
index 841e95d..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/properties.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{ "properties" :
-  [
-    { "property" :
-      { "property-name" : "test-name-1",
-        "property-value" : "test-value-1"
-      }
-    },
-    { "property" :
-      { "property-name" : "test-name-2",
-        "property-value" : "test-value-2"
-      }
-    },
-    { "property" :
-      { "property-name" : "test-name-3",
-        "property-value" : "test-value-3"
-      }
-    }
-  ]
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/simple-values.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/simple-values.json b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/simple-values.json
deleted file mode 100644
index dd38059..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/simple-values.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
-  "test-str": "text",
-  "test-int": 42,
-  "test-flt": 3.1415927,
-  "test-bool": true,
-  "test-null": null
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-attributes.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-attributes.xml b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-attributes.xml
deleted file mode 100644
index ae308d4..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-attributes.xml
+++ /dev/null
@@ -1,22 +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.
--->
-<properties>
-    <property name="test-name-1" value="test-value-1"/>
-    <property name="test-name-2" value="test-value-2"/>
-    <property name="test-name-3" value="test-value-3"/>
-</properties>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-elements.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-elements.xml b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-elements.xml
deleted file mode 100644
index cb27162..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-elements.xml
+++ /dev/null
@@ -1,31 +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.
--->
-<properties>
-    <property>
-        <name>test-name-1</name>
-        <value>test-value-1</value>
-    </property>
-    <property>
-        <name>test-name-2</name>
-        <value>test-value-2</value>
-    </property>
-    <property>
-        <name>test-name-3</name>
-        <value>test-value-3</value>
-    </property>
-</properties>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules-different-scope.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules-different-scope.xml b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules-different-scope.xml
new file mode 100644
index 0000000..6c27476
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules-different-scope.xml
@@ -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.
+-->
+<rules>
+
+    <rule name="test-rule-1" dir="OUT" pattern="*://*:*/**?**">
+        <match pattern="*://{host}:{port}/{path=**}?{**}" />
+        <rewrite template="output-mock-scheme-1://output-mock-host-1:{port}/{path=**}" />
+    </rule>
+
+    <rule name="service-1/test-rule-2" dir="OUT" pattern="*://*:*/**?**">
+        <match pattern="*://{host}:{port}/{path=**}?{**}" />
+        <rewrite template="output-mock-scheme-2://output-mock-host-2:{port}/{path=**}" />
+    </rule>
+
+    <rule name="test-rule-3" dir="OUT" pattern="*://*:*/no-query">
+        <match pattern="{scheme}://{host}:{port}/{path=**}" />
+        <rewrite template="{scheme}://output-mock-host-3:{port}/{path=**}" />
+    </rule>
+
+    <rule name="service-2/test-rule-4" dir="OUT" pattern="*://*:*/no-query">
+        <match pattern="{scheme}://{host}:{port}/{path=**}" />
+        <rewrite template="{scheme}://output-mock-host-4:{port}/{path=**}" />
+    </rule>
+
+    <rule name="service-1/test-rule-5" dir="OUT" pattern="*://*:*/no-query">
+        <match pattern="{scheme}://{host}:{port}/{path=**}" />
+        <rewrite template="{scheme}://output-mock-host-5:{port}/{path=**}" />
+    </rule>
+
+    <rule name="test-rule-6" dir="IN" pattern="*://*:*/**?**">
+        <match pattern="*://{host}:{port}/{path=**}?{**}" />
+        <rewrite template="input-mock-scheme-1://input-mock-host-1:{port}/{path=**}" />
+    </rule>
+
+    <rule name="service-2/test-rule-7" dir="IN" pattern="*://*:*/**?**">
+        <match pattern="*://{host}:{port}/{path=**}?{**}" />
+        <rewrite template="input-mock-scheme-2://input-mock-host-2:{port}/{path=**}" />
+    </rule>
+
+</rules>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules.xml b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules.xml
new file mode 100644
index 0000000..e3be214
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules.xml
@@ -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.
+-->
+<rules>
+
+    <rule name="test-rule-1" dir="OUT" pattern="*://*:*/**?**">
+        <match pattern="*://{host}:{port}/{path=**}?{**}" />
+        <rewrite template="output-mock-scheme-1://output-mock-host-1:{port}/{path=**}" />
+    </rule>
+
+    <rule name="test-rule-2" dir="OUT" pattern="*://*:*/**?**">
+        <match pattern="*://{host}:{port}/{path=**}?{**}" />
+        <rewrite template="output-mock-scheme-2://output-mock-host-2:{port}/{path=**}" />
+    </rule>
+
+    <rule name="test-rule-3" dir="OUT" pattern="*://*:*/no-query">
+        <match pattern="{scheme}://{host}:{port}/{path=**}" />
+        <rewrite template="{scheme}://output-mock-host-3:{port}/{path=**}" />
+    </rule>
+
+    <rule name="test-rule-4" dir="OUT" pattern="*://*:*/no-query">
+        <match pattern="{scheme}://{host}:{port}/{path=**}" />
+        <rewrite template="{scheme}://output-mock-host-4:{port}/{path=**}" />
+    </rule>
+
+</rules>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite.xml b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite.xml
new file mode 100644
index 0000000..84836d5
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite.xml
@@ -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.
+-->
+<rules>
+    <rule name="test-rule-1" url="{scheme=*}://{host=*}:{port=*}/{path=**}">
+        <rewrite param="{scheme}://{host}:{port}/test-output-path"/>
+    </rule>
+
+    <rule dir="OUT" name="test-rule-2">
+        <match pattern="*://*:*/{path=**}?{**}"/>
+        <rewrite template="test-scheme-output://test-host-output:777/test-path-output/{path}?{**}"/>
+    </rule>
+
+    <rule name="test-rule-with-complex-flow" flow="OR">
+        <match pattern="*://*:*/~/{path=**}?{**}">
+            <rewrite template="test-scheme-output://test-host-output:777/test-path-output/test-home/{path}?{**}"/>
+        </match>
+        <match pattern="*://*:*/{path=**}?{**}">
+            <rewrite template="test-scheme-output://test-host-output:42/test-path-output/{path}?{**}"/>
+        </match>
+    </rule>
+
+</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/empty.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/empty.xml b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/empty.xml
new file mode 100644
index 0000000..1e2850e
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/empty.xml
@@ -0,0 +1,16 @@
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one or more
+  contributor license agreements.  See the NOTICE file distributed with
+  this work for additional information regarding copyright ownership.
+  The ASF licenses this file to You under the Apache License, Version 2.0
+  (the "License"); you may not use this file except in compliance with
+  the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+-->
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-complete.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-complete.xml b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-complete.xml
new file mode 100644
index 0000000..54789c5
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-complete.xml
@@ -0,0 +1,33 @@
+<?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.
+-->
+<rules>
+    <filter name="test-filter-name-1">
+        <content type="test-content-type-1/test-content-subtype-1">
+            <apply path="test-apply-path-1" rule="test-apply-rule-1"/>
+            <scope path="test-scope-path-1">
+                <apply path="test-apply-path-2" rule="test-apply-rule-2"/>
+            </scope>
+            <buffer path="test-buffer-path-1">
+                <apply path="test-apply-path-3" rule="test-apply-rule-3"/>
+                <detect path="test-detect-path-1" value="test-detect-value-1">
+                    <apply path="test-apply-path-4" rule="test-apply-rule-4"/>
+                </detect>
+            </buffer>
+        </content>
+    </filter>
+</rules>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-sample.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-sample.xml b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-sample.xml
new file mode 100644
index 0000000..60da1d3
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-sample.xml
@@ -0,0 +1,37 @@
+<?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.
+-->
+<rules>
+    <filter name="WEBHDFS/request">
+        <content type="http/header">
+            <apply target="Location" rule="{rewrite-rule-name}"/>
+            <apply>...</apply>
+        </content>
+        <content type="http/cookie">
+            <apply target="hadoop.auth" rule="{rewrite-rule-name}"/>
+        </content>
+        <content type="*/json" name="{filter-impl-name}">
+            <select node="/config/property">
+                <choice source="name" pattern="YarnNodeManager ">
+                    <apply target="value[2]" rule="{rewrite-rule-name}"/>
+                    <apply target="value[3]" rule="{rewrite-rule-name}"/>
+                </choice>
+                <choice>...</choice>
+            </select>
+        </content>
+    </filter>
+</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-simple.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-simple.xml b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-simple.xml
new file mode 100644
index 0000000..f31de77
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-simple.xml
@@ -0,0 +1,24 @@
+<?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.
+-->
+<rules>
+    <filter name="test-filter-1">
+        <content type="test-content-type-1/test-content-subtype-1">
+            <apply path="test-apply-path-1" rule="test-apply-rule-1"/>
+        </content>
+    </filter>
+</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/invalid.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/invalid.xml b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/invalid.xml
new file mode 100644
index 0000000..6508f3f
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/invalid.xml
@@ -0,0 +1,18 @@
+<?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.
+-->
+</invalid>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/noop.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/noop.xml b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/noop.xml
new file mode 100644
index 0000000..a716582
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/noop.xml
@@ -0,0 +1,18 @@
+<?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.
+-->
+<rules/>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/simple.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/simple.xml b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/simple.xml
new file mode 100644
index 0000000..729a2d4
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/simple.xml
@@ -0,0 +1,19 @@
+<?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.
+-->
+<rules>
+</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest/rewrite.xml b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest/rewrite.xml
new file mode 100644
index 0000000..2e1d5af
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest/rewrite.xml
@@ -0,0 +1,18 @@
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one or more
+  contributor license agreements.  See the NOTICE file distributed with
+  this work for additional information regarding copyright ownership.
+  The ASF licenses this file to You under the Apache License, Version 2.0
+  (the "License"); you may not use this file except in compliance with
+  the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+-->
+<rules>
+</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletFilterTest/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletFilterTest/rewrite.xml b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletFilterTest/rewrite.xml
new file mode 100644
index 0000000..3b77eb3
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletFilterTest/rewrite.xml
@@ -0,0 +1,109 @@
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one or more
+  contributor license agreements.  See the NOTICE file distributed with
+  this work for additional information regarding copyright ownership.
+  The ASF licenses this file to You under the Apache License, Version 2.0
+  (the "License"); you may not use this file except in compliance with
+  the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+-->
+<rules>
+
+    <rule name="test-rule-1" url="{scheme=*}://{host=*}:{port=*}/{path=**}">
+        <rewrite template="{scheme}://{host}:{port}/test-output-path-1"/>
+    </rule>
+
+    <rule name="test-rule-2" url="{scheme=*}://{host=*}:{port=*}/{path=**}">
+        <rewrite template="{scheme}://{host}:{port}/test-output-path-2"/>
+    </rule>
+
+    <rule name="test-rule-username">
+        <match pattern="*://{host}:{port}/{path=**}?{**}"/>
+        <rewrite template="test-output-scheme://{host}:{port}/test-output-path/{path=**}?user.name={$username}?{**}?test-output-query-name=test-output-query-value"/>
+    </rule>
+
+    <rule name="test-rule-scvreg-all">
+        <match pattern="{*}://{*}:{*}/{**}?{**}"/>
+        <rewrite template="{$serviceScheme[NAMENODE]}://{$serviceHost[NAMENODE]:{$servicePort[NAMENOCE]}/{$servicePath[NAMENODE]}"/>
+    </rule>
+
+    <rule name="test-rule-scvreg-url">
+        <match pattern="{*}://{*}:{*}/{**}?{**}"/>
+        <rewrite template="{$serviceScheme[NAMENODE]}://{$serviceHost[NAMENODE]:{$servicePort[NAMENOCE]}/{$servicePath[NAMENODE]}"/>
+    </rule>
+
+    <rule name="test-rule-scvreg-addr">
+        <match pattern="{*}://{*}:{*}/{**}?{**}"/>
+        <rewrite template="{$serviceUrl[NAMENODE]}"/>
+    </rule>
+
+    <rule name="test-rule-scvreg-addr">
+        <match pattern="{*}://{*}:{*}/{**}?{**}"/>
+        <rewrite template="test-protocol://{$serviceAddr[NAMENODE]}/test-path"/>
+    </rule>
+
+    <rule name="test-rule-html-attribute">
+        <rewrite template="http://someotherhost/stylesheets/pretty.css"/>
+    </rule>
+
+    <rule name="test-rule-html-import-attribute">
+        <rewrite template="{$import[&quot;, url]}/stylesheets/pretty.css&quot;;"/>
+    </rule>
+
+    <!-- HTML Prefix attribute tests, since 0.14.0 -->
+    <rule dir="OUT" name="test-rule-html-prefix-attribute-prefix/1" pattern="'components/{**}?{**}">
+        <rewrite template="{$prefix[&#39;,url]}/zeppelin/components/{**}?{**}"/>
+    </rule>
+
+    <filter name="test-filter-1">
+        <content type="application/json">
+            <apply path="$.url" rule="test-rule-1"/>
+        </content>
+        <content type="*/xml">
+            <apply path="/root/@url" rule="test-rule-1"/>
+            <apply path="/root/url" rule="test-rule-1"/>
+        </content>
+    </filter>
+
+    <filter name="test-filter-2">
+        <content type="application/x-http-headers">
+            <apply path="Location" rule="test-rule-2"/>
+        </content>
+        <content type="application/x-www-form-urlencoded">
+            <apply path="url" rule="test-rule-2"/>
+        </content>
+        <content type="application/json">
+            <apply path="$.url" rule="test-rule-2"/>
+        </content>
+        <content type="*/xml">
+            <apply path="/root/@url" rule="test-rule-2"/>
+            <apply path="/root/url" rule="test-rule-2"/>
+        </content>
+    </filter>
+
+    <filter name="test-filter-3">
+        <content type="*/xml">
+            <apply path="$.url" rule="test-rule-2"/>
+        </content>
+    </filter>
+
+    <filter name="test-filter-4">
+        <content type="*/html">
+            <apply path="pretty.css" rule="test-rule-html-attribute"/>
+        </content>
+    </filter>
+
+    <filter name="test-filter-5">
+        <content type="*/html">
+            <apply path="(@import)+ .*css.*" rule="test-rule-html-import-attribute"/>
+        </content>
+    </filter>
+
+</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/rewrite.xml b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/rewrite.xml
new file mode 100644
index 0000000..c55eb77
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/rewrite.xml
@@ -0,0 +1,64 @@
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one or more
+  contributor license agreements.  See the NOTICE file distributed with
+  this work for additional information regarding copyright ownership.
+  The ASF licenses this file to You under the Apache License, Version 2.0
+  (the "License"); you may not use this file except in compliance with
+  the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+-->
+<rules>
+
+    <rule name="test-rule-frontend-url">
+        <rewrite template="{$frontend[url]}"/>
+    </rule>
+
+    <rule name="test-rule-frontend-scheme">
+        <rewrite template="{$frontend[scheme]}"/>
+    </rule>
+
+    <rule name="test-rule-frontend-host">
+        <rewrite template="{$frontend[host]}"/>
+    </rule>
+
+    <rule name="test-rule-frontend-port">
+        <rewrite template="{$frontend[port]}"/>
+    </rule>
+
+    <rule name="test-rule-frontend-addr">
+        <rewrite template="{$frontend[addr]}"/>
+    </rule>
+
+    <rule name="test-rule-frontend-address">
+        <rewrite template="{$frontend[address]}"/>
+    </rule>
+
+    <rule name="test-rule-frontend-path">
+        <rewrite template="{$frontend[path]}"/>
+    </rule>
+
+    <rule name="test-rule-frontend-topology">
+        <rewrite template="{$frontend[topology]}"/>
+    </rule>
+
+    <filter name="test-filter">
+        <content type="application/json">
+            <apply path="$.url" rule="test-rule-frontend-url"/>
+            <apply path="$.scheme" rule="test-rule-frontend-scheme"/>
+            <apply path="$.host" rule="test-rule-frontend-host"/>
+            <apply path="$.port" rule="test-rule-frontend-port"/>
+            <apply path="$.addr" rule="test-rule-frontend-addr"/>
+            <apply path="$.address" rule="test-rule-frontend-address"/>
+            <apply path="$.path" rule="test-rule-frontend-path"/>
+            <apply path="$.topology" rule="test-rule-frontend-topology"/>
+        </content>
+    </filter>
+
+</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/test-input-body.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/test-input-body.json b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/test-input-body.json
new file mode 100644
index 0000000..ef625d3
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest/test-input-body.json
@@ -0,0 +1,10 @@
+{
+    "url":"test-input-url",
+    "scheme":"test-input-scheme",
+    "host":"test-input-host",
+    "port":"test-input-port",
+    "addr":"test-input-addr",
+    "address":"test-input-address",
+    "path":"test-input-path",
+    "topology":"test-input-topology"
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/array.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/array.json b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/array.json
new file mode 100644
index 0000000..d42309d
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/array.json
@@ -0,0 +1,4 @@
+[
+  { "obj1-fld1" : "obj1-val1" },
+  { "obj2-fld1" : "obj2-val1" }
+]
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/complex.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/complex.json b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/complex.json
new file mode 100644
index 0000000..b9fcf6b
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/complex.json
@@ -0,0 +1,16 @@
+{
+  "test-str": "text",
+  "test-int": 42,
+  "test-flt": 3.1415927,
+  "test-bool": true,
+  "test-null": null,
+  "test-obj-empty": {},
+  "test-ary-empty": [],
+  "test-obj-simple": { "obj-inner-name" : "obj-inner-value" },
+  "test-ary-simple": [ "ary-inner-value" ],
+  "test-obj-nest": { "nested-name": { "obj-inner-name" : "obj-inner-value" } },
+  "test-ary-nest": [["nested-value"]],
+  "test-ary-obj": [ { "obj-inner-name": "obj-inner-value" } ],
+  "test-ary-multi": [ "text", 3.14, { "obj-inner-name": "obj-inner-value" }, [ "arry-inner-value" ] ],
+  "test-obj-multi": { "val":"text", "obj": { "obj-inner-name": "obj-inner-value" }, "ary": [ "arry-inner-value" ] }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/dotted-field-name.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/dotted-field-name.json b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/dotted-field-name.json
new file mode 100644
index 0000000..bb18642
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/dotted-field-name.json
@@ -0,0 +1,6 @@
+{
+  "testField": "testField value",
+  "test_field": "test_field value",
+  "test-field": "test-field value",
+  "test.field": "test.field value"
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-array-value.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-array-value.json b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-array-value.json
new file mode 100644
index 0000000..a7f5fb8
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-array-value.json
@@ -0,0 +1,3 @@
+{
+  "empty-array" : []
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-object-value.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-object-value.json b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-object-value.json
new file mode 100644
index 0000000..414f014
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/empty-object-value.json
@@ -0,0 +1,3 @@
+{
+  "empty-object" : {}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/properties.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/properties.json b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/properties.json
new file mode 100644
index 0000000..841e95d
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/properties.json
@@ -0,0 +1,19 @@
+{ "properties" :
+  [
+    { "property" :
+      { "property-name" : "test-name-1",
+        "property-value" : "test-value-1"
+      }
+    },
+    { "property" :
+      { "property-name" : "test-name-2",
+        "property-value" : "test-value-2"
+      }
+    },
+    { "property" :
+      { "property-name" : "test-name-3",
+        "property-value" : "test-value-3"
+      }
+    }
+  ]
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/simple-values.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/simple-values.json b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/simple-values.json
new file mode 100644
index 0000000..dd38059
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest/simple-values.json
@@ -0,0 +1,7 @@
+{
+  "test-str": "text",
+  "test-int": 42,
+  "test-flt": 3.1415927,
+  "test-bool": true,
+  "test-null": null
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-attributes.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-attributes.xml b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-attributes.xml
new file mode 100644
index 0000000..ae308d4
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-attributes.xml
@@ -0,0 +1,22 @@
+<?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.
+-->
+<properties>
+    <property name="test-name-1" value="test-value-1"/>
+    <property name="test-name-2" value="test-value-2"/>
+    <property name="test-name-3" value="test-value-3"/>
+</properties>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-elements.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-elements.xml b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-elements.xml
new file mode 100644
index 0000000..cb27162
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/resources/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest/properties-elements.xml
@@ -0,0 +1,31 @@
+<?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.
+-->
+<properties>
+    <property>
+        <name>test-name-1</name>
+        <value>test-value-1</value>
+    </property>
+    <property>
+        <name>test-name-2</name>
+        <value>test-value-2</value>
+    </property>
+    <property>
+        <name>test-name-3</name>
+        <value>test-value-3</value>
+    </property>
+</properties>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authc-anon/src/main/java/org/apache/hadoop/gateway/deploy/AnonymousAuthDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authc-anon/src/main/java/org/apache/hadoop/gateway/deploy/AnonymousAuthDeploymentContributor.java b/gateway-provider-security-authc-anon/src/main/java/org/apache/hadoop/gateway/deploy/AnonymousAuthDeploymentContributor.java
deleted file mode 100755
index b49643d..0000000
--- a/gateway-provider-security-authc-anon/src/main/java/org/apache/hadoop/gateway/deploy/AnonymousAuthDeploymentContributor.java
+++ /dev/null
@@ -1,65 +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.hadoop.gateway.deploy;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-public class AnonymousAuthDeploymentContributor extends ProviderDeploymentContributorBase {
-
-  private static final String ROLE = "authentication";
-  private static final String NAME = "Anonymous";
-
-  private static final String FILTER_CLASSNAME = "org.apache.hadoop.gateway.filter.AnonymousAuthFilter";
-
-  @Override
-  public String getRole() {
-    return ROLE;
-  }
-
-  @Override
-  public String getName() {
-    return NAME;
-  }
-
-  @Override
-  public void initializeContribution(DeploymentContext context) {
-    super.initializeContribution(context);
-  }
-
-  @Override
-  public void contributeFilter(DeploymentContext context, Provider provider, Service service, 
-      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
-    // blindly add all the provider params as filter init params
-    if (params == null) {
-      params = new ArrayList<>();
-    }
-    Map<String, String> providerParams = provider.getParams();
-    for(Entry<String, String> entry : providerParams.entrySet()) {
-      params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
-    }
-    resource.addFilter().name( getName() ).role( getRole() ).impl(FILTER_CLASSNAME).params( params );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authc-anon/src/main/java/org/apache/hadoop/gateway/filter/AnonymousAuthFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authc-anon/src/main/java/org/apache/hadoop/gateway/filter/AnonymousAuthFilter.java b/gateway-provider-security-authc-anon/src/main/java/org/apache/hadoop/gateway/filter/AnonymousAuthFilter.java
deleted file mode 100755
index 59b64fd..0000000
--- a/gateway-provider-security-authc-anon/src/main/java/org/apache/hadoop/gateway/filter/AnonymousAuthFilter.java
+++ /dev/null
@@ -1,101 +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.hadoop.gateway.filter;
-
-import org.apache.hadoop.gateway.audit.api.Action;
-import org.apache.hadoop.gateway.audit.api.ActionOutcome;
-import org.apache.hadoop.gateway.audit.api.AuditService;
-import org.apache.hadoop.gateway.audit.api.AuditServiceFactory;
-import org.apache.hadoop.gateway.audit.api.Auditor;
-import org.apache.hadoop.gateway.audit.api.ResourceType;
-import org.apache.hadoop.gateway.audit.log4j.audit.AuditConstants;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-
-import java.io.IOException;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-
-import javax.security.auth.Subject;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-public class AnonymousAuthFilter implements Filter {
-  private static AuditService auditService = AuditServiceFactory.getAuditService();
-  private static Auditor auditor = auditService.getAuditor(
-      AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
-      AuditConstants.KNOX_COMPONENT_NAME );
-
-  @Override
-  public void init(FilterConfig filterConfig) throws ServletException {
-
-  }
-
-  @Override
-  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
-    HttpServletRequest httpRequest = (HttpServletRequest)request;
-    String principal = httpRequest.getRemoteUser();
-    if (principal == null) {
-      principal = "anonymous";
-    }
-    Subject subject = new Subject();
-    subject.getPrincipals().add(new PrimaryPrincipal(principal));
-    auditService.getContext().setUsername( principal ); //KM: Audit Fix
-    String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
-    auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
-    continueWithEstablishedSecurityContext(subject, (HttpServletRequest)request, (HttpServletResponse)response, filterChain);
-  }
-
-  private void continueWithEstablishedSecurityContext(Subject subject, final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
-    try {
-      Subject.doAs(
-          subject,
-          new PrivilegedExceptionAction<Object>() {
-            @Override
-            public Object run() throws Exception {
-              chain.doFilter(request, response);
-              return null;
-            }
-          }
-      );
-    }
-    catch (PrivilegedActionException e) {
-      Throwable t = e.getCause();
-      if (t instanceof IOException) {
-        throw (IOException) t;
-      }
-      else if (t instanceof ServletException) {
-        throw (ServletException) t;
-      }
-      else {
-        throw new ServletException(t);
-      }
-    }
-  }
-
-
-  @Override
-  public void destroy() {
-
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authc-anon/src/main/java/org/apache/knox/gateway/deploy/AnonymousAuthDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authc-anon/src/main/java/org/apache/knox/gateway/deploy/AnonymousAuthDeploymentContributor.java b/gateway-provider-security-authc-anon/src/main/java/org/apache/knox/gateway/deploy/AnonymousAuthDeploymentContributor.java
new file mode 100755
index 0000000..e0c0609
--- /dev/null
+++ b/gateway-provider-security-authc-anon/src/main/java/org/apache/knox/gateway/deploy/AnonymousAuthDeploymentContributor.java
@@ -0,0 +1,65 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.deploy;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+public class AnonymousAuthDeploymentContributor extends ProviderDeploymentContributorBase {
+
+  private static final String ROLE = "authentication";
+  private static final String NAME = "Anonymous";
+
+  private static final String FILTER_CLASSNAME = "AnonymousAuthFilter";
+
+  @Override
+  public String getRole() {
+    return ROLE;
+  }
+
+  @Override
+  public String getName() {
+    return NAME;
+  }
+
+  @Override
+  public void initializeContribution(DeploymentContext context) {
+    super.initializeContribution(context);
+  }
+
+  @Override
+  public void contributeFilter(DeploymentContext context, Provider provider, Service service,
+      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
+    // blindly add all the provider params as filter init params
+    if (params == null) {
+      params = new ArrayList<>();
+    }
+    Map<String, String> providerParams = provider.getParams();
+    for(Entry<String, String> entry : providerParams.entrySet()) {
+      params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
+    }
+    resource.addFilter().name( getName() ).role( getRole() ).impl(FILTER_CLASSNAME).params( params );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authc-anon/src/main/java/org/apache/knox/gateway/filter/AnonymousAuthFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authc-anon/src/main/java/org/apache/knox/gateway/filter/AnonymousAuthFilter.java b/gateway-provider-security-authc-anon/src/main/java/org/apache/knox/gateway/filter/AnonymousAuthFilter.java
new file mode 100755
index 0000000..0d002dd
--- /dev/null
+++ b/gateway-provider-security-authc-anon/src/main/java/org/apache/knox/gateway/filter/AnonymousAuthFilter.java
@@ -0,0 +1,101 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter;
+
+import org.apache.knox.gateway.audit.api.Action;
+import org.apache.knox.gateway.audit.api.ActionOutcome;
+import org.apache.knox.gateway.audit.api.AuditService;
+import org.apache.knox.gateway.audit.api.AuditServiceFactory;
+import org.apache.knox.gateway.audit.api.Auditor;
+import org.apache.knox.gateway.audit.api.ResourceType;
+import org.apache.knox.gateway.audit.log4j.audit.AuditConstants;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+
+import java.io.IOException;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+
+import javax.security.auth.Subject;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+public class AnonymousAuthFilter implements Filter {
+  private static AuditService auditService = AuditServiceFactory.getAuditService();
+  private static Auditor auditor = auditService.getAuditor(
+      AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
+      AuditConstants.KNOX_COMPONENT_NAME );
+
+  @Override
+  public void init(FilterConfig filterConfig) throws ServletException {
+
+  }
+
+  @Override
+  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
+    HttpServletRequest httpRequest = (HttpServletRequest)request;
+    String principal = httpRequest.getRemoteUser();
+    if (principal == null) {
+      principal = "anonymous";
+    }
+    Subject subject = new Subject();
+    subject.getPrincipals().add(new PrimaryPrincipal(principal));
+    auditService.getContext().setUsername( principal ); //KM: Audit Fix
+    String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
+    auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
+    continueWithEstablishedSecurityContext(subject, (HttpServletRequest)request, (HttpServletResponse)response, filterChain);
+  }
+
+  private void continueWithEstablishedSecurityContext(Subject subject, final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
+    try {
+      Subject.doAs(
+          subject,
+          new PrivilegedExceptionAction<Object>() {
+            @Override
+            public Object run() throws Exception {
+              chain.doFilter(request, response);
+              return null;
+            }
+          }
+      );
+    }
+    catch (PrivilegedActionException e) {
+      Throwable t = e.getCause();
+      if (t instanceof IOException) {
+        throw (IOException) t;
+      }
+      else if (t instanceof ServletException) {
+        throw (ServletException) t;
+      }
+      else {
+        throw new ServletException(t);
+      }
+    }
+  }
+
+
+  @Override
+  public void destroy() {
+
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authc-anon/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authc-anon/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-authc-anon/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100755
index 99f1edf..0000000
--- a/gateway-provider-security-authc-anon/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.deploy.AnonymousAuthDeploymentContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authc-anon/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authc-anon/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-authc-anon/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100755
index 0000000..df2b225
--- /dev/null
+++ b/gateway-provider-security-authc-anon/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.deploy.AnonymousAuthDeploymentContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authc-anon/src/test/java/org/apache/hadoop/gateway/deploy/AnonymousAuthDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authc-anon/src/test/java/org/apache/hadoop/gateway/deploy/AnonymousAuthDeploymentContributorTest.java b/gateway-provider-security-authc-anon/src/test/java/org/apache/hadoop/gateway/deploy/AnonymousAuthDeploymentContributorTest.java
deleted file mode 100644
index 38e25a8..0000000
--- a/gateway-provider-security-authc-anon/src/test/java/org/apache/hadoop/gateway/deploy/AnonymousAuthDeploymentContributorTest.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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.deploy;
-
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class AnonymousAuthDeploymentContributorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( ProviderDeploymentContributor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof AnonymousAuthDeploymentContributor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + AnonymousAuthDeploymentContributor.class.getName() + " via service loader." );
-  }
-
-}


[48/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/SimpleLdapDirectoryServer.java
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/SimpleLdapDirectoryServer.java b/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/SimpleLdapDirectoryServer.java
new file mode 100644
index 0000000..9f59e9b
--- /dev/null
+++ b/gateway-demo-ldap/src/main/java/org/apache/knox/gateway/security/ldap/SimpleLdapDirectoryServer.java
@@ -0,0 +1,124 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.security.ldap;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.directory.api.ldap.model.entry.DefaultModification;
+import org.apache.directory.api.ldap.model.entry.ModificationOperation;
+import org.apache.directory.api.ldap.model.exception.LdapException;
+import org.apache.directory.api.ldap.model.name.Dn;
+import org.apache.directory.server.core.api.CoreSession;
+import org.apache.directory.server.core.api.DirectoryService;
+import org.apache.directory.server.core.api.partition.Partition;
+import org.apache.directory.server.core.factory.DirectoryServiceFactory;
+import org.apache.directory.server.ldap.LdapServer;
+import org.apache.directory.server.protocol.shared.store.LdifFileLoader;
+import org.apache.directory.server.protocol.shared.transport.TcpTransport;
+import org.apache.directory.server.protocol.shared.transport.Transport;
+import org.apache.log4j.PropertyConfigurator;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.net.ServerSocket;
+import java.util.UUID;
+
+public class SimpleLdapDirectoryServer {
+
+  private DirectoryServiceFactory factory;
+
+  private DirectoryService service;
+
+  private LdapServer server;
+
+  public SimpleLdapDirectoryServer( String rootDn, File usersLdif, Transport... transports ) throws Exception {
+    if( !usersLdif.exists() ) {
+      throw new FileNotFoundException( usersLdif.getAbsolutePath() );
+    }
+
+    factory = new SimpleDirectoryServiceFactory();
+    factory.init( UUID.randomUUID().toString() );
+    service = factory.getDirectoryService();
+
+    enabledPosixSchema( service );
+
+    Partition partition = factory.getPartitionFactory().createPartition(
+        service.getSchemaManager(), service.getDnFactory(), "users", rootDn, 500,
+        service.getInstanceLayout().getInstanceDirectory() );
+    service.addPartition( partition );
+
+    CoreSession session = service.getAdminSession();
+    LdifFileLoader lfl = new LdifFileLoader( session, usersLdif, null );
+    lfl.execute();
+
+    server = new LdapServer();
+    server.setTransports( transports );
+    server.setDirectoryService( service );
+  }
+
+  private static void enabledPosixSchema( DirectoryService service ) throws LdapException {
+    service.getSchemaManager().getLoadedSchema( "nis" ).enable();
+    service.getAdminSession().modify(
+        new Dn( "cn=nis,ou=schema" ),
+        new DefaultModification( ModificationOperation.REPLACE_ATTRIBUTE, "m-disabled", "FALSE" ) );
+  }
+
+  public void start() throws Exception {
+    service.startup();
+    server.start();
+  }
+
+  public void stop( boolean clean ) throws Exception {
+    server.stop();
+    service.shutdown();
+    if( clean ) {
+      FileUtils.deleteDirectory( service.getInstanceLayout().getInstanceDirectory() );
+    }
+  }
+
+  public static void main( String[] args ) throws Exception {
+    PropertyConfigurator.configure( System.getProperty( "log4j.configuration" ) );
+
+    SimpleLdapDirectoryServer ldap;
+
+    File file;
+    if ( args.length < 1 ) {
+      file = new File( "conf/users.ldif" );
+    } else {
+      File dir = new File( args[0] );
+      if( !dir.exists() || !dir.isDirectory() ) {
+        throw new FileNotFoundException( dir.getAbsolutePath() );
+      }
+      file = new File( dir, "users.ldif" );
+    }
+
+    if( !file.exists() || !file.canRead() ) {
+      throw new FileNotFoundException( file.getAbsolutePath() );
+    }
+
+    int port = 33389;
+
+    // Make sure the port is free.
+    ServerSocket socket = new ServerSocket( port );
+    socket.close();
+
+    TcpTransport transport = new TcpTransport( port );
+    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", file, transport );
+    ldap.start();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-demo-ldap/src/test/java/org/apache/hadoop/gateway/security/ldap/SimpleLdapServerTest.java
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap/src/test/java/org/apache/hadoop/gateway/security/ldap/SimpleLdapServerTest.java b/gateway-demo-ldap/src/test/java/org/apache/hadoop/gateway/security/ldap/SimpleLdapServerTest.java
deleted file mode 100644
index 33a367e..0000000
--- a/gateway-demo-ldap/src/test/java/org/apache/hadoop/gateway/security/ldap/SimpleLdapServerTest.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.hadoop.gateway.security.ldap;
-
-import org.apache.directory.api.ldap.model.exception.LdapAuthenticationException;
-import org.apache.directory.api.ldap.model.exception.LdapException;
-import org.apache.directory.ldap.client.api.LdapConnection;
-import org.apache.directory.ldap.client.api.LdapNetworkConnection;
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
-import org.apache.directory.server.protocol.shared.transport.Transport;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.ServerSocket;
-
-import static org.junit.Assert.fail;
-
-public class SimpleLdapServerTest {
-
-  private static int port;
-  private static File ldifFile;
-  private static TcpTransport ldapTransport;
-  private static SimpleLdapDirectoryServer ldap;
-
-  @BeforeClass
-  public static void setup() throws Exception {
-    ldifFile = new File( ClassLoader.getSystemResource( "users.ldif" ).toURI() );
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", ldifFile, ldapTransport );
-    ldap.start();
-    port = ldapTransport.getAcceptor().getLocalAddress().getPort();
-  }
-
-  @AfterClass
-  public static void cleanup() throws Exception {
-    if( ldap != null ) {
-      ldap.stop( true );
-    }
-  }
-
-  @Test
-  public void testBind() throws LdapException, IOException {
-    LdapConnection connection;
-
-    connection = new LdapNetworkConnection( "localhost", port );
-    try {
-      connection.bind( "uid=guest,ou=people,dc=hadoop,dc=apache,dc=org", "guest-password" );
-    } finally {
-      connection.close();
-    }
-
-    connection = new LdapNetworkConnection( "localhost", port );
-    try {
-      connection.bind( "uid=nobody,ou=people,dc=hadoop,dc=apache,dc=org", "guest-password" );
-      fail( "Expected LdapAuthenticationException" );
-    } catch ( LdapAuthenticationException e ) {
-      // Expected
-    } finally {
-      connection.close();
-    }
-
-    connection = new LdapNetworkConnection( "localhost", port );
-    try {
-      connection.bind( "uid=guest,ou=people,dc=hadoop,dc=apache,dc=org", "wrong-password" );
-      fail( "Expected LdapAuthenticationException" );
-    } catch ( LdapAuthenticationException e ) {
-      // Expected
-    } finally {
-      connection.close();
-    }
-
-  }
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-demo-ldap/src/test/java/org/apache/knox/gateway/security/ldap/SimpleLdapServerTest.java
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap/src/test/java/org/apache/knox/gateway/security/ldap/SimpleLdapServerTest.java b/gateway-demo-ldap/src/test/java/org/apache/knox/gateway/security/ldap/SimpleLdapServerTest.java
new file mode 100644
index 0000000..8f20154
--- /dev/null
+++ b/gateway-demo-ldap/src/test/java/org/apache/knox/gateway/security/ldap/SimpleLdapServerTest.java
@@ -0,0 +1,91 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT 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.knox.gateway.security.ldap;
+
+import org.apache.directory.api.ldap.model.exception.LdapAuthenticationException;
+import org.apache.directory.api.ldap.model.exception.LdapException;
+import org.apache.directory.ldap.client.api.LdapConnection;
+import org.apache.directory.ldap.client.api.LdapNetworkConnection;
+import org.apache.directory.server.protocol.shared.transport.TcpTransport;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.IOException;
+
+import static org.junit.Assert.fail;
+
+public class SimpleLdapServerTest {
+
+  private static int port;
+  private static File ldifFile;
+  private static TcpTransport ldapTransport;
+  private static SimpleLdapDirectoryServer ldap;
+
+  @BeforeClass
+  public static void setup() throws Exception {
+    ldifFile = new File( ClassLoader.getSystemResource( "users.ldif" ).toURI() );
+    ldapTransport = new TcpTransport( 0 );
+    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", ldifFile, ldapTransport );
+    ldap.start();
+    port = ldapTransport.getAcceptor().getLocalAddress().getPort();
+  }
+
+  @AfterClass
+  public static void cleanup() throws Exception {
+    if( ldap != null ) {
+      ldap.stop( true );
+    }
+  }
+
+  @Test
+  public void testBind() throws LdapException, IOException {
+    LdapConnection connection;
+
+    connection = new LdapNetworkConnection( "localhost", port );
+    try {
+      connection.bind( "uid=guest,ou=people,dc=hadoop,dc=apache,dc=org", "guest-password" );
+    } finally {
+      connection.close();
+    }
+
+    connection = new LdapNetworkConnection( "localhost", port );
+    try {
+      connection.bind( "uid=nobody,ou=people,dc=hadoop,dc=apache,dc=org", "guest-password" );
+      fail( "Expected LdapAuthenticationException" );
+    } catch ( LdapAuthenticationException e ) {
+      // Expected
+    } finally {
+      connection.close();
+    }
+
+    connection = new LdapNetworkConnection( "localhost", port );
+    try {
+      connection.bind( "uid=guest,ou=people,dc=hadoop,dc=apache,dc=org", "wrong-password" );
+      fail( "Expected LdapAuthenticationException" );
+    } catch ( LdapAuthenticationException e ) {
+      // Expected
+    } finally {
+      connection.close();
+    }
+
+  }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-log4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/log4j/Log4jMessageLogger.java
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-log4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/log4j/Log4jMessageLogger.java b/gateway-i18n-logging-log4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/log4j/Log4jMessageLogger.java
deleted file mode 100644
index f027d9f..0000000
--- a/gateway-i18n-logging-log4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/log4j/Log4jMessageLogger.java
+++ /dev/null
@@ -1,87 +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.hadoop.gateway.i18n.messages.loggers.log4j;
-
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.MessageLogger;
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.apache.log4j.spi.LocationInfo;
-import org.apache.log4j.spi.LoggingEvent;
-import org.apache.log4j.spi.ThrowableInformation;
-
-public class Log4jMessageLogger implements MessageLogger {
-
-  private static String CLASS_NAME = Log4jMessageLogger.class.getName();
-
-  private Logger logger;
-
-  Log4jMessageLogger( Logger logger ) {
-    this.logger = logger;
-  }
-
-  @Override
-  public final boolean isLoggable( final MessageLevel level ) {
-    return logger.isEnabledFor( toLevel( level ) );
-  }
-
-  @Override
-  public final void log( final StackTraceElement caller, final MessageLevel messageLevel, final String messageId, final String messageText, final Throwable thrown ) {
-    LoggingEvent event = new LoggingEvent(
-        /* String fqnOfCategoryClass */ CLASS_NAME,
-        /* Category logger */ logger,
-        /* long timeStamp */ System.currentTimeMillis(),
-        /* Level level */ toLevel( messageLevel ),
-        /* Object message */ messageText,
-        /* String threadName */ Thread.currentThread().getName(),
-        /* ThrowableInformation throwable */ toThrownInformation( thrown ),
-        /* String ndc */ null,
-        /* LocationInfo info */ toLocationInfo( caller ),
-        /* java.util.Map properties */ null );
-    logger.callAppenders( event );
-  }
-
-  private static final ThrowableInformation toThrownInformation( final Throwable thrown ) {
-    ThrowableInformation info = null;
-    if( thrown != null ) {
-      info = new ThrowableInformation( thrown );
-    }
-    return info;
-  }
-
-  private static final LocationInfo toLocationInfo( final StackTraceElement caller ) {
-    LocationInfo info = null;
-    if( caller != null ) {
-        info = new LocationInfo( caller.getFileName(), caller.getClassName(), caller.getMethodName(), Integer.toString(caller.getLineNumber()) );
-    }
-    return info;
-  }
-
-  private static final Level toLevel( final MessageLevel level ) {
-    switch( level ) {
-      case FATAL: return Level.FATAL;
-      case ERROR: return Level.ERROR;
-      case WARN: return Level.WARN;
-      case INFO: return Level.INFO;
-      case DEBUG: return Level.DEBUG;
-      case TRACE: return Level.TRACE;
-      default: return Level.OFF;
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-log4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-log4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactory.java b/gateway-i18n-logging-log4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactory.java
deleted file mode 100644
index 664053a..0000000
--- a/gateway-i18n-logging-log4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactory.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.i18n.messages.loggers.log4j;
-
-import org.apache.hadoop.gateway.i18n.messages.MessageLogger;
-import org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory;
-import org.apache.log4j.Logger;
-
-public class Log4jMessageLoggerFactory implements MessageLoggerFactory {
-
-  @Override
-  public MessageLogger getLogger( String name ) {
-    return new Log4jMessageLogger( Logger.getLogger( name ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-log4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/log4j/Log4jMessageLogger.java
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-log4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/log4j/Log4jMessageLogger.java b/gateway-i18n-logging-log4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/log4j/Log4jMessageLogger.java
new file mode 100644
index 0000000..4c66e5c
--- /dev/null
+++ b/gateway-i18n-logging-log4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/log4j/Log4jMessageLogger.java
@@ -0,0 +1,87 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.messages.loggers.log4j;
+
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.MessageLogger;
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.apache.log4j.spi.LocationInfo;
+import org.apache.log4j.spi.LoggingEvent;
+import org.apache.log4j.spi.ThrowableInformation;
+
+public class Log4jMessageLogger implements MessageLogger {
+
+  private static String CLASS_NAME = Log4jMessageLogger.class.getName();
+
+  private Logger logger;
+
+  Log4jMessageLogger( Logger logger ) {
+    this.logger = logger;
+  }
+
+  @Override
+  public final boolean isLoggable( final MessageLevel level ) {
+    return logger.isEnabledFor( toLevel( level ) );
+  }
+
+  @Override
+  public final void log( final StackTraceElement caller, final MessageLevel messageLevel, final String messageId, final String messageText, final Throwable thrown ) {
+    LoggingEvent event = new LoggingEvent(
+        /* String fqnOfCategoryClass */ CLASS_NAME,
+        /* Category logger */ logger,
+        /* long timeStamp */ System.currentTimeMillis(),
+        /* Level level */ toLevel( messageLevel ),
+        /* Object message */ messageText,
+        /* String threadName */ Thread.currentThread().getName(),
+        /* ThrowableInformation throwable */ toThrownInformation( thrown ),
+        /* String ndc */ null,
+        /* LocationInfo info */ toLocationInfo( caller ),
+        /* java.util.Map properties */ null );
+    logger.callAppenders( event );
+  }
+
+  private static final ThrowableInformation toThrownInformation( final Throwable thrown ) {
+    ThrowableInformation info = null;
+    if( thrown != null ) {
+      info = new ThrowableInformation( thrown );
+    }
+    return info;
+  }
+
+  private static final LocationInfo toLocationInfo( final StackTraceElement caller ) {
+    LocationInfo info = null;
+    if( caller != null ) {
+        info = new LocationInfo( caller.getFileName(), caller.getClassName(), caller.getMethodName(), Integer.toString(caller.getLineNumber()) );
+    }
+    return info;
+  }
+
+  private static final Level toLevel( final MessageLevel level ) {
+    switch( level ) {
+      case FATAL: return Level.FATAL;
+      case ERROR: return Level.ERROR;
+      case WARN: return Level.WARN;
+      case INFO: return Level.INFO;
+      case DEBUG: return Level.DEBUG;
+      case TRACE: return Level.TRACE;
+      default: return Level.OFF;
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-log4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-log4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactory.java b/gateway-i18n-logging-log4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactory.java
new file mode 100644
index 0000000..5a908cb
--- /dev/null
+++ b/gateway-i18n-logging-log4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactory.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.messages.loggers.log4j;
+
+import org.apache.knox.gateway.i18n.messages.MessageLogger;
+import org.apache.knox.gateway.i18n.messages.MessageLoggerFactory;
+import org.apache.log4j.Logger;
+
+public class Log4jMessageLoggerFactory implements MessageLoggerFactory {
+
+  @Override
+  public MessageLogger getLogger( String name ) {
+    return new Log4jMessageLogger( Logger.getLogger( name ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-log4j/src/main/resources/META-INF/services/org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-log4j/src/main/resources/META-INF/services/org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory b/gateway-i18n-logging-log4j/src/main/resources/META-INF/services/org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory
deleted file mode 100644
index 988ecd6..0000000
--- a/gateway-i18n-logging-log4j/src/main/resources/META-INF/services/org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.i18n.messages.loggers.log4j.Log4jMessageLoggerFactory
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-log4j/src/main/resources/META-INF/services/org.apache.knox.gateway.i18n.messages.MessageLoggerFactory
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-log4j/src/main/resources/META-INF/services/org.apache.knox.gateway.i18n.messages.MessageLoggerFactory b/gateway-i18n-logging-log4j/src/main/resources/META-INF/services/org.apache.knox.gateway.i18n.messages.MessageLoggerFactory
new file mode 100644
index 0000000..ba8d704
--- /dev/null
+++ b/gateway-i18n-logging-log4j/src/main/resources/META-INF/services/org.apache.knox.gateway.i18n.messages.MessageLoggerFactory
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.i18n.messages.loggers.log4j.Log4jMessageLoggerFactory
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-log4j/src/test/java/org/apache/hadoop/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactoryTest.java
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-log4j/src/test/java/org/apache/hadoop/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactoryTest.java b/gateway-i18n-logging-log4j/src/test/java/org/apache/hadoop/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactoryTest.java
deleted file mode 100644
index 2d97f27..0000000
--- a/gateway-i18n-logging-log4j/src/test/java/org/apache/hadoop/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactoryTest.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.hadoop.gateway.i18n.messages.loggers.log4j;
-
-import org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class Log4jMessageLoggerFactoryTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( MessageLoggerFactory.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof Log4jMessageLoggerFactory ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + Log4jMessageLoggerFactory.class.getName() + " via service loader." );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-log4j/src/test/java/org/apache/knox/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactoryTest.java
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-log4j/src/test/java/org/apache/knox/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactoryTest.java b/gateway-i18n-logging-log4j/src/test/java/org/apache/knox/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactoryTest.java
new file mode 100644
index 0000000..26d25e8
--- /dev/null
+++ b/gateway-i18n-logging-log4j/src/test/java/org/apache/knox/gateway/i18n/messages/loggers/log4j/Log4jMessageLoggerFactoryTest.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.knox.gateway.i18n.messages.loggers.log4j;
+
+import org.apache.knox.gateway.i18n.messages.MessageLoggerFactory;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class Log4jMessageLoggerFactoryTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( MessageLoggerFactory.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof Log4jMessageLoggerFactory ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + Log4jMessageLoggerFactory.class.getName() + " via service loader." );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-sl4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLogger.java
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-sl4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLogger.java b/gateway-i18n-logging-sl4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLogger.java
deleted file mode 100644
index c129500..0000000
--- a/gateway-i18n-logging-sl4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLogger.java
+++ /dev/null
@@ -1,82 +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.hadoop.gateway.i18n.messages.loggers.sl4j;
-
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.MessageLogger;
-import org.slf4j.Logger;
-
-public class Sl4jMessageLogger implements MessageLogger {
-
-  private Logger logger;
-
-  Sl4jMessageLogger( Logger logger ) {
-    this.logger = logger;
-  }
-
-  @Override
-  public boolean isLoggable( MessageLevel level ) {
-    switch( level ) {
-      case FATAL: return logger.isErrorEnabled();
-      case ERROR: return logger.isErrorEnabled();
-      case WARN: return logger.isWarnEnabled();
-      case INFO: return logger.isInfoEnabled();
-      case DEBUG: return logger.isDebugEnabled();
-      case TRACE: return logger.isTraceEnabled();
-      default: return false;
-    }
-  }
-
-  @Override
-  public void log( final StackTraceElement caller, final MessageLevel messageLevel, final String messageId, final String messageText, final Throwable thrown ) {
-    switch( messageLevel ) {
-      case FATAL:
-      case ERROR:
-        if( thrown == null )
-          logger.error( messageText );
-        else
-          logger.error( messageText, thrown );
-        break;
-      case WARN:
-        if( thrown == null )
-          logger.warn( messageText );
-        else
-          logger.warn( messageText, thrown );
-        break;
-      case INFO:
-        if( thrown == null )
-          logger.info( messageText );
-        else
-          logger.info( messageText, thrown );
-        break;
-      case DEBUG:
-        if( thrown == null )
-          logger.debug( messageText );
-        else
-          logger.debug( messageText, thrown );
-        break;
-      case TRACE:
-        if( thrown == null )
-          logger.trace( messageText );
-        else
-          logger.trace( messageText, thrown );
-        break;
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-sl4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-sl4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactory.java b/gateway-i18n-logging-sl4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactory.java
deleted file mode 100644
index 0fe4794..0000000
--- a/gateway-i18n-logging-sl4j/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactory.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.i18n.messages.loggers.sl4j;
-
-import org.apache.hadoop.gateway.i18n.messages.MessageLogger;
-import org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory;
-import org.slf4j.LoggerFactory;
-
-public class Sl4jMessageLoggerFactory implements MessageLoggerFactory {
-
-  @Override
-  public MessageLogger getLogger( String name ) {
-    return new Sl4jMessageLogger( LoggerFactory.getLogger( name ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-sl4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLogger.java
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-sl4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLogger.java b/gateway-i18n-logging-sl4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLogger.java
new file mode 100644
index 0000000..03239dc
--- /dev/null
+++ b/gateway-i18n-logging-sl4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLogger.java
@@ -0,0 +1,82 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.messages.loggers.sl4j;
+
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.MessageLogger;
+import org.slf4j.Logger;
+
+public class Sl4jMessageLogger implements MessageLogger {
+
+  private Logger logger;
+
+  Sl4jMessageLogger( Logger logger ) {
+    this.logger = logger;
+  }
+
+  @Override
+  public boolean isLoggable( MessageLevel level ) {
+    switch( level ) {
+      case FATAL: return logger.isErrorEnabled();
+      case ERROR: return logger.isErrorEnabled();
+      case WARN: return logger.isWarnEnabled();
+      case INFO: return logger.isInfoEnabled();
+      case DEBUG: return logger.isDebugEnabled();
+      case TRACE: return logger.isTraceEnabled();
+      default: return false;
+    }
+  }
+
+  @Override
+  public void log( final StackTraceElement caller, final MessageLevel messageLevel, final String messageId, final String messageText, final Throwable thrown ) {
+    switch( messageLevel ) {
+      case FATAL:
+      case ERROR:
+        if( thrown == null )
+          logger.error( messageText );
+        else
+          logger.error( messageText, thrown );
+        break;
+      case WARN:
+        if( thrown == null )
+          logger.warn( messageText );
+        else
+          logger.warn( messageText, thrown );
+        break;
+      case INFO:
+        if( thrown == null )
+          logger.info( messageText );
+        else
+          logger.info( messageText, thrown );
+        break;
+      case DEBUG:
+        if( thrown == null )
+          logger.debug( messageText );
+        else
+          logger.debug( messageText, thrown );
+        break;
+      case TRACE:
+        if( thrown == null )
+          logger.trace( messageText );
+        else
+          logger.trace( messageText, thrown );
+        break;
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-sl4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-sl4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactory.java b/gateway-i18n-logging-sl4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactory.java
new file mode 100644
index 0000000..2ff932a
--- /dev/null
+++ b/gateway-i18n-logging-sl4j/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactory.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.messages.loggers.sl4j;
+
+import org.apache.knox.gateway.i18n.messages.MessageLogger;
+import org.apache.knox.gateway.i18n.messages.MessageLoggerFactory;
+import org.slf4j.LoggerFactory;
+
+public class Sl4jMessageLoggerFactory implements MessageLoggerFactory {
+
+  @Override
+  public MessageLogger getLogger( String name ) {
+    return new Sl4jMessageLogger( LoggerFactory.getLogger( name ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-sl4j/src/main/resources/META-INF/services/org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-sl4j/src/main/resources/META-INF/services/org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory b/gateway-i18n-logging-sl4j/src/main/resources/META-INF/services/org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory
deleted file mode 100644
index afd88bd..0000000
--- a/gateway-i18n-logging-sl4j/src/main/resources/META-INF/services/org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.i18n.messages.loggers.sl4j.Sl4jMessageLoggerFactory
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-sl4j/src/main/resources/META-INF/services/org.apache.knox.gateway.i18n.messages.MessageLoggerFactory
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-sl4j/src/main/resources/META-INF/services/org.apache.knox.gateway.i18n.messages.MessageLoggerFactory b/gateway-i18n-logging-sl4j/src/main/resources/META-INF/services/org.apache.knox.gateway.i18n.messages.MessageLoggerFactory
new file mode 100644
index 0000000..0fc7b6b
--- /dev/null
+++ b/gateway-i18n-logging-sl4j/src/main/resources/META-INF/services/org.apache.knox.gateway.i18n.messages.MessageLoggerFactory
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.i18n.messages.loggers.sl4j.Sl4jMessageLoggerFactory
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-sl4j/src/test/java/org/apache/hadoop/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactoryTest.java
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-sl4j/src/test/java/org/apache/hadoop/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactoryTest.java b/gateway-i18n-logging-sl4j/src/test/java/org/apache/hadoop/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactoryTest.java
deleted file mode 100644
index 699ad3d..0000000
--- a/gateway-i18n-logging-sl4j/src/test/java/org/apache/hadoop/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactoryTest.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.hadoop.gateway.i18n.messages.loggers.sl4j;
-
-import org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class Sl4jMessageLoggerFactoryTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( MessageLoggerFactory.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof Sl4jMessageLoggerFactory ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + Sl4jMessageLoggerFactory.class.getName() + " via service loader." );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n-logging-sl4j/src/test/java/org/apache/knox/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactoryTest.java
----------------------------------------------------------------------
diff --git a/gateway-i18n-logging-sl4j/src/test/java/org/apache/knox/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactoryTest.java b/gateway-i18n-logging-sl4j/src/test/java/org/apache/knox/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactoryTest.java
new file mode 100644
index 0000000..7d2a6d0
--- /dev/null
+++ b/gateway-i18n-logging-sl4j/src/test/java/org/apache/knox/gateway/i18n/messages/loggers/sl4j/Sl4jMessageLoggerFactoryTest.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.knox.gateway.i18n.messages.loggers.sl4j;
+
+import org.apache.knox.gateway.i18n.messages.MessageLoggerFactory;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class Sl4jMessageLoggerFactoryTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( MessageLoggerFactory.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof Sl4jMessageLoggerFactory ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + Sl4jMessageLoggerFactory.class.getName() + " via service loader." );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/Message.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/Message.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/Message.java
deleted file mode 100644
index bc63e79..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/Message.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.hadoop.gateway.i18n.messages;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- *
- */
-@Retention( RetentionPolicy.RUNTIME )
-@Target( ElementType.METHOD )
-public @interface Message {
-  static final String DEFAULT_TEXT = "{}";
-  static final int DEFAULT_CODE = -1;
-  MessageLevel level() default MessageLevel.INFO;
-  int code() default DEFAULT_CODE;
-  String text() default DEFAULT_TEXT;
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessageLevel.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessageLevel.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessageLevel.java
deleted file mode 100644
index ae2cc0b..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessageLevel.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.hadoop.gateway.i18n.messages;
-
-/**
- *
- */
-public enum MessageLevel {
-  FATAL, ERROR, WARN, INFO, DEBUG, TRACE
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessageLogger.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessageLogger.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessageLogger.java
deleted file mode 100644
index 5ab41ad..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessageLogger.java
+++ /dev/null
@@ -1,29 +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.hadoop.gateway.i18n.messages;
-
-/**
- *
- */
-public interface MessageLogger {
-
-  boolean isLoggable( MessageLevel level );
-
-  void log( StackTraceElement caller, MessageLevel messageLevel, String messageId, String messageText, Throwable thrown );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessageLoggerFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessageLoggerFactory.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessageLoggerFactory.java
deleted file mode 100644
index e0e61c7..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessageLoggerFactory.java
+++ /dev/null
@@ -1,27 +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.hadoop.gateway.i18n.messages;
-
-/**
- *
- */
-public interface MessageLoggerFactory {
-
-  MessageLogger getLogger( String name );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/Messages.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/Messages.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/Messages.java
deleted file mode 100644
index 68579b8..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/Messages.java
+++ /dev/null
@@ -1,37 +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.hadoop.gateway.i18n.messages;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- *
- */
-@Retention( RetentionPolicy.RUNTIME )
-@Target( ElementType.TYPE )
-public @interface Messages {
-  static final String DEFAULT_BUNDLE = "";
-  static final String DEFAULT_LOGGER = "";
-  static final String DEFAULT_CODES = "{0}";
-  String bundle() default DEFAULT_BUNDLE;
-  String logger() default DEFAULT_LOGGER;
-  String codes() default DEFAULT_CODES;
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessagesFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessagesFactory.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessagesFactory.java
deleted file mode 100644
index 7ba766a..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessagesFactory.java
+++ /dev/null
@@ -1,65 +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.hadoop.gateway.i18n.messages;
-
-import org.apache.hadoop.gateway.i18n.messages.loggers.jdk.JdkMessageLoggerFactory;
-import org.apache.hadoop.gateway.i18n.messages.loggers.sout.SoutMessageLoggerFactory;
-import org.apache.hadoop.gateway.i18n.messages.loggers.sout.SoutMessageLoggerFactory;
-
-import java.lang.reflect.Proxy;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.ServiceLoader;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- *
- */
-public class MessagesFactory {
-
-  private static MessageLoggerFactory loggers = getMessageLoggerFactory();
-  private static Map<Class<?>, Object> proxies = new ConcurrentHashMap<Class<?>, Object>();
-
-  @SuppressWarnings( "unchecked" )
-  public static <T> T get( Class<T> clazz ) {
-    Object proxy = proxies.get( clazz );
-    if( proxy == null ) {
-      Messages anno = clazz.getAnnotation( Messages.class );
-      if( anno == null ) {
-        throw new IllegalArgumentException( clazz.getName() + " missing @" + Messages.class.getCanonicalName() );
-      }
-      MessagesInvoker invoker = new MessagesInvoker( clazz, loggers );
-      proxy = Proxy.newProxyInstance( clazz.getClassLoader(), new Class[]{ clazz }, invoker );
-      proxies.put( clazz, proxy );
-    }
-    return (T)proxy;
-  }
-
-  private static MessageLoggerFactory getMessageLoggerFactory() {
-    MessageLoggerFactory factory;
-    ServiceLoader<MessageLoggerFactory> loader = ServiceLoader.load( MessageLoggerFactory.class );
-    Iterator<MessageLoggerFactory> factories = loader.iterator();
-    if( factories != null && factories.hasNext() ) {
-      factory = loader.iterator().next();
-    } else {
-      factory = new JdkMessageLoggerFactory();
-    }
-    return factory;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessagesInvoker.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessagesInvoker.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessagesInvoker.java
deleted file mode 100644
index 7fad77d..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/MessagesInvoker.java
+++ /dev/null
@@ -1,173 +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.hadoop.gateway.i18n.messages;
-
-import org.apache.hadoop.gateway.i18n.resources.ResourcesInvoker;
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.text.MessageFormat;
-
-/**
- *
- */
-public class MessagesInvoker extends ResourcesInvoker implements InvocationHandler {
-
-  private String codes;
-  private MessageLogger logger;
-  private String bundle;
-
-  public MessagesInvoker( Class<?> clazz, MessageLoggerFactory loggers ) {
-    super( clazz );
-    Messages anno = clazz.getAnnotation( Messages.class );
-    codes = calcCodePattern( clazz, anno );
-    bundle = calcBundleName( clazz, anno );
-    logger = getLogger( clazz, anno, loggers );
-  }
-
-  @Override
-  public Object invoke( final Object proxy, final Method method, final Object[] args ) throws Throwable {
-    String message = null;
-    MessageLevel level = getLevel( method );
-    if( logger.isLoggable( level ) ) {
-      message = getText( method, args );
-      String code = getCode( method );
-      Throwable throwable = findLoggableThrowable( logger, method, args );
-      // Supposedly this Throwable way is faster than the Thread way.
-      // From looking at the JRE code it looks this is probably the case.
-      // The second version ends up calling the first version after getting the current thread
-      // and then checking that it is being called from the current thread.
-      //TODO: Should probably only do this if the logger is at debug or finer to make sure there isn't a performance impact during production usage.
-      StackTraceElement caller = new Throwable().getStackTrace()[2];
-      // StackTraceElement caller = Thread.currentThread().getStackTrace()[3];
-      logger.log( caller, level, code, message, throwable );
-    }
-    return message;
-  }
-
-  private final String getCode( final Method method ) {
-    String code = null;
-    Message anno = method.getAnnotation( Message.class );
-    if( anno != null ) {
-      int num = anno.code();
-      if( Message.DEFAULT_CODE != num ) {
-        code = MessageFormat.format( codes, num );
-      }
-    }
-    return code;
-  }
-
-  private static final StackTrace getStackTraceAnno( final Method method, final int param ) {
-    final Annotation[] annos = method.getParameterAnnotations()[ param ];
-    for( Annotation anno: annos ) {
-      if( anno instanceof StackTrace ) {
-        return (StackTrace)anno;
-      }
-    }
-    return null;
-  }
-
-  private static final Throwable findLoggableThrowable( final MessageLogger logger, final Method method, final Object[] args ) {
-    Throwable throwable = null;
-    if( args != null ) {
-      for( int i=0; i<args.length; i++ ) {
-        Object arg = args[i];
-        if( arg instanceof Throwable ) {
-          StackTrace anno = getStackTraceAnno( method, i );
-          if( anno != null ) {
-            if( logger.isLoggable( anno.level() ) ) {
-              throwable = (Throwable)arg;
-              break;
-            }
-          }
-        }
-      }
-    }
-    return throwable;
-  }
-
-  protected String getAnnotationPattern( final Method method ) {
-    String pattern = null;
-    Message anno = method.getAnnotation( Message.class );
-    if( anno != null ) {
-      pattern = anno.text();
-    }
-    return pattern;
-  }
-
-  private static final MessageLevel getLevel( final Method method ) {
-    MessageLevel level;
-    Message anno = method.getAnnotation( Message.class );
-    if( anno == null ) {
-      level = MessageLevel.INFO;
-    } else {
-      level = anno.level();
-    }
-    return level;
-  }
-
-  private static String calcCodePattern( final Class<?> clazz, final Messages anno ) {
-    String pattern = anno.codes();
-    if( Messages.DEFAULT_CODES.equals( pattern ) ) {
-      pattern = clazz.getCanonicalName().replace( '.', '/' );
-    }
-    return pattern;
-  }
-
-  private static String calcBundleName( Class<?> clazz, Messages anno ) {
-    String bundle = null;
-    if( anno != null ) {
-      bundle = anno.bundle();
-      if( Messages.DEFAULT_BUNDLE.equals( bundle ) ) {
-        bundle = null;
-      }
-    }
-    if( bundle == null ) {
-      bundle = clazz.getCanonicalName().replace( '.', '/' );
-    }
-    return bundle;
-  }
-
-  private static final String calcLoggerName( final Class<?> clazz, final Messages anno ) {
-    String logger = null;
-    if( anno != null ) {
-      logger = anno.logger();
-      if( Messages.DEFAULT_LOGGER.equals( logger ) ) {
-        logger = null;
-      }
-    }
-    if( logger == null ) {
-      logger = clazz.getCanonicalName();
-    }
-    return logger;
-  }
-
-  protected String getBundleName() {
-    return bundle;
-  }
-
-  private static final MessageLogger getLogger( final Class<?> clazz, final Messages anno, final MessageLoggerFactory loggers ) {
-    return loggers.getLogger( calcLoggerName( clazz, anno ) );
-  }
-
-  public String toString() {
-    return "MessageInvoker["+bundle+"]";
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/StackTrace.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/StackTrace.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/StackTrace.java
deleted file mode 100644
index 03ba33c..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/StackTrace.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.hadoop.gateway.i18n.messages;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- *
- */
-@Retention( RetentionPolicy.RUNTIME )
-@Target( ElementType.PARAMETER )
-public @interface StackTrace {
-  MessageLevel level() default MessageLevel.DEBUG;
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/jdk/JdkMessageLogger.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/jdk/JdkMessageLogger.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/jdk/JdkMessageLogger.java
deleted file mode 100644
index 42f07a5..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/jdk/JdkMessageLogger.java
+++ /dev/null
@@ -1,67 +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.hadoop.gateway.i18n.messages.loggers.jdk;
-
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.MessageLogger;
-
-import java.util.logging.Level;
-import java.util.logging.LogRecord;
-import java.util.logging.Logger;
-
-/**
- *
- */
-final class JdkMessageLogger implements MessageLogger {
-
-  private final Logger logger;
-
-  JdkMessageLogger( final Logger logger ) {
-    this.logger = logger;
-  }
-
-  @Override
-  public final boolean isLoggable( final MessageLevel level ) {
-    return logger.isLoggable( toLevel( level ) );
-  }
-
-  //TODO: Handle message ID.
-  @Override
-  public final void log( final StackTraceElement caller, final MessageLevel level, final String id, final String message, final Throwable thrown ) {
-    LogRecord record = new LogRecord( toLevel( level ), message );
-    record.setSourceClassName( caller.getClassName() );
-    record.setSourceMethodName( caller.getMethodName() );
-    if( thrown != null ) {
-      record.setThrown( thrown );
-    }
-    logger.log( record );
-  }
-
-  private static final Level toLevel( final MessageLevel level ) {
-    switch( level ) {
-      case FATAL: return Level.SEVERE;
-      case ERROR: return Level.SEVERE;
-      case WARN: return Level.WARNING;
-      case INFO: return Level.INFO;
-      case DEBUG: return Level.FINE;
-      case TRACE: return Level.FINEST;
-      default: return Level.OFF;
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/jdk/JdkMessageLoggerFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/jdk/JdkMessageLoggerFactory.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/jdk/JdkMessageLoggerFactory.java
deleted file mode 100644
index 0d540fb..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/jdk/JdkMessageLoggerFactory.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.hadoop.gateway.i18n.messages.loggers.jdk;
-
-import org.apache.hadoop.gateway.i18n.messages.MessageLogger;
-import org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory;
-
-import java.util.logging.Logger;
-
-/**
- *
- */
-public class JdkMessageLoggerFactory implements MessageLoggerFactory {
-
-  @Override
-  public MessageLogger getLogger( String name ) {
-    return new JdkMessageLogger( Logger.getLogger( name ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sout/SoutMessageLogger.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sout/SoutMessageLogger.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sout/SoutMessageLogger.java
deleted file mode 100644
index 283e494..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sout/SoutMessageLogger.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.hadoop.gateway.i18n.messages.loggers.sout;
-
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.MessageLogger;
-
-import java.text.MessageFormat;
-
-/**
- *
- */
-public class SoutMessageLogger implements MessageLogger {
-
-  private static final String FORMAT_WITHOUT_ID = "{0}: {2}";
-  private static final String FORMAT_WITH_ID = "{0}: {2} [{1}]";
-
-  private final String name;
-
-  SoutMessageLogger( String name ) {
-    this.name = name;
-  }
-
-  @Override
-  public boolean isLoggable( MessageLevel level ) {
-    return true;
-  }
-
-  private static final String getFormat( final String id ) {
-    return( id == null ) ? FORMAT_WITHOUT_ID : FORMAT_WITH_ID;
-  }
-
-  @Override
-  public void log( final StackTraceElement caller, final MessageLevel level, final String id, final String message, final Throwable thrown ) {
-    System.out.println( MessageFormat.format( getFormat( id ), level, id, message ) ); // I18N not required.
-    if( thrown != null ) {
-      thrown.printStackTrace();
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sout/SoutMessageLoggerFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sout/SoutMessageLoggerFactory.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sout/SoutMessageLoggerFactory.java
deleted file mode 100644
index 07c9e6c..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/sout/SoutMessageLoggerFactory.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.hadoop.gateway.i18n.messages.loggers.sout;
-
-import org.apache.hadoop.gateway.i18n.messages.MessageLogger;
-import org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory;
-import org.apache.hadoop.gateway.i18n.messages.loggers.test.TestMessageLogger;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- *
- */
-public class SoutMessageLoggerFactory implements MessageLoggerFactory {
-
-  private static SoutMessageLoggerFactory INSTANCE;
-  private static final Map<String,MessageLogger> LOGGERS = new ConcurrentHashMap<String,MessageLogger>();
-
-  public static SoutMessageLoggerFactory getFactory() {
-    if( INSTANCE == null ) {
-      INSTANCE = new SoutMessageLoggerFactory();
-    }
-    return INSTANCE;
-  }
-
-  public SoutMessageLoggerFactory() {
-    INSTANCE = this;
-  }
-
-  @Override
-  public MessageLogger getLogger( String name ) {
-    MessageLogger logger = LOGGERS.get( name );
-    if( logger == null ) {
-      logger = new SoutMessageLogger( name );
-      LOGGERS.put( name, logger );
-    }
-    return logger;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/test/TestMessageLogger.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/test/TestMessageLogger.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/test/TestMessageLogger.java
deleted file mode 100644
index 4dc3409..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/test/TestMessageLogger.java
+++ /dev/null
@@ -1,55 +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.hadoop.gateway.i18n.messages.loggers.test;
-
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.MessageLogger;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/**
- *
- */
-public class TestMessageLogger implements MessageLogger {
-
-  public final List<TestMessageRecord> records = Collections.synchronizedList( new ArrayList<TestMessageRecord>() );
-
-  public final String name;
-
-  TestMessageLogger( final String name ) {
-    this.name = name;
-  }
-
-  public String getName() {
-    return name;
-  }
-
-  @Override
-  public boolean isLoggable( MessageLevel level ) {
-    return true;
-  }
-
-  @Override
-  public void log( final StackTraceElement caller, final MessageLevel level, final String id, final String text, final Throwable thrown ) {
-    TestMessageRecord record = new TestMessageRecord( this, caller, level, id, text, thrown );
-    records.add( record );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/test/TestMessageLoggerFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/test/TestMessageLoggerFactory.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/test/TestMessageLoggerFactory.java
deleted file mode 100644
index 9b8b5e0..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/test/TestMessageLoggerFactory.java
+++ /dev/null
@@ -1,55 +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.hadoop.gateway.i18n.messages.loggers.test;
-
-import org.apache.hadoop.gateway.i18n.messages.MessageLogger;
-import org.apache.hadoop.gateway.i18n.messages.MessageLoggerFactory;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- *
- */
-public class TestMessageLoggerFactory implements MessageLoggerFactory {
-
-  private static TestMessageLoggerFactory INSTANCE;
-  private static final Map<String,MessageLogger> LOGGERS = new ConcurrentHashMap<String,MessageLogger>();
-
-  public static TestMessageLoggerFactory getFactory() {
-    if( INSTANCE == null ) {
-      INSTANCE = new TestMessageLoggerFactory();
-    }
-    return INSTANCE;
-  }
-
-  public TestMessageLoggerFactory() {
-    INSTANCE = this;
-  }
-
-  @Override
-  public MessageLogger getLogger( String name ) {
-    MessageLogger logger = LOGGERS.get( name );
-    if( logger == null ) {
-      logger = new TestMessageLogger( name );
-      LOGGERS.put( name, logger );
-    }
-    return logger;
-  }
-
-}


[17/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest.java
new file mode 100644
index 0000000..f1d9687
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest.java
@@ -0,0 +1,253 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.hamcrest.Matchers;
+import org.junit.Test;
+import org.xmlmatchers.transform.XmlConverters;
+
+import javax.xml.transform.Source;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.net.URL;
+import java.util.List;
+
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.CoreMatchers.sameInstance;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
+import static org.xmlmatchers.XmlMatchers.hasXPath;
+
+public class UrlRewriteRulesDescriptorFactoryTest {
+
+  @Test
+  public void testCreate() throws Exception {
+    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
+    assertThat( descriptor, notNullValue() );
+    assertThat( descriptor.getRules(), notNullValue() );
+    assertThat( descriptor.getRules().isEmpty(), is( true ) );
+
+    UrlRewriteRuleDescriptor rule = descriptor.newRule();
+    assertThat( rule, notNullValue() );
+    assertThat( descriptor.getRules().isEmpty(), is( true ) );
+    rule.name( "first" );
+    descriptor.addRule( rule );
+    assertThat( descriptor.getRules().size(), is( 1 ) );
+    assertThat( descriptor.getRule( "first" ), sameInstance( rule ) );
+
+    rule = descriptor.addRule( "second" );
+    assertThat( descriptor.getRules().size(), is( 2 ) );
+  }
+
+  private static URL getTestResourceUrl( String name ) throws FileNotFoundException {
+    name = UrlRewriteRulesDescriptorFactoryTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
+    URL url = ClassLoader.getSystemResource( name );
+    if( url == null ) {
+      throw new FileNotFoundException( name );
+    }
+    return url;
+  }
+
+  private static InputStream getTestResourceStream( String name ) throws IOException {
+    URL url = getTestResourceUrl( name );
+    InputStream stream = url.openStream();
+    return stream;
+  }
+
+  private static Reader getTestResourceReader( String name, String charset ) throws IOException {
+    return new InputStreamReader( getTestResourceStream( name ), charset );
+  }
+
+  @Test
+  public void testLoadMissingFile() throws IOException {
+    try {
+      UrlRewriteRulesDescriptorFactory.load( "xml", getTestResourceReader( "missing.xml", "UTF-8" ) );
+      fail( "Should have thrown a FileNotFoundException." );
+    } catch ( FileNotFoundException e ) {
+      assertThat( e.getMessage(), containsString( "missing.xml" ) );
+    }
+  }
+
+  @Test
+  public void testLoadEmptyFile() throws IOException {
+    Logger logger = org.apache.log4j.LogManager.getLogger( "org.apache.commons.digester3.Digester" );
+    Level level = logger.getLevel();
+    try {
+      logger.setLevel( org.apache.log4j.Level.OFF );
+      UrlRewriteRulesDescriptorFactory.load( "xml", getTestResourceReader( "empty.xml", "UTF-8" ) );
+      fail( "Should have thrown an IOException." );
+    } catch ( IOException e ) {
+      // Expected.
+    } catch ( Throwable t ) {
+      fail( "Should have thrown an IOException." );
+    } finally {
+      logger.setLevel( level );
+    }
+  }
+
+  @Test
+  public void testLoadInvalidFile() throws IOException {
+    Logger logger = org.apache.log4j.LogManager.getLogger( "org.apache.commons.digester3.Digester" );
+    Level level = logger.getLevel();
+    try {
+      logger.setLevel( org.apache.log4j.Level.OFF );
+      UrlRewriteRulesDescriptorFactory.load( "xml", getTestResourceReader( "invalid.xml", "UTF-8" ) );
+      fail( "Should have thrown an IOException." );
+    } catch ( IOException e ) {
+      // Expected.
+    } catch ( Throwable t ) {
+      fail( "Should have thrown an IOException." );
+    } finally {
+      logger.setLevel( level );
+    }
+  }
+
+  @Test
+  public void testLoadNoopFile() throws IOException {
+    UrlRewriteRulesDescriptor config =
+        UrlRewriteRulesDescriptorFactory.load( "xml", getTestResourceReader( "noop.xml", "UTF-8" ) );
+    assertThat( "Rules should be an empty list.", config.getRules().isEmpty(), Matchers.is( true ) );
+  }
+
+  @Test
+  public void testLoadSimpleFile() throws IOException {
+    UrlRewriteRulesDescriptor config =
+        UrlRewriteRulesDescriptorFactory.load( "xml", getTestResourceReader( "simple.xml", "UTF-8" ) );
+    assertThat( "Failed to load simple config file.", config, notNullValue() );
+  }
+
+  @Test
+  public void testLoadSimpleFilterFile() throws IOException {
+    UrlRewriteRulesDescriptor config =
+        UrlRewriteRulesDescriptorFactory.load( "xml", getTestResourceReader( "filter-simple.xml", "UTF-8" ) );
+    List<UrlRewriteFilterDescriptor> filters = config.getFilters();
+    assertThat( filters.size(), is( 1 ) );
+    UrlRewriteFilterDescriptor filter = config.getFilter( "test-filter-1" );
+    assertThat( filter, notNullValue() );
+    assertThat( config.getFilters().get(0), sameInstance( filter ) );
+  }
+
+  @Test
+  public void testLoadStoreCompleteFilterFile() throws IOException {
+    UrlRewriteRulesDescriptor config =
+        UrlRewriteRulesDescriptorFactory.load( "xml", getTestResourceReader( "filter-complete.xml", "UTF-8" ) );
+
+    List<UrlRewriteFilterDescriptor> filters = config.getFilters();
+    assertThat( filters.size(), is( 1 ) );
+
+    UrlRewriteFilterDescriptor filter = config.getFilter( "test-filter-name-1" );
+    assertThat( filter, notNullValue() );
+    assertThat( config.getFilters().get(0), sameInstance( filter ) );
+    assertThat( filter.name(), is( "test-filter-name-1" ) );
+
+    UrlRewriteFilterContentDescriptor content = filter.getContent( "test-content-type-1/test-content-subtype-1" );
+    assertThat( content, notNullValue() );
+    assertThat( content.type(), is( "test-content-type-1/test-content-subtype-1" ) );
+
+    List<UrlRewriteFilterPathDescriptor> selectors = content.getSelectors();
+    assertThat( selectors, notNullValue() );
+    assertThat( selectors.size(), is( 3 ) );
+
+    UrlRewriteFilterApplyDescriptor apply = (UrlRewriteFilterApplyDescriptor)selectors.get( 0 );
+    assertThat( apply, notNullValue() );
+    assertThat( apply.path(), is( "test-apply-path-1" ) );
+    assertThat( apply.rule(), is( "test-apply-rule-1" ) );
+    assertThat( apply.compiledPath(), nullValue() );
+
+    UrlRewriteFilterScopeDescriptor scope = (UrlRewriteFilterScopeDescriptor)selectors.get( 1 );
+    assertThat( scope, notNullValue() );
+    assertThat( scope.path(), is( "test-scope-path-1" ) );
+    assertThat( scope.compiledPath(), nullValue() );
+    List<UrlRewriteFilterPathDescriptor> scopeSelectors = scope.getSelectors();
+    assertThat( scopeSelectors, notNullValue() );
+    assertThat( scopeSelectors.size(), is( 1 ) );
+    UrlRewriteFilterApplyDescriptor scopeApply = (UrlRewriteFilterApplyDescriptor)scopeSelectors.get( 0 );
+    assertThat( scopeApply, notNullValue() );
+    assertThat( scopeApply.path(), is( "test-apply-path-2" ) );
+    assertThat( scopeApply.compiledPath(), nullValue() );
+    assertThat( scopeApply.rule(), is( "test-apply-rule-2" ) );
+
+    UrlRewriteFilterBufferDescriptor buffer = (UrlRewriteFilterBufferDescriptor)selectors.get( 2 );
+    assertThat( buffer, notNullValue() );
+    assertThat( buffer.path(), is( "test-buffer-path-1" ) );
+    assertThat( buffer.compiledPath(), nullValue() );
+    List<UrlRewriteFilterPathDescriptor> bufferSelectors = buffer.getSelectors();
+    assertThat( bufferSelectors, notNullValue() );
+    assertThat( bufferSelectors.size(), is( 2 ) );
+    UrlRewriteFilterApplyDescriptor bufferApply = (UrlRewriteFilterApplyDescriptor)bufferSelectors.get( 0 );
+    assertThat( bufferApply, notNullValue() );
+    assertThat( bufferApply.path(), is( "test-apply-path-3" ) );
+    assertThat( bufferApply.compiledPath(), nullValue() );
+    assertThat( bufferApply.rule(), is( "test-apply-rule-3" ) );
+    UrlRewriteFilterDetectDescriptor bufferDetect = (UrlRewriteFilterDetectDescriptor)bufferSelectors.get( 1 );
+    assertThat( bufferDetect, notNullValue() );
+    assertThat( bufferDetect.value(), is( "test-detect-value-1" ) );
+    assertThat( bufferDetect.compiledValue(), nullValue() );
+    List<UrlRewriteFilterPathDescriptor> detectSelectors = bufferDetect.getSelectors();
+    assertThat( detectSelectors, notNullValue() );
+    assertThat( detectSelectors.size(), is( 1 ) );
+    UrlRewriteFilterApplyDescriptor detectApply = (UrlRewriteFilterApplyDescriptor)detectSelectors.get( 0 );
+    assertThat( detectApply, notNullValue() );
+    assertThat( detectApply.path(), is( "test-apply-path-4" ) );
+    assertThat( detectApply.compiledPath(), nullValue() );
+    assertThat( detectApply.rule(), is( "test-apply-rule-4" ) );
+
+    StringWriter writer = new StringWriter();
+    UrlRewriteRulesDescriptorFactory.store( config, "xml", writer );
+    Source xml = XmlConverters.the( writer.toString() );
+
+    assertThat( xml, notNullValue() );
+    assertThat( xml, hasXPath( "/" ) );
+    assertThat( xml, hasXPath( "/rules" ) );
+    assertThat( xml, hasXPath( "/rules/filter" ) );
+    assertThat( xml, hasXPath( "/rules/filter/@name", equalTo( "test-filter-name-1" ) ) );
+    assertThat( xml, hasXPath( "/rules/filter/content" ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/@type", equalTo( "test-content-type-1/test-content-subtype-1" ) ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/apply" ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/apply/@path", equalTo( "test-apply-path-1" ) ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/apply/@rule", equalTo( "test-apply-rule-1" ) ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/scope" ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/scope/@path", equalTo( "test-scope-path-1" ) ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/scope/apply" ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/scope/apply/@path", equalTo( "test-apply-path-2" ) ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/scope/apply/@rule", equalTo( "test-apply-rule-2" ) ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/buffer" ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/buffer/@path", equalTo( "test-buffer-path-1" ) ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/buffer/apply" ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/buffer/apply/@path", equalTo( "test-apply-path-3" ) ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/buffer/apply/@rule", equalTo( "test-apply-rule-3" ) ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/buffer/detect" ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/buffer/detect/@path", equalTo( "test-detect-path-1" ) ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/buffer/detect/@value", equalTo( "test-detect-value-1" ) ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/buffer/detect/apply" ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/buffer/detect/apply/@path", equalTo( "test-apply-path-4" ) ) );
+    assertThat( xml, hasXPath( "/rules/filter/content/buffer/detect/apply/@rule", equalTo( "test-apply-rule-4" ) ) );
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest.java
new file mode 100644
index 0000000..1d0d72d
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest.java
@@ -0,0 +1,89 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+import org.apache.hadoop.test.mock.MockInteraction;
+import org.apache.hadoop.test.mock.MockServlet;
+import org.eclipse.jetty.servlet.FilterHolder;
+import org.eclipse.jetty.servlet.ServletHolder;
+import org.eclipse.jetty.http.HttpTester;
+import org.eclipse.jetty.servlet.ServletTester;
+import org.eclipse.jetty.util.ArrayQueue;
+import org.junit.After;
+import org.junit.Before;
+
+import javax.servlet.DispatcherType;
+import java.net.URL;
+import java.util.EnumSet;
+
+import static org.junit.Assert.fail;
+
+public class UrlRewriteServletContextListenerTest {
+
+  private ServletTester server;
+  private HttpTester.Request request;
+  private HttpTester.Response response;
+  private ArrayQueue<MockInteraction> interactions;
+  private MockInteraction interaction;
+
+  private static URL getTestResource( String name ) {
+    name = UrlRewriteServletFilterTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
+    URL url = ClassLoader.getSystemResource( name );
+    return url;
+  }
+
+  @Before
+  public void setUp() throws Exception {
+    String descriptorUrl = getTestResource( "rewrite.xml" ).toExternalForm();
+
+    server = new ServletTester();
+    server.setContextPath( "/" );
+    server.getContext().addEventListener( new UrlRewriteServletContextListener() );
+    server.getContext().setInitParameter(
+        UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );
+
+    FilterHolder filter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
+    filter.setFilter( new UrlRewriteServletFilter() );
+
+    interactions = new ArrayQueue<MockInteraction>();
+
+    ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
+    servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );
+    servlet.setInitParameter(
+        UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME,
+        getTestResource( "rewrite.xml" ).toExternalForm() );
+
+    server.start();
+
+    interaction = new MockInteraction();
+    request = HttpTester.newRequest();
+    response = null;
+  }
+
+  @After
+  public void tearDown() throws Exception {
+    server.stop();
+  }
+
+//  @Test
+//  @Ignore("TODO")
+//  public void testProvider() throws Exception {
+//    fail( "TODO" );
+//  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletEnvironmentTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletEnvironmentTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletEnvironmentTest.java
new file mode 100644
index 0000000..8b860fc
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletEnvironmentTest.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.knox.gateway.filter.rewrite.api;
+
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+import javax.servlet.ServletContext;
+
+import java.net.URL;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
+
+public class UrlRewriteServletEnvironmentTest {
+
+  @Test
+  public void testGetResource() throws Exception {
+    ServletContext context = EasyMock.createNiceMock( ServletContext.class );
+    EasyMock.expect( context.getResource( "test-resource-name" ) ).andReturn( new URL( "http:/test-resource-value" ) ).anyTimes();
+    EasyMock.replay( context );
+    UrlRewriteServletEnvironment env = new UrlRewriteServletEnvironment( context );
+    assertThat( env.getResource( "test-resource-name" ), is( new URL( "http:/test-resource-value" ) ) );
+  }
+
+  @Test
+  public void testGetAttribute() throws Exception {
+    ServletContext context = EasyMock.createNiceMock( ServletContext.class );
+    EasyMock.expect(  context.getAttribute( "test-attribute-name" ) ).andReturn( "test-attribute-value" ).anyTimes();
+    EasyMock.replay( context );
+    UrlRewriteServletEnvironment env = new UrlRewriteServletEnvironment( context );
+    assertThat( (String)env.getAttribute( "test-attribute-name" ), is( "test-attribute-value" ) );
+  }
+
+  @Test
+  public void testResolve() throws Exception {
+    ServletContext context = EasyMock.createNiceMock( ServletContext.class );
+    EasyMock.expect( context.getInitParameter( "test-parameter-name" ) ).andReturn( "test-parameter-value" );
+    EasyMock.replay( context );
+    UrlRewriteServletEnvironment env = new UrlRewriteServletEnvironment( context );
+    assertThat( env.resolve( "test-parameter-name" ), contains( "test-parameter-value" ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletFilterTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletFilterTest.java
new file mode 100644
index 0000000..484786e
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletFilterTest.java
@@ -0,0 +1,920 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+import com.jayway.jsonassert.JsonAssert;
+import org.apache.knox.gateway.filter.AbstractGatewayFilter;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.hadoop.test.TestUtils;
+import org.apache.hadoop.test.log.NoOpAppender;
+import org.apache.hadoop.test.mock.MockInteraction;
+import org.apache.hadoop.test.mock.MockServlet;
+import org.apache.log4j.Appender;
+import org.apache.log4j.Logger;
+import org.eclipse.jetty.http.HttpHeader;
+import org.eclipse.jetty.servlet.FilterHolder;
+import org.eclipse.jetty.servlet.ServletHolder;
+import org.eclipse.jetty.http.HttpTester;
+import org.eclipse.jetty.servlet.ServletTester;
+import org.eclipse.jetty.util.ArrayQueue;
+import org.junit.After;
+import org.junit.Test;
+
+import javax.servlet.DispatcherType;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.nio.charset.Charset;
+import java.util.EnumSet;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.anyOf;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.fail;
+import static org.xmlmatchers.XmlMatchers.hasXPath;
+import static org.xmlmatchers.transform.XmlConverters.the;
+
+public class UrlRewriteServletFilterTest {
+
+  Logger LOG = Logger.getLogger(UrlRewriteServletFilterTest.class);
+
+  private ServletTester server;
+  private HttpTester.Request request;
+  private HttpTester.Response response;
+  private ArrayQueue<MockInteraction> interactions;
+  private MockInteraction interaction;
+
+  private static URL getTestResource( String name ) {
+    name = UrlRewriteServletFilterTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
+    URL url = ClassLoader.getSystemResource( name );
+    return url;
+  }
+
+  public void setUp( Map<String,String> initParams ) throws Exception {
+    String descriptorUrl = getTestResource( "rewrite.xml" ).toExternalForm();
+
+    server = new ServletTester();
+    server.setContextPath( "/" );
+    server.getContext().addEventListener( new UrlRewriteServletContextListener() );
+    server.getContext().setInitParameter(
+        UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );
+
+    FilterHolder setupFilter = server.addFilter( SetupFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
+    setupFilter.setFilter( new SetupFilter() );
+    FilterHolder rewriteFilter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
+    if( initParams != null ) {
+      for( Map.Entry<String,String> entry : initParams.entrySet() ) {
+        rewriteFilter.setInitParameter( entry.getKey(), entry.getValue() );
+      }
+    }
+    rewriteFilter.setFilter( new UrlRewriteServletFilter() );
+
+    interactions = new ArrayQueue<MockInteraction>();
+
+    ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
+    servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );
+
+    server.start();
+
+    interaction = new MockInteraction();
+    request = HttpTester.newRequest();
+    response = null;
+  }
+
+  @After
+  public void tearDown() throws Exception {
+    if( server != null ) {
+      server.stop();
+    }
+  }
+
+  @Test
+  public void testInboundRequestUrlRewrite() throws Exception {
+    setUp( null );
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "GET" )
+        .requestUrl( "http://mock-host:1/test-output-path-1" );
+    interaction.respond().status( 200 ).content( "test-response-content".getBytes() );
+    interactions.add( interaction );
+    // Create the client request.
+    request.setMethod( "GET" );
+    request.setURI( "/test-input-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "mock-host:1" );
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), is( 200 ) );
+    assertThat( response.getContent(), is( "test-response-content" ) );
+  }
+
+  @Test
+  public void testInboundHeaderRewrite() throws Exception {
+    setUp( null );
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "GET" )
+        .requestUrl( "http://mock-host:1/test-output-path-1" )
+        .header( "Location", "http://mock-host:1/test-output-path-1" );
+    interaction.respond()
+        .status( 200 );
+    interactions.add( interaction );
+    // Create the client request.
+    request.setMethod( "GET" );
+    request.setURI( "/test-input-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "mock-host:1" );
+    request.setHeader( "Location", "http://mock-host:1/test-input-path" );
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), is( 200 ) );
+  }
+
+  @Test
+  public void testOutboundHeaderRewrite() throws Exception {
+    setUp( null );
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "GET" )
+        .requestUrl( "http://mock-host:1/test-output-path-1" );
+    interaction.respond()
+        .status( 201 )
+        .header( "Location", "http://mock-host:1/test-input-path" );
+    interactions.add( interaction );
+    // Create the client request.
+    request.setMethod( "GET" );
+    request.setURI( "/test-input-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "mock-host:1" );
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), is( 201 ) );
+    assertThat( response.get( HttpHeader.LOCATION ), is( "http://mock-host:1/test-output-path-1" ) );
+  }
+
+//  @Ignore( "Need to figure out how to handle cookies since domain and path are separate." )
+//  @Test
+//  public void testRequestCookieRewrite() throws Exception {
+//    setUp( null );
+//    // Setup the server side request/response interaction.
+//    interaction.expect()
+//        .method( "GET" )
+//        .requestUrl( "http://mock-host:1/test-output-path-1" )
+//        .header( "Cookie", "cookie-name=cookie-value; Domain=docs.foo.com; Path=/accounts; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly" );
+//    interaction.respond()
+//        .status( 201 );
+//    interactions.add( interaction );
+//    // Create the client request.
+//    request.setMethod( "GET" );
+//    request.setURI( "/test-input-path" );
+//    //request.setVersion( "HTTP/1.1" );
+//    request.setHeader( "Host", "mock-host:1" );
+//    request.setHeader( "Cookie", "cookie-name=cookie-value; Domain=docs.foo.com; Path=/accounts; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly" );
+//
+//    // Execute the request.
+//    response = TestUtils.execute( server, request );
+//
+//    // Test the results.
+//    assertThat( response.getStatus(), is( 201 ) );
+//    fail( "TODO" );
+//  }
+
+//  @Ignore( "Need to figure out how to handle cookies since domain and path are separate." )
+//  @Test
+//  public void testResponseCookieRewrite() throws Exception {
+//    setUp( null );
+//    // Setup the server side request/response interaction.
+//    interaction.expect()
+//        .method( "GET" )
+//        .requestUrl( "http://mock-host:1/test-output-path-1" );
+//    interaction.respond()
+//        .status( 200 )
+//        .header( "Set-Cookie", "cookie-name=cookie-value; Domain=docs.foo.com; Path=/accounts; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly" );
+//    interactions.add( interaction );
+//    // Create the client request.
+//    request.setMethod( "GET" );
+//    request.setURI( "/test-input-path" );
+//    //request.setVersion( "HTTP/1.1" );
+//    request.setHeader( "Host", "mock-host:1" );
+//
+//    // Execute the request.
+//    response = TestUtils.execute( server, request );
+//
+//    // Test the results.
+//    assertThat( response.getStatus(), is( 200 ) );
+//    assertThat( response.get( HttpHeader.SET_COOKIE ), is( "TODO" ) );
+//    fail( "TODO" );
+//  }
+
+  @Test
+  public void testInboundJsonBodyRewrite() throws Exception {
+    setUp( null );
+
+    String inputJson = "{\"url\":\"http://mock-host:1/test-input-path\"}";
+    String outputJson = "{\"url\":\"http://mock-host:1/test-output-path-1\"}";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "PUT" )
+        .requestUrl( "http://mock-host:1/test-output-path-1" )
+        .content( outputJson, Charset.forName( "UTF-8" ) );
+    interaction.respond()
+        .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "PUT" );
+    request.setURI( "/test-input-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "mock-host:1" );
+    request.setHeader( "Content-Type", "application/json; charset=UTF-8" );
+    request.setContent( inputJson );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), is( 200 ) );
+  }
+
+  @Test
+  public void testInboundXmlBodyRewrite() throws Exception {
+    setUp( null );
+    String input = "<root attribute=\"http://mock-host:1/test-input-path\">http://mock-host:1/test-input-path</root>";
+    String output = null;
+    if(System.getProperty("java.vendor").contains("IBM")){
+      output = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><root attribute=\"http://mock-host:1/test-output-path-1\">http://mock-host:1/test-output-path-1</root>";
+    }else {
+      output = "<?xml version=\"1.0\" standalone=\"no\"?><root attribute=\"http://mock-host:1/test-output-path-1\">http://mock-host:1/test-output-path-1</root>";
+    }
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "PUT" )
+        .requestUrl( "http://mock-host:1/test-output-path-1" )
+        .content( output, Charset.forName( "UTF-8" ) );
+    interaction.respond()
+        .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "PUT" );
+    request.setURI( "/test-input-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "mock-host:1" );
+    request.setHeader( "Content-Type", "application/xml; charset=UTF-8" );
+    request.setContent( input );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), is( 200 ) );
+  }
+
+  // MatcherAssert.assertThat( XmlConverters.the( outputHtml ), XmlMatchers.hasXPath( "/html" ) );
+  @Test
+  public void testOutboundJsonBodyRewrite() throws Exception {
+    setUp( null );
+
+    String input = "{\"url\":\"http://mock-host:1/test-input-path\"}";
+    String expect = "{\"url\":\"http://mock-host:1/test-output-path-1\"}";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "PUT" )
+        .requestUrl( "http://mock-host:1/test-output-path-1" );
+    interaction.respond()
+        .status( 200 )
+        .contentType( "application/json" )
+        .content( input, Charset.forName( "UTF-8" ) );
+    interactions.add( interaction );
+    request.setMethod( "PUT" );
+    request.setURI( "/test-input-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "mock-host:1" );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), is( 200 ) );
+    assertThat( response.getContent(), is( expect ) );
+  }
+
+  @Test
+  public void testOutboundHtmlBodyRewrite() throws Exception {
+    setUp( null );
+
+    String input = "<html><head></head><body><a href=\"http://mock-host:1/test-input-path\">link text</a></body></html>";
+    String output = "<html><head></head><body><a href=\"http://mock-host:1/test-output-path-1\">link text</a></body></html>";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "PUT" )
+        .requestUrl( "http://mock-host:1/test-output-path-1" )
+        .content( output, Charset.forName( "UTF-8" ) );
+    interaction.respond()
+        .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "PUT" );
+    request.setURI( "/test-input-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "mock-host:1" );
+    request.setHeader( "Content-Type", "application/html; charset=UTF-8" );
+    request.setContent( input );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), is( 200 ) );
+  }
+
+  @Test
+  public void testInboundHtmlFormRewrite() throws Exception {
+    setUp( null );
+
+    String input = "Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21&url=http%3A%2F%2Fmock-host%3A1%2Ftest-input-path";
+    String expect = "Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21&url=http%3A%2F%2Fmock-host%3A1%2Ftest-output-path-1";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "PUT" )
+        .requestUrl( "http://mock-host:1/test-output-path-1" )
+        .content( expect, Charset.forName( "UTF-8" ) );
+    interaction.respond()
+        .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "PUT" );
+    request.setURI( "/test-input-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "mock-host:1" );
+    request.setHeader( "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8" );
+    request.setContent( input );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), is( 200 ) );
+  }
+
+  @Test
+  public void testRequestUrlRewriteWithFilterInitParam() throws Exception {
+    Map<String,String> initParams = new HashMap<>();
+    initParams.put( "request.url", "test-rule-2" );
+    setUp( initParams );
+
+    String input = "<root/>";
+    String expect = "<root/>";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "PUT" )
+        .requestUrl( "http://mock-host:42/test-output-path-2" )
+        .contentType( "text/xml" )
+        .characterEncoding( "UTF-8" )
+        .content( expect, Charset.forName( "UTF-8" ) );
+    interaction.respond()
+        .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "PUT" );
+    request.setURI( "/test-input-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "mock-host:42" );
+    request.setHeader( "Content-Type", "text/xml; charset=UTF-8" );
+    request.setContent( input );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), is( 200 ) );
+  }
+
+  @Test
+  public void testRequestHeaderRewriteWithFilterInitParam() throws Exception {
+    Map<String,String> initParams = new HashMap<>();
+    initParams.put( "request.headers", "test-filter-2" );
+    setUp( initParams );
+
+    String input = "<root/>";
+    String expect = "<root/>";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "PUT" )
+        .requestUrl( "http://mock-host:42/test-output-path-1" )
+        .contentType( "text/xml" )
+        .characterEncoding( "UTF-8" )
+        .content( expect, Charset.forName( "UTF-8" ) )
+        .header( "Location", "http://mock-host:42/test-output-path-2" );
+    interaction.respond()
+        .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "PUT" );
+    request.setURI( "/test-input-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "mock-host:42" );
+    request.setHeader( "Location", "http://mock-host:42/test-input-path-1" );
+    request.setHeader( "Content-Type", "text/xml; charset=UTF-8" );
+    request.setContent( input );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), is( 200 ) );
+  }
+
+//  @Ignore( "Not Implemented Yet" )
+//  @Test
+//  public void testRequestCookieRewriteWithFilterInitParam() {
+//    fail( "TODO" );
+//  }
+
+  @Test
+  public void testRequestJsonBodyRewriteWithFilterInitParam() throws Exception {
+    Map<String,String> initParams = new HashMap<>();
+    //initParams.put( "url, "" );
+    initParams.put( "request.body", "test-filter-2" );
+    //initParams.put( "response", "" );
+    setUp( initParams );
+
+    String inputJson = "{\"url\":\"http://mock-host:42/test-input-path-1\"}";
+    String expectJson = "{\"url\":\"http://mock-host:42/test-output-path-2\"}";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "PUT" )
+        .requestUrl( "http://mock-host:42/test-output-path-1" )
+        .contentType( "application/json" )
+        .content( expectJson, Charset.forName( "UTF-8" ) );
+    interaction.respond()
+        .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "PUT" );
+    request.setURI( "/test-input-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "mock-host:42" );
+    request.setHeader( "Content-Type", "application/json; charset=UTF-8" );
+    request.setContent( inputJson );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), is( 200 ) );
+  }
+
+  @Test
+  public void testRequestXmlBodyRewriteWithFilterInitParam() throws Exception {
+    Map<String,String> initParams = new HashMap<>();
+    initParams.put( "request.body", "test-filter-2" );
+    setUp( initParams );
+
+    String input = "<root url='http://mock-host:42/test-input-path-1'><url>http://mock-host:42/test-input-path-1</url></root>";
+    String expect = "<root url='http://mock-host:42/test-output-path-2'><url>http://mock-host:42/test-output-path-2</url></root>";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "PUT" )
+        .requestUrl( "http://mock-host:42/test-output-path-1" )
+        .contentType( "text/xml" )
+        .characterEncoding( "UTF-8" )
+        .content( expect, Charset.forName( "UTF-8" ) );
+    interaction.respond()
+        .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "PUT" );
+    request.setURI( "/test-input-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "mock-host:42" );
+    request.setHeader( "Content-Type", "text/xml; charset=UTF-8" );
+    request.setContent( input );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), is( 200 ) );
+  }
+
+  @Test
+  public void testRequestXmlBodyRewriteWithFilterInitParamForInvalidFilterConfig() throws Exception {
+    Enumeration<Appender> realAppenders = NoOpAppender.setUp();
+    try {
+
+      Map<String,String> initParams = new HashMap<>();
+      initParams.put( "request.body", "test-filter-3" );
+      setUp( initParams );
+
+      String input = "<root url='http://mock-host:42/test-input-path-1'><url>http://mock-host:42/test-input-path-2</url></root>";
+      String expect = "<root url='http://mock-host:42/test-input-path-2'><url>http://mock-host:42/test-input-path-2</url></root>";
+
+      // Setup the server side request/response interaction.
+      interaction.expect()
+          .method( "PUT" )
+          .requestUrl( "http://mock-host:42/test-output-path-1" )
+          .contentType( "text/xml" )
+          .characterEncoding( "UTF-8" )
+          .content( expect, Charset.forName( "UTF-8" ) );
+      interaction.respond()
+          .status( 200 );
+      interactions.add( interaction );
+      request.setMethod( "PUT" );
+      request.setURI( "/test-input-path" );
+      //request.setVersion( "HTTP/1.1" );
+      request.setHeader( "Host", "mock-host:42" );
+      request.setHeader( "Content-Type", "text/xml; charset=UTF-8" );
+      request.setContent( input );
+
+      // Execute the request.
+      response = TestUtils.execute( server, request );
+
+      // Test the results.
+      assertThat( response.getStatus(), is( 500 ) );
+    } finally {
+      NoOpAppender.tearDown( realAppenders );
+    }
+  }
+
+  @Test
+  public void testRequestFormBodyRewriteWithFilterInitParam() throws Exception {
+    Map<String,String> initParams = new HashMap<>();
+    initParams.put( "request.body", "test-filter-2" );
+    setUp( initParams );
+
+    String input = "Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21&url=http%3A%2F%2Fmock-host%3A1%2Ftest-input-path";
+    String expect = "Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21&url=http%3A%2F%2Fmock-host%3A1%2Ftest-output-path-2";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "PUT" )
+        .requestUrl( "http://mock-host:1/test-output-path-1" )
+        .content( expect, Charset.forName( "UTF-8" ) )
+        .characterEncoding( "UTF-8" );
+    interaction.respond()
+        .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "PUT" );
+    request.setURI( "/test-input-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "mock-host:1" );
+    request.setHeader( "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8" );
+    request.setContent( input );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), is( 200 ) );
+  }
+
+  @Test
+  public void testResponseHeaderRewriteWithFilterInitParam() throws Exception {
+    Map<String,String> initParams = new HashMap<>();
+    initParams.put( "response.headers", "test-filter-2" );
+    setUp( initParams );
+
+    String output = "<root url='http://mock-host:42/test-input-path-2'><url>http://mock-host:42/test-input-path-3</url></root>";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "GET" )
+        .requestUrl( "http://mock-host:42/test-output-path-1" );
+    interaction.respond()
+        .content( output, Charset.forName( "UTF-8" ) )
+        .contentType( "text/xml" )
+        .header( "Location", "http://mock-host:42/test-input-path-4" )
+        .status( 307 );
+    interactions.add( interaction );
+    request.setMethod( "GET" );
+    request.setURI( "/test-input-path-1" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "mock-host:42" );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), is( 307 ) );
+    assertThat( response.get( HttpHeader.LOCATION ), is( "http://mock-host:42/test-output-path-2" ) );
+
+    String actual = response.getContent();
+
+    assertThat( the( actual ), hasXPath( "/root/@url", equalTo( "http://mock-host:42/test-output-path-1" ) ) );
+    assertThat( the( actual ), hasXPath( "/root/url/text()", equalTo( "http://mock-host:42/test-output-path-1" ) ) );
+  }
+
+//  @Ignore( "Not Implemented Yet" )
+//  @Test
+//  public void testResponseCookieRewriteWithFilterInitParam() {
+//    fail( "TODO" );
+//  }
+
+  @Test
+  public void testResponseJsonBodyRewriteWithFilterInitParam() throws Exception {
+    Map<String,String> initParams = new HashMap<>();
+    //initParams.put( "url, "" );
+    initParams.put( "response.body", "test-filter-2" );
+    //initParams.put( "response", "" );
+    setUp( initParams );
+
+    String responseJson = "{\"url\":\"http://mock-host:42/test-input-path-1\"}";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "GET" )
+        .requestUrl( "http://mock-host:42/test-output-path-1" );
+    interaction.respond()
+        .contentType( "application/json" )
+        .content( responseJson, Charset.forName( "UTF-8" ) )
+        .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "GET" );
+    request.setURI( "/test-input-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "mock-host:42" );
+    request.setHeader( "Content-Type", "application/json; charset=UTF-8" );
+    request.setContent( responseJson );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    assertThat( response.getStatus(), is( 200 ) );
+    JsonAssert.with( response.getContent() ).assertThat( "$.url", is( "http://mock-host:42/test-output-path-2" ) );
+  }
+
+  @Test
+  public void testResponseHtmlBodyRewriteWithFilterInitParam() throws Exception {
+    Map<String,String> initParams = new HashMap<>();
+    //initParams.put( "url, "" );
+    initParams.put( "response.body", "test-filter-4" );
+    //initParams.put( "response", "" );
+    setUp( initParams );
+
+    String responseHtml = "<!DOCTYPE html>\n" +
+        "<html>\n" +
+        "  <head>\n" +
+        "    <meta charset=\"UTF-8\">\n" +
+        "    <link rel=\"stylesheet\" href=\"pretty.css\">\n" +
+        "    <script src=\"script.js\"></script>\n" +
+        "  </head>\n" +
+        "  <body>\n" +
+        "  </body>\n" +
+        "</html>";
+    String rewrittenResponseHtml = "<!DOCTYPE html>\n" +
+        "<html>\n" +
+        "  <head>\n" +
+        "    <meta charset=\"UTF-8\">\n" +
+        "    <link rel=\"stylesheet\" href=\"http://someotherhost/stylesheets/pretty.css\">\n" +
+        "    <script src=\"script.js\"></script>\n" +
+        "  </head>\n" +
+        "  <body>\n" +
+        "  </body>\n" +
+        "</html>";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "GET" )
+        .requestUrl( "http://mock-host:42/test-output-path-1" );
+    interaction.respond()
+        .contentType( "application/html" )
+        .content( responseHtml, Charset.forName( "UTF-8" ) )
+        .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "GET" );
+    request.setURI( "/test-input-path" );
+    request.setHeader( "Host", "mock-host:42" );
+    request.setHeader( "Content-Type", "application/html" );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    assertThat( response.getStatus(), is( 200 ) );
+    String content = response.getContent();
+    assertThat(content, is(rewrittenResponseHtml));
+  }
+
+  @Test
+  public void testResponseXmlBodyRewriteWithFilterInitParam() throws Exception {
+    Map<String,String> initParams = new HashMap<>();
+    initParams.put( "response.body", "test-filter-2" );
+    setUp( initParams );
+
+    String output = "<root url='http://mock-host:42/test-input-path-1'><url>http://mock-host:42/test-input-path-1</url></root>";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "GET" )
+        .requestUrl( "http://mock-host:42/test-output-path-1" );
+    interaction.respond()
+        .content( output, Charset.forName( "UTF-8" ) )
+        .contentType( "text/xml" )
+        .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "GET" );
+    request.setURI( "/test-input-path" );
+    request.setVersion( "HTTP/1.0" );
+    request.setHeader( "Host", "mock-host:42" );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), is( 200 ) );
+
+    String actual = response.getContent();
+
+    assertThat( the( actual ), hasXPath( "/root/@url", equalTo( "http://mock-host:42/test-output-path-2" ) ) );
+    assertThat( the( actual ), hasXPath( "/root/url/text()", equalTo( "http://mock-host:42/test-output-path-2" ) ) );
+  }
+
+  @Test
+  public void testResponseHtmlBodyRewriteCSSImport() throws Exception {
+    Map<String,String> initParams = new HashMap<>();
+    //initParams.put( "url, "" );
+    initParams.put( "response.body", "test-filter-5" );
+    //initParams.put( "response", "" );
+    setUp( initParams );
+
+    String responseHtml = "<html>" +
+                          "  <head>" +
+                          "    <style type=\"text/css\">@import \"pretty.css\";</style>" +
+                          "  </head>" +
+                          "</html>";
+    String responseHtmlOne = "<html>" +
+                          "  <head>" +
+                          "    <style type=\"text/css\">@import \"http://0.0.0.0:0/stylesheets/pretty.css\";</style>" +
+                          "  </head>" +
+                          "</html>";
+    String responseHtmlTwo = "<html>" +
+                          "  <head>" +
+                          "    <style type=\"text/css\">@import \"http://localhost:0/stylesheets/pretty.css\";</style>" +
+                          "  </head>" +
+                          "</html>";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+               .method( "GET" )
+               .requestUrl( "http://mock-host:42/test-output-path-1" );
+    interaction.respond()
+               .contentType( "application/html" )
+               .content( responseHtml, Charset.forName( "UTF-8" ) )
+               .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "GET" );
+    request.setURI( "/test-input-path" );
+    request.setHeader( "Host", "mock-host:42" );
+    request.setHeader( "Content-Type", "application/html" );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    assertThat( response.getStatus(), is( 200 ) );
+    String content = response.getContent();
+//    assertThat( the( content ), hasXPath( "//style/text()", equalTo( "@import \\\"http://0.0.0.0:0/stylesheets/pretty.css\\\";" ) ) );
+    assertThat(content, anyOf( is(responseHtmlOne), is(responseHtmlTwo)));
+  }
+
+  /**
+   * Test the prefix function
+   * @see KNOX-994
+   * @since 0.14.0
+   */
+  @Test
+  public void testResponseHtmlBodyRewritePrefixFunctionTestPrefix() throws Exception {
+
+    Map<String,String> initParams = new HashMap<>();
+    initParams.put( "response.body", "test-filter-6" );
+    setUp( initParams );
+
+    String responseHtml = "<html><div src=\"'components/navbar/navbar.html?v=1496201914075\"></div></html>";
+    String responseHtmlOne = "<html><div src=\"'http://0.0.0.0:0/zeppelin/components/navbar/navbar.html?v=1496201914075\"></div></html>";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "GET" )
+        .requestUrl( "http://mock-host:42/test-output-path-1" );
+    interaction.respond()
+        .contentType( "application/html" )
+        .content( responseHtml, Charset.forName( "UTF-8" ) )
+        .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "GET" );
+    request.setURI( "/test-input-path" );
+    request.setHeader( "Host", "mock-host:42" );
+    request.setHeader( "Content-Type", "application/html" );
+
+    // Execute the request.
+    response = TestUtils.execute( server, request );
+
+    assertThat( response.getStatus(), is( 200 ) );
+    String content = response.getContent();
+
+    assertThat(content,  is(responseHtmlOne));
+
+  }
+
+
+  /**
+   * See KNOX-791
+   * @since 0.11.0
+   * @throws Exception
+   */
+  @Test
+  public void testResponseHtmlAttributeEscaping() throws Exception {
+    final Map<String, String> initParams = new HashMap<>();
+    initParams.put("response.body", "test-filter-4");
+    setUp(initParams);
+
+    final String responseHtml = "<!DOCTYPE html>\n" + "<html>\n" + "  <head>\n"
+        + "    <meta charset=\"UTF-8\">\n"
+        + "    <link rel=\"stylesheet\" href=\"pretty.css\">\n"
+        + "    <script escaped-data=\"&lt;&gt;\" src=\"script.js\"></script>\n"
+        + "  </head>\n" + "  <body>\n" + "  </body>\n" + "</html>";
+    final String rewrittenResponseHtml = "<!DOCTYPE html>\n" + "<html>\n"
+        + "  <head>\n" + "    <meta charset=\"UTF-8\">\n"
+        + "    <link rel=\"stylesheet\" href=\"http://someotherhost/stylesheets/pretty.css\">\n"
+        + "    <script escaped-data=\"&lt;&gt;\" src=\"script.js\"></script>\n"
+        + "  </head>\n" + "  <body>\n" + "  </body>\n" + "</html>";
+
+    // Setup the server side request/response interaction.
+    interaction.expect().method("GET")
+        .requestUrl("http://mock-host:42/test-output-path-1");
+    interaction.respond().contentType("application/html")
+        .content(responseHtml, Charset.forName("UTF-8")).status(200);
+    interactions.add(interaction);
+    request.setMethod("GET");
+    request.setURI("/test-input-path");
+    request.setHeader("Host", "mock-host:42");
+    request.setHeader("Content-Type", "application/html");
+
+    // Execute the request.
+    response = TestUtils.execute(server, request);
+
+    assertThat(response.getStatus(), is(200));
+    String content = response.getContent();
+    assertThat(content, is(rewrittenResponseHtml));
+  }
+  
+
+  private static class SetupFilter implements Filter {
+    @Override
+    public void init( FilterConfig filterConfig ) throws ServletException {
+    }
+
+    @Override
+    public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException {
+      HttpServletRequest httpRequest = ((HttpServletRequest)request);
+      StringBuffer sourceUrl = httpRequest.getRequestURL();
+      String queryString = httpRequest.getQueryString();
+      if( queryString != null ) {
+        sourceUrl.append( "?" );
+        sourceUrl.append( queryString );
+      }
+      try {
+        request.setAttribute(
+            AbstractGatewayFilter.SOURCE_REQUEST_URL_ATTRIBUTE_NAME,
+            Parser.parseLiteral( sourceUrl.toString() ) );
+      } catch( URISyntaxException e ) {
+        throw new ServletException( e );
+      }
+      chain.doFilter( request, response );
+    }
+
+    @Override
+    public void destroy() {
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/CookieScopeResponseWrapperTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/CookieScopeResponseWrapperTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/CookieScopeResponseWrapperTest.java
new file mode 100644
index 0000000..2c01fa8
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/CookieScopeResponseWrapperTest.java
@@ -0,0 +1,91 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.easymock.Capture;
+import org.easymock.EasyMock;
+import org.easymock.EasyMockSupport;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import javax.servlet.http.HttpServletResponse;
+
+public class CookieScopeResponseWrapperTest extends EasyMockSupport {
+
+  private HttpServletResponse mock;
+
+  private Capture<String> captureKey;
+
+  private Capture<String> captureValue;
+
+  @Before
+  public void init(){
+    mock = EasyMock.createNiceMock(HttpServletResponse.class);
+    captureKey = new Capture<>();
+    captureValue = new Capture<>();
+    mock.addHeader( EasyMock.capture(captureKey), EasyMock.capture(captureValue));
+    EasyMock.replay(mock);
+  }
+
+  @Test
+  public void testNoPath() {
+    CookieScopeResponseWrapper underTest = new CookieScopeResponseWrapper(mock, "gw");
+    underTest.addHeader("Set-Cookie", "SESSIONID=jn0zexg59r1jo1n66hd7tg5anl;HttpOnly;");
+
+    Assert.assertEquals("Set-Cookie", captureKey.getValue());
+    Assert.assertEquals("SESSIONID=jn0zexg59r1jo1n66hd7tg5anl;HttpOnly; Path=/gw/;", captureValue.getValue());
+  }
+
+  @Test
+  public void testRootPath() {
+    CookieScopeResponseWrapper underTest = new CookieScopeResponseWrapper(mock, "gw");
+    underTest.addHeader("Set-Cookie", "SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/; HttpOnly;");
+
+    Assert.assertEquals("Set-Cookie", captureKey.getValue());
+    Assert.assertEquals("SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/gw/; HttpOnly;", captureValue.getValue());
+  }
+
+  @Test
+  public void testMultiSegmentPath() {
+    CookieScopeResponseWrapper underTest = new CookieScopeResponseWrapper(mock, "some/path");
+    underTest.addHeader("Set-Cookie", "SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/; HttpOnly;");
+
+    Assert.assertEquals("Set-Cookie", captureKey.getValue());
+    Assert.assertEquals("SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/some/path/; HttpOnly;", captureValue.getValue());
+  }
+
+  @Test
+  public void testAlreadyScopedPath() {
+    CookieScopeResponseWrapper underTest = new CookieScopeResponseWrapper(mock, "some/path");
+    underTest.addHeader("Set-Cookie", "SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/already-scoped/; HttpOnly;");
+
+    Assert.assertEquals("Set-Cookie", captureKey.getValue());
+    Assert.assertEquals("SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/some/path/already-scoped/; HttpOnly;", captureValue.getValue());
+  }
+
+  @Test
+  public void testCaseSensitive() {
+    CookieScopeResponseWrapper underTest = new CookieScopeResponseWrapper(mock, "some/path");
+    underTest.addHeader("set-cookie", "SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/not-touched/; HttpOnly;");
+
+    Assert.assertEquals("set-cookie", captureKey.getValue());
+    Assert.assertEquals("SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/not-touched/; HttpOnly;", captureValue.getValue());
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest.java
new file mode 100644
index 0000000..d40edc9
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest.java
@@ -0,0 +1,303 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import com.jayway.jsonassert.JsonAssert;
+import org.apache.knox.gateway.filter.AbstractGatewayFilter;
+import org.apache.knox.gateway.filter.rewrite.api.FrontendFunctionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletFilter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.hadoop.test.TestUtils;
+import org.apache.hadoop.test.log.NoOpLogger;
+import org.apache.hadoop.test.mock.MockInteraction;
+import org.apache.hadoop.test.mock.MockServlet;
+import org.apache.http.auth.BasicUserPrincipal;
+import org.easymock.EasyMock;
+import org.eclipse.jetty.http.HttpTester;
+import org.eclipse.jetty.servlet.FilterHolder;
+import org.eclipse.jetty.servlet.ServletHolder;
+import org.eclipse.jetty.servlet.ServletTester;
+import org.eclipse.jetty.util.ArrayQueue;
+import org.eclipse.jetty.util.Attributes;
+import org.eclipse.jetty.util.AttributesMap;
+import org.eclipse.jetty.util.log.Log;
+import org.hamcrest.core.Is;
+import org.junit.Test;
+
+import javax.security.auth.Subject;
+import javax.servlet.DispatcherType;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.nio.charset.Charset;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.anyOf;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.fail;
+
+public class FrontendFunctionProcessorTest {
+
+  private ServletTester server;
+  private HttpTester.Request request;
+  private HttpTester.Response response;
+  private ArrayQueue<MockInteraction> interactions;
+  private MockInteraction interaction;
+
+  @SuppressWarnings("rawtypes")
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof FrontendFunctionProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + FrontendFunctionProcessor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    FrontendFunctionProcessor processor = new FrontendFunctionProcessor();
+    assertThat( processor.name(), is( "frontend" ) );
+  }
+
+  @Test
+  public void testNullHandling() throws Exception {
+    UrlRewriteEnvironment badEnv = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    UrlRewriteEnvironment goodEnv = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( goodEnv.getAttribute(FrontendFunctionDescriptor.FRONTEND_URI_ATTRIBUTE) ).andReturn( new URI( "http://mock-host:80/mock-root/mock-topo" ) ).anyTimes();
+    EasyMock.replay( badEnv,goodEnv );
+
+    FrontendFunctionProcessor processor = new FrontendFunctionProcessor();
+    try {
+      processor.initialize( null, null );
+    } catch ( IllegalArgumentException e ) {
+      assertThat( e.getMessage(), containsString( "environment" ) );
+    }
+    try {
+      processor.initialize( badEnv, null );
+    } catch ( IllegalArgumentException e ) {
+      assertThat( e.getMessage(), containsString( "org.apache.hadoop.knox.frontend.context.uri" ) );
+    }
+    processor.initialize( goodEnv, null );
+    processor.resolve( null, null );
+  }
+
+  public void setUp( String username, Map<String, String> initParams, Attributes attributes ) throws Exception {
+    ServiceRegistry mockServiceRegistry = EasyMock.createNiceMock( ServiceRegistry.class );
+    EasyMock.expect( mockServiceRegistry.lookupServiceURL( "test-cluster", "NAMENODE" ) ).andReturn( "test-nn-scheme://test-nn-host:411" ).anyTimes();
+    EasyMock.expect( mockServiceRegistry.lookupServiceURL( "test-cluster", "JOBTRACKER" ) ).andReturn( "test-jt-scheme://test-jt-host:511" ).anyTimes();
+
+    GatewayServices mockGatewayServices = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( mockGatewayServices.getService(GatewayServices.SERVICE_REGISTRY_SERVICE) ).andReturn( mockServiceRegistry ).anyTimes();
+
+    EasyMock.replay( mockServiceRegistry, mockGatewayServices );
+
+    String descriptorUrl = TestUtils.getResourceUrl( FrontendFunctionProcessorTest.class, "rewrite.xml" ).toExternalForm();
+
+    Log.setLog( new NoOpLogger() );
+
+    server = new ServletTester();
+    server.setContextPath( "/" );
+    server.getContext().addEventListener( new UrlRewriteServletContextListener() );
+    server.getContext().setInitParameter(
+        UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );
+
+    if( attributes != null ) {
+      server.getContext().setAttributes( attributes );
+    }
+    server.getContext().setAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE, "test-cluster" );
+    server.getContext().setAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE, mockGatewayServices );
+
+    FilterHolder setupFilter = server.addFilter( SetupFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
+    setupFilter.setFilter( new SetupFilter( username ) );
+    FilterHolder rewriteFilter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
+    if( initParams != null ) {
+      for( Map.Entry<String,String> entry : initParams.entrySet() ) {
+        rewriteFilter.setInitParameter( entry.getKey(), entry.getValue() );
+      }
+    }
+    rewriteFilter.setFilter( new UrlRewriteServletFilter() );
+
+    interactions = new ArrayQueue<MockInteraction>();
+
+    ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
+    servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );
+
+    server.start();
+
+    interaction = new MockInteraction();
+    request = HttpTester.newRequest();
+    response = null;
+  }
+
+  @Test
+  public void testFrontendFunctionsOnJsonRequestBody() throws Exception {
+    Map<String,String> initParams = new HashMap<>();
+    initParams.put( "response.body", "test-filter" );
+    setUp( "test-user", initParams, null );
+
+    String input = TestUtils.getResourceString( FrontendFunctionProcessorTest.class, "test-input-body.json", "UTF-8" );
+
+    interaction.expect()
+        .method( "GET" )
+        .requestUrl( "http://test-host:42/test-path" );
+    interaction.respond()
+        .status( 200 )
+        .contentType( "application/json" )
+        .characterEncoding( "UTF-8" )
+        .content( input, Charset.forName( "UTF-8" ) );
+    interactions.add( interaction );
+    request.setMethod( "GET" );
+    request.setURI( "/test-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "test-host:42" );
+
+    response = TestUtils.execute( server, request );
+
+    assertThat( response.getStatus(), Is.is( 200 ) );
+
+    String json = response.getContent();
+
+    // Note: The Jetty ServletTester/HttpTester doesn't return very good values.
+    JsonAssert.with( json ).assertThat( "$.url", anyOf( is( "http://localhost:0" ), is( "http://0.0.0.0:0" ) ) );
+    JsonAssert.with( json ).assertThat( "$.scheme", is( "http" ) );
+    JsonAssert.with( json ).assertThat( "$.host", anyOf( is( "localhost" ), is( "0.0.0.0" ) ) );
+    JsonAssert.with( json ).assertThat( "$.port", is( "0" ) );
+    JsonAssert.with( json ).assertThat( "$.addr", anyOf( is( "localhost:0" ), is( "0.0.0.0:0" ) ) );
+    JsonAssert.with( json ).assertThat( "$.address", anyOf( is( "localhost:0" ), is( "0.0.0.0:0" ) ) );
+    JsonAssert.with( json ).assertThat( "$.path", is( "" ) );
+    JsonAssert.with( json ).assertThat( "$.topology", is( "test-cluster" ) );
+  }
+
+  @Test
+  public void testFrontendFunctionsWithFrontendUriConfigOnJsonRequestBody() throws Exception {
+
+    // This hooks up the filter in rewrite.xml in this class' test resource directory.
+    Map<String,String> initParams = new HashMap<>();
+    initParams.put( "response.body", "test-filter" );
+
+    // This simulates having gateway.frontend.uri in gateway-site.xml
+    Attributes attributes = new AttributesMap(  );
+    attributes.setAttribute( FrontendFunctionDescriptor.FRONTEND_URI_ATTRIBUTE, new URI( "mock-frontend-scheme://mock-frontend-host:777/mock-frontend-path" ) );
+
+    setUp( "test-user", initParams, attributes );
+
+    String input = TestUtils.getResourceString( FrontendFunctionProcessorTest.class, "test-input-body.json", "UTF-8" );
+
+    interaction.expect()
+        .method( "GET" )
+        .requestUrl( "http://test-host:42/test-path" );
+    interaction.respond()
+        .status( 200 )
+        .contentType( "application/json" )
+        .characterEncoding( "UTF-8" )
+        .content( input, Charset.forName( "UTF-8" ) );
+    interactions.add( interaction );
+    request.setMethod( "GET" );
+    request.setURI( "/test-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "test-host:42" );
+
+    response = TestUtils.execute( server, request );
+
+    assertThat( response.getStatus(), Is.is( 200 ) );
+
+    String json = response.getContent();
+
+    // Note: The Jetty ServletTester/HttpTester doesn't return very good values.
+    JsonAssert.with( json ).assertThat( "$.url", is( "mock-frontend-scheme://mock-frontend-host:777/mock-frontend-path" ) );
+    JsonAssert.with( json ).assertThat( "$.scheme", is( "mock-frontend-scheme" ) );
+    JsonAssert.with( json ).assertThat( "$.host", is( "mock-frontend-host" ) );
+    JsonAssert.with( json ).assertThat( "$.port", is( "777" ) );
+    JsonAssert.with( json ).assertThat( "$.addr", is( "mock-frontend-host:777" ) );
+    JsonAssert.with( json ).assertThat( "$.address", is( "mock-frontend-host:777" ) );
+    JsonAssert.with( json ).assertThat( "$.path", is( "/mock-frontend-path" ) );
+  }
+
+  private static class SetupFilter implements Filter {
+    private Subject subject;
+
+    public SetupFilter( String userName ) {
+      subject = new Subject();
+      subject.getPrincipals().add( new BasicUserPrincipal( userName ) );
+    }
+
+    @Override
+    public void init( FilterConfig filterConfig ) throws ServletException {
+    }
+
+    @Override
+    public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException {
+      HttpServletRequest httpRequest = ((HttpServletRequest)request);
+      StringBuffer sourceUrl = httpRequest.getRequestURL();
+      String queryString = httpRequest.getQueryString();
+      if( queryString != null ) {
+        sourceUrl.append( "?" );
+        sourceUrl.append( queryString );
+      }
+      try {
+        request.setAttribute(
+            AbstractGatewayFilter.SOURCE_REQUEST_URL_ATTRIBUTE_NAME,
+            Parser.parseLiteral( sourceUrl.toString() ) );
+      } catch( URISyntaxException e ) {
+        throw new ServletException( e );
+      }
+      try {
+        Subject.doAs( subject, new PrivilegedExceptionAction<Void>() {
+          @Override
+          public Void run() throws Exception {
+            chain.doFilter( request, response );
+            return null;
+          }
+        } );
+      } catch( PrivilegedActionException e ) {
+        throw new ServletException( e );
+      }
+    }
+
+    @Override
+    public void destroy() {
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteContextImplTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteContextImplTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteContextImplTest.java
new file mode 100644
index 0000000..14db347
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteContextImplTest.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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.util.urltemplate.Params;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+import org.apache.knox.gateway.util.urltemplate.Template;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public class UrlRewriteContextImplTest {
+
+  @Test
+  public void testResolve() throws Exception {
+
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( environment.resolve( "test-env-param-name" ) ).andReturn( Arrays.asList( "test-env-param-value" ) ).anyTimes();
+
+    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
+    EasyMock.expect( resolver.resolve( "test-ctx-param-name" ) ).andReturn( Arrays.asList( "test-ctx-param-value" ) );
+
+    EasyMock.replay( environment, resolver );
+
+    Map<String,UrlRewriteFunctionProcessor> functions = new HashMap<>();
+
+    UrlRewriter.Direction direction = UrlRewriter.Direction.OUT;
+    Template template = Parser.parseLiteral( "scheme://host:port/dir/file" );
+
+    UrlRewriteContextImpl context = new UrlRewriteContextImpl( environment, resolver, functions, direction, template );
+
+    Params params = context.getParameters();
+    List<String> values = params.resolve( "test-env-param-name" );
+    assertThat( values, notNullValue() );
+    assertThat( values.size(), is( 1 ) );
+    assertThat( values.get( 0 ), is( "test-env-param-value" ) );
+
+    values = params.resolve( "test-ctx-param-name" );
+    assertThat( values, notNullValue() );
+    assertThat( values.size(), is( 1 ) );
+    assertThat( values.get( 0 ), is( "test-ctx-param-value" ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteResponseTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteResponseTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteResponseTest.java
new file mode 100644
index 0000000..d3a9e33
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteResponseTest.java
@@ -0,0 +1,171 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteProcessor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletFilter;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+import javax.activation.MimeTypeParseException;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.List;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.IsCollectionContaining.hasItems;
+
+public class UrlRewriteResponseTest {
+
+  @Test
+  public void testResolve() throws Exception {
+
+    UrlRewriteProcessor rewriter = EasyMock.createNiceMock( UrlRewriteProcessor.class );
+
+    ServletContext context = EasyMock.createNiceMock( ServletContext.class );
+    EasyMock.expect( context.getServletContextName() ).andReturn( "test-cluster-name" ).anyTimes();
+    EasyMock.expect( context.getInitParameter( "test-init-param-name" ) ).andReturn( "test-init-param-value" ).anyTimes();
+    EasyMock.expect( context.getAttribute( UrlRewriteServletContextListener.PROCESSOR_ATTRIBUTE_NAME ) ).andReturn( rewriter ).anyTimes();
+
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect( config.getInitParameter( "test-filter-init-param-name" ) ).andReturn( "test-filter-init-param-value" ).anyTimes();
+    EasyMock.expect( config.getServletContext() ).andReturn( context ).anyTimes();
+
+    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
+    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
+
+    EasyMock.replay( rewriter, context, config, request, response );
+
+    UrlRewriteResponse rewriteResponse = new UrlRewriteResponse( config, request, response );
+
+    List<String> names = rewriteResponse.resolve( "test-filter-init-param-name" );
+    assertThat( names.size(), is( 1 ) );
+    assertThat( names.get( 0 ), is( "test-filter-init-param-value" ) );
+  }
+
+  @Test
+  public void testResolveGatewayParams() throws Exception {
+
+    UrlRewriteProcessor rewriter = EasyMock.createNiceMock( UrlRewriteProcessor.class );
+
+    ServletContext context = EasyMock.createNiceMock( ServletContext.class );
+    EasyMock.expect( context.getAttribute( UrlRewriteServletContextListener.PROCESSOR_ATTRIBUTE_NAME ) ).andReturn( rewriter ).anyTimes();
+
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect( config.getServletContext() ).andReturn( context ).anyTimes();
+
+    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
+    EasyMock.expect( request.getScheme() ).andReturn( "mock-scheme" ).anyTimes();
+    EasyMock.expect( request.getLocalName() ).andReturn( "mock-host" ).anyTimes();
+    EasyMock.expect( request.getLocalPort() ).andReturn( 42 ).anyTimes();
+    EasyMock.expect( request.getContextPath() ).andReturn( "/mock-path" ).anyTimes();
+    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
+
+    EasyMock.replay( rewriter, context, config, request, response );
+
+    UrlRewriteResponse rewriteResponse = new UrlRewriteResponse( config, request, response );
+
+    List<String> url = rewriteResponse.resolve( "gateway.url" );
+    assertThat( url, hasItems( new String[]{ "mock-scheme://mock-host:42/mock-path" } ) );
+
+    List<String> scheme = rewriteResponse.resolve( "gateway.scheme" );
+    assertThat( scheme, hasItems( new String[]{ "mock-scheme" } ) );
+
+    List<String> host = rewriteResponse.resolve( "gateway.host" );
+    assertThat( host, hasItems( new String[]{ "mock-host" } ) );
+
+    List<String> port = rewriteResponse.resolve( "gateway.port" );
+    assertThat( port, hasItems( new String[]{ "42" } ) );
+
+    List<String> addr = rewriteResponse.resolve( "gateway.addr" );
+    assertThat( addr, hasItems( new String[]{ "mock-host:42" } ) );
+
+    List<String> address = rewriteResponse.resolve( "gateway.addr" );
+    assertThat( address, hasItems( new String[]{ "mock-host:42" } ) );
+
+    List<String> path = rewriteResponse.resolve( "gateway.path" );
+    assertThat( path, hasItems( new String[]{ "/mock-path" } ) );
+  }
+
+  @Test
+  public void testStreamResponse() throws IOException, MimeTypeParseException {
+    UrlRewriteProcessor rewriter = EasyMock.createNiceMock( UrlRewriteProcessor.class );
+    EasyMock.expect( rewriter.getConfig() ).andReturn( null ).anyTimes();
+
+    ServletContext context = EasyMock.createNiceMock( ServletContext.class );
+    EasyMock.expect( context.getAttribute( UrlRewriteServletContextListener.PROCESSOR_ATTRIBUTE_NAME ) ).andReturn( rewriter ).anyTimes();
+
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect( config.getInitParameter( UrlRewriteServletFilter.RESPONSE_BODY_FILTER_PARAM ) ).andReturn( "test-filter" ).anyTimes();
+    EasyMock.expect( config.getServletContext() ).andReturn( context ).anyTimes();
+
+    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
+    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
+
+    EasyMock.replay( rewriter, context, config, request, response );
+
+    UrlRewriteResponse rewriteResponse = new UrlRewriteResponse( config, request, response );
+
+    String content = "content to test gzip streaming";
+    testStreamResponseGzip ( content, rewriteResponse, false );
+    testStreamResponseGzip ( content, rewriteResponse, true );
+  }
+
+  private void testStreamResponseGzip( String content, UrlRewriteResponse rewriteResponse , boolean isGzip ) throws IOException {
+    File targetDir = new File( System.getProperty( "user.dir" ), "target" );
+    File inputFile = new File( targetDir, "input.test" );
+    File outputFile = new File( targetDir, "output.test" );
+    OutputStream outStream = null, output = null;
+    InputStream inStream = null, input = null;
+    try {
+      outStream = isGzip ? new GZIPOutputStream( new FileOutputStream( inputFile ) ) : new FileOutputStream( inputFile );
+      outStream.write( content.getBytes() );
+      outStream.close();
+
+      input = new FileInputStream( inputFile );
+      output = new FileOutputStream( outputFile );
+      rewriteResponse.streamResponse( input, output );
+
+      inStream = isGzip ? new GZIPInputStream( new FileInputStream( outputFile ) ) : new FileInputStream( outputFile );
+      assertThat( String.valueOf( IOUtils.toCharArray( inStream ) ), is( content ) );
+    } finally {
+      if ( inStream != null ) {
+        inStream.close();
+      }
+      if ( input != null ) {
+        input.close();
+      }
+      inputFile.delete();
+      outputFile.delete();
+    }
+  }
+}


[04/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/deploy/WebAppSecContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/deploy/WebAppSecContributor.java b/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/deploy/WebAppSecContributor.java
new file mode 100644
index 0000000..57d76fa
--- /dev/null
+++ b/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/deploy/WebAppSecContributor.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.knox.gateway.webappsec.deploy;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+public class WebAppSecContributor extends
+    ProviderDeploymentContributorBase {
+  private static final String ROLE = "webappsec";
+  private static final String NAME = "WebAppSec";
+  private static final String CSRF_SUFFIX = "_CSRF";
+  private static final String CSRF_FILTER_CLASSNAME = "CSRFPreventionFilter";
+  private static final String CSRF_ENABLED = "csrf.enabled";
+  private static final String CORS_SUFFIX = "_CORS";
+  private static final String CORS_FILTER_CLASSNAME = "com.thetransactioncompany.cors.CORSFilter";
+  private static final String CORS_ENABLED = "cors.enabled";
+  private static final String XFRAME_OPTIONS_SUFFIX = "_XFRAMEOPTIONS";
+  private static final String XFRAME_OPTIONS_FILTER_CLASSNAME = "XFrameOptionsFilter";
+  private static final String XFRAME_OPTIONS_ENABLED = "xframe.options.enabled";
+
+  @Override
+  public String getRole() {
+    return ROLE;
+  }
+
+  @Override
+  public String getName() {
+    return NAME;
+  }
+
+  @Override
+  public void initializeContribution(DeploymentContext context) {
+    super.initializeContribution(context);
+  }
+
+  @Override
+  public void contributeFilter(DeploymentContext context, Provider provider, Service service, 
+      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
+    
+    Provider webappsec = context.getTopology().getProvider(ROLE, NAME);
+    if (webappsec != null && webappsec.isEnabled()) {
+      Map<String,String> map = provider.getParams();
+      if (params == null) {
+        params = new ArrayList<FilterParamDescriptor>();
+      }
+
+      Map<String, String> providerParams = provider.getParams();
+      // CORS support
+      String corsEnabled = map.get(CORS_ENABLED);
+      if ( corsEnabled != null && corsEnabled.equals("true")) {
+        provisionConfig(resource, providerParams, params, "cors.");
+        resource.addFilter().name( getName() + CORS_SUFFIX ).role( getRole() ).impl( CORS_FILTER_CLASSNAME ).params( params );
+      }
+
+      // CRSF
+      params = new ArrayList<FilterParamDescriptor>();
+      String csrfEnabled = map.get(CSRF_ENABLED);
+      if ( csrfEnabled != null && csrfEnabled.equals("true")) {
+        provisionConfig(resource, providerParams, params, "csrf.");
+        resource.addFilter().name( getName() + CSRF_SUFFIX ).role( getRole() ).impl( CSRF_FILTER_CLASSNAME ).params( params );
+      }
+
+      // X-Frame-Options - clickjacking protection
+      params = new ArrayList<FilterParamDescriptor>();
+      String xframeOptionsEnabled = map.get(XFRAME_OPTIONS_ENABLED);
+      if ( xframeOptionsEnabled != null && xframeOptionsEnabled.equals("true")) {
+        provisionConfig(resource, providerParams, params, "xframe.");
+        resource.addFilter().name( getName() + XFRAME_OPTIONS_SUFFIX ).role( getRole() ).impl( XFRAME_OPTIONS_FILTER_CLASSNAME ).params( params );
+      }
+    }
+  }
+
+  private void provisionConfig(ResourceDescriptor resource, Map<String,String> providerParams,
+      List<FilterParamDescriptor> params, String prefix) {
+    for(Entry<String, String> entry : providerParams.entrySet()) {
+      if (entry.getKey().startsWith(prefix)) {
+        params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
+      }
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/filter/CSRFPreventionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/filter/CSRFPreventionFilter.java b/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/filter/CSRFPreventionFilter.java
new file mode 100644
index 0000000..862670f
--- /dev/null
+++ b/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/filter/CSRFPreventionFilter.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.knox.gateway.webappsec.filter;
+
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+public class CSRFPreventionFilter implements Filter {
+  private static final String CUSTOM_HEADER_PARAM = "csrf.customheader";
+  private static final String CUSTOM_METHODS_TO_IGNORE_PARAM = "csrf.methodstoignore";
+  private String  headerName = "X-XSRF-Header";
+  private String  mti = "GET,OPTIONS,HEAD";
+  private Set<String> methodsToIgnore = null;
+  
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+    String customHeader = filterConfig.getInitParameter(CUSTOM_HEADER_PARAM);
+    if (customHeader != null) {
+      headerName = customHeader;
+    }
+    String customMTI = filterConfig.getInitParameter(CUSTOM_METHODS_TO_IGNORE_PARAM);
+    if (customMTI != null) {
+      mti = customMTI;
+    }
+    String[] methods = mti.split(",");
+    methodsToIgnore = new HashSet<>();
+    for (int i = 0; i < methods.length; i++) {
+      methodsToIgnore.add(methods[i]);
+    }
+  }
+  
+  @Override
+  public void doFilter(ServletRequest request, ServletResponse response,
+      FilterChain chain) throws IOException, ServletException {
+    HttpServletRequest httpRequest = (HttpServletRequest)request;
+    if ( methodsToIgnore.contains( httpRequest.getMethod() ) || httpRequest.getHeader(headerName) != null ) {
+      chain.doFilter(request, response);
+    } else {
+      ((HttpServletResponse)response).sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing Required Header for Vulnerability Protection");
+    }
+  }
+
+  /* (non-Javadoc)
+   * @see javax.servlet.Filter#destroy()
+   */
+  @Override
+  public void destroy() {
+    // TODO Auto-generated method stub
+    
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/filter/XFrameOptionsFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/filter/XFrameOptionsFilter.java b/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/filter/XFrameOptionsFilter.java
new file mode 100644
index 0000000..3c67764
--- /dev/null
+++ b/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/filter/XFrameOptionsFilter.java
@@ -0,0 +1,137 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.webappsec.filter;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpServletResponseWrapper;
+
+/**
+ * This filter protects proxied webapps from clickjacking attacks that
+ * are possible through use of Frames to contain the proxied resources.
+ */
+public class XFrameOptionsFilter implements Filter {
+  private static final String X_FRAME_OPTIONS = "X-Frame-Options";
+  private static final String CUSTOM_HEADER_PARAM = "xframe.options";
+
+  private String option = "DENY";
+
+  /* (non-Javadoc)
+   * @see javax.servlet.Filter#destroy()
+   */
+  @Override
+  public void destroy() {
+  }
+
+  /* (non-Javadoc)
+   * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
+   */
+  @Override
+  public void doFilter(ServletRequest req, ServletResponse res,
+      FilterChain chain) throws IOException, ServletException {
+    ((HttpServletResponse) res).setHeader(X_FRAME_OPTIONS, option);
+    chain.doFilter(req, new XFrameOptionsResponseWrapper((HttpServletResponse) res));
+  }
+
+  /* (non-Javadoc)
+   * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
+   */
+  @Override
+  public void init(FilterConfig config) throws ServletException {
+    String customOption = config.getInitParameter(CUSTOM_HEADER_PARAM);
+    if (customOption != null) {
+      option = customOption;
+    }
+  }
+
+  public class XFrameOptionsResponseWrapper extends HttpServletResponseWrapper {
+    @Override
+    public void addHeader(String name, String value) {
+      // don't allow additional values to be added to
+      // the configured options value in topology
+      if (!name.equals(X_FRAME_OPTIONS)) {
+        super.addHeader(name, value);
+      }
+    }
+
+    @Override
+    public void setHeader(String name, String value) {
+      // don't allow overwriting of configured value
+      if (!name.equals(X_FRAME_OPTIONS)) {
+        super.setHeader(name, value);
+      }
+    }
+
+    /**
+     * construct a wrapper for this request
+     * 
+     * @param request
+     */
+    public XFrameOptionsResponseWrapper(HttpServletResponse response) {
+        super(response);
+    }
+
+    @Override
+    public String getHeader(String name) {
+        String headerValue = null;
+        if (name.equals(X_FRAME_OPTIONS)) {
+            headerValue = option;
+        }
+        else {
+          headerValue = super.getHeader(name);
+        }
+        return headerValue;
+    }
+
+    /**
+     * get the Header names
+     */
+    @Override
+    public Collection<String> getHeaderNames() {
+        List<String> names = (List<String>) super.getHeaderNames();
+        if (names == null) {
+          names = new ArrayList<String>();
+        }
+        names.add(X_FRAME_OPTIONS);
+        return names;
+    }
+
+    @Override
+    public Collection<String> getHeaders(String name) {
+        List<String> values = (List<String>) super.getHeaders(name);
+        if (name.equals(X_FRAME_OPTIONS)) {
+          if (values == null) {
+            values = new ArrayList<String>();
+          }
+          values.add(option);
+        }
+        return values;
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-webappsec/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-webappsec/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index 9a060d3..0000000
--- a/gateway-provider-security-webappsec/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.webappsec.deploy.WebAppSecContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-webappsec/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-webappsec/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..aee3e0b
--- /dev/null
+++ b/gateway-provider-security-webappsec/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.webappsec.deploy.WebAppSecContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-webappsec/src/test/java/org/apache/hadoop/gateway/webappsec/CSRFTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/test/java/org/apache/hadoop/gateway/webappsec/CSRFTest.java b/gateway-provider-security-webappsec/src/test/java/org/apache/hadoop/gateway/webappsec/CSRFTest.java
deleted file mode 100644
index baab4b2..0000000
--- a/gateway-provider-security-webappsec/src/test/java/org/apache/hadoop/gateway/webappsec/CSRFTest.java
+++ /dev/null
@@ -1,29 +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.hadoop.gateway.webappsec;
-
-import junit.framework.TestCase;
-
-import org.junit.Test;
-
-public class CSRFTest extends TestCase {
-  @Test
-  public void testCsrf() throws Exception {
-    assertTrue(true);
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-webappsec/src/test/java/org/apache/hadoop/gateway/webappsec/XFrameOptionsFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/test/java/org/apache/hadoop/gateway/webappsec/XFrameOptionsFilterTest.java b/gateway-provider-security-webappsec/src/test/java/org/apache/hadoop/gateway/webappsec/XFrameOptionsFilterTest.java
deleted file mode 100644
index cda73f6..0000000
--- a/gateway-provider-security-webappsec/src/test/java/org/apache/hadoop/gateway/webappsec/XFrameOptionsFilterTest.java
+++ /dev/null
@@ -1,193 +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.hadoop.gateway.webappsec;
-
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.Properties;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.hadoop.gateway.webappsec.filter.XFrameOptionsFilter;
-import org.easymock.EasyMock;
-import org.junit.Assert;
-import org.junit.Test;
-
-/**
- *
- */
-public class XFrameOptionsFilterTest {
-  /**
-   * 
-   */
-  private static final String X_FRAME_OPTIONS = "X-Frame-Options";
-  String options = null;
-  Collection<String> headerNames = null;
-  Collection<String> headers = null;
-
-  @Test
-  public void testDefaultOptionsValue() throws Exception {
-    try {
-      XFrameOptionsFilter filter = new XFrameOptionsFilter();
-      Properties props = new Properties();
-      props.put("xframe.options.enabled", "true");
-      filter.init(new TestFilterConfig(props));
-
-      HttpServletRequest request = EasyMock.createNiceMock(
-          HttpServletRequest.class);
-      HttpServletResponse response = EasyMock.createNiceMock(
-          HttpServletResponse.class);
-      EasyMock.replay(request);
-      EasyMock.replay(response);
-
-      TestFilterChain chain = new TestFilterChain();
-      filter.doFilter(request, response, chain);
-      Assert.assertTrue("doFilterCalled should not be false.",
-          chain.doFilterCalled == true);
-      Assert.assertTrue("Options value incorrect should be DENY but is: "
-          + options, options.equals("DENY"));
-
-      Assert.assertTrue("X-Frame-Options count not equal to 1.", headers.size() == 1);
-    } catch (ServletException se) {
-      fail("Should NOT have thrown a ServletException.");
-    }
-  }
-
-  @Test
-  public void testConfiguredOptionsValue() throws Exception {
-    try {
-      XFrameOptionsFilter filter = new XFrameOptionsFilter();
-      Properties props = new Properties();
-      props.put("xframe.options.enabled", "true");
-      props.put("xframe.options", "SAMEORIGIN");
-      filter.init(new TestFilterConfig(props));
-
-      HttpServletRequest request = EasyMock.createNiceMock(
-          HttpServletRequest.class);
-      HttpServletResponse response = EasyMock.createNiceMock(
-          HttpServletResponse.class);
-      EasyMock.replay(request);
-      EasyMock.replay(response);
-
-      TestFilterChain chain = new TestFilterChain();
-      filter.doFilter(request, response, chain);
-      Assert.assertTrue("doFilterCalled should not be false.",
-          chain.doFilterCalled == true);
-      Assert.assertTrue("Options value incorrect should be SAMEORIGIN but is: "
-          + options, options.equals("SAMEORIGIN"));
-
-      Assert.assertTrue("X-Frame-Options count not equal to 1.", headers.size() == 1);
-    } catch (ServletException se) {
-      fail("Should NOT have thrown a ServletException.");
-    }
-  }
-
-//  @Test
-//  public void testExistingXFrameOptionHeader() throws Exception {
-//    try {
-//      XFrameOptionsFilter filter = new XFrameOptionsFilter();
-//      Properties props = new Properties();
-//      props.put("xframe.options.enabled", "true");
-//      props.put("xframe.options", "SAMEORIGIN");
-//      filter.init(new TestFilterConfig(props));
-//
-//      HttpServletRequest request = EasyMock.createNiceMock(
-//          HttpServletRequest.class);
-//      HttpServletResponse response = EasyMock.createNiceMock(
-//          HttpServletResponse.class);
-//      EasyMock.replay(request);
-//      EasyMock.replay(response);
-//
-//      TestFilterChain chain = new TestFilterChain();
-//      filter.doFilter(request, response, chain);
-//      Assert.assertTrue("doFilterCalled should not be false.",
-//          chain.doFilterCalled == true);
-//      Assert.assertTrue("Options value incorrect should be SAMEORIGIN but is: "
-//          + options, options.equals("SAMEORIGIN"));
-//
-//      Assert.assertTrue("X-Frame-Options count not equal to 1.", headers.size() == 1);
-//    } catch (ServletException se) {
-//      fail("Should NOT have thrown a ServletException.");
-//    }
-//  }
-
-  class TestFilterConfig implements FilterConfig {
-    Properties props = null;
-
-    public TestFilterConfig(Properties props) {
-      this.props = props;
-    }
-
-    @Override
-    public String getFilterName() {
-      return null;
-    }
-
-    /* (non-Javadoc)
-     * @see javax.servlet.FilterConfig#getServletContext()
-     */
-    @Override
-    public ServletContext getServletContext() {
-      return null;
-    }
-
-    /* (non-Javadoc)
-     * @see javax.servlet.FilterConfig#getInitParameter(java.lang.String)
-     */
-    @Override
-    public String getInitParameter(String name) {
-      return props.getProperty(name, null);
-    }
-
-    /* (non-Javadoc)
-     * @see javax.servlet.FilterConfig#getInitParameterNames()
-     */
-    @Override
-    public Enumeration<String> getInitParameterNames() {
-      return null;
-    }
-    
-  }
-
-  class TestFilterChain implements FilterChain {
-    boolean doFilterCalled = false;
-
-    /* (non-Javadoc)
-     * @see javax.servlet.FilterChain#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
-     */
-    @Override
-    public void doFilter(ServletRequest request, ServletResponse response)
-        throws IOException, ServletException {
-      doFilterCalled = true;
-      options = ((HttpServletResponse)response).getHeader(X_FRAME_OPTIONS);
-      headerNames = ((HttpServletResponse)response).getHeaderNames();
-      headers = ((HttpServletResponse)response).getHeaders(X_FRAME_OPTIONS);
-    }
-    
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-webappsec/src/test/java/org/apache/knox/gateway/webappsec/CSRFTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/test/java/org/apache/knox/gateway/webappsec/CSRFTest.java b/gateway-provider-security-webappsec/src/test/java/org/apache/knox/gateway/webappsec/CSRFTest.java
new file mode 100644
index 0000000..f21d3c2
--- /dev/null
+++ b/gateway-provider-security-webappsec/src/test/java/org/apache/knox/gateway/webappsec/CSRFTest.java
@@ -0,0 +1,29 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.webappsec;
+
+import junit.framework.TestCase;
+
+import org.junit.Test;
+
+public class CSRFTest extends TestCase {
+  @Test
+  public void testCsrf() throws Exception {
+    assertTrue(true);
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-webappsec/src/test/java/org/apache/knox/gateway/webappsec/XFrameOptionsFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/test/java/org/apache/knox/gateway/webappsec/XFrameOptionsFilterTest.java b/gateway-provider-security-webappsec/src/test/java/org/apache/knox/gateway/webappsec/XFrameOptionsFilterTest.java
new file mode 100644
index 0000000..2bb7bda
--- /dev/null
+++ b/gateway-provider-security-webappsec/src/test/java/org/apache/knox/gateway/webappsec/XFrameOptionsFilterTest.java
@@ -0,0 +1,193 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.webappsec;
+
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.Properties;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.webappsec.filter.XFrameOptionsFilter;
+import org.easymock.EasyMock;
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ *
+ */
+public class XFrameOptionsFilterTest {
+  /**
+   * 
+   */
+  private static final String X_FRAME_OPTIONS = "X-Frame-Options";
+  String options = null;
+  Collection<String> headerNames = null;
+  Collection<String> headers = null;
+
+  @Test
+  public void testDefaultOptionsValue() throws Exception {
+    try {
+      XFrameOptionsFilter filter = new XFrameOptionsFilter();
+      Properties props = new Properties();
+      props.put("xframe.options.enabled", "true");
+      filter.init(new TestFilterConfig(props));
+
+      HttpServletRequest request = EasyMock.createNiceMock(
+          HttpServletRequest.class);
+      HttpServletResponse response = EasyMock.createNiceMock(
+          HttpServletResponse.class);
+      EasyMock.replay(request);
+      EasyMock.replay(response);
+
+      TestFilterChain chain = new TestFilterChain();
+      filter.doFilter(request, response, chain);
+      Assert.assertTrue("doFilterCalled should not be false.",
+          chain.doFilterCalled == true);
+      Assert.assertTrue("Options value incorrect should be DENY but is: "
+          + options, options.equals("DENY"));
+
+      Assert.assertTrue("X-Frame-Options count not equal to 1.", headers.size() == 1);
+    } catch (ServletException se) {
+      fail("Should NOT have thrown a ServletException.");
+    }
+  }
+
+  @Test
+  public void testConfiguredOptionsValue() throws Exception {
+    try {
+      XFrameOptionsFilter filter = new XFrameOptionsFilter();
+      Properties props = new Properties();
+      props.put("xframe.options.enabled", "true");
+      props.put("xframe.options", "SAMEORIGIN");
+      filter.init(new TestFilterConfig(props));
+
+      HttpServletRequest request = EasyMock.createNiceMock(
+          HttpServletRequest.class);
+      HttpServletResponse response = EasyMock.createNiceMock(
+          HttpServletResponse.class);
+      EasyMock.replay(request);
+      EasyMock.replay(response);
+
+      TestFilterChain chain = new TestFilterChain();
+      filter.doFilter(request, response, chain);
+      Assert.assertTrue("doFilterCalled should not be false.",
+          chain.doFilterCalled == true);
+      Assert.assertTrue("Options value incorrect should be SAMEORIGIN but is: "
+          + options, options.equals("SAMEORIGIN"));
+
+      Assert.assertTrue("X-Frame-Options count not equal to 1.", headers.size() == 1);
+    } catch (ServletException se) {
+      fail("Should NOT have thrown a ServletException.");
+    }
+  }
+
+//  @Test
+//  public void testExistingXFrameOptionHeader() throws Exception {
+//    try {
+//      XFrameOptionsFilter filter = new XFrameOptionsFilter();
+//      Properties props = new Properties();
+//      props.put("xframe.options.enabled", "true");
+//      props.put("xframe.options", "SAMEORIGIN");
+//      filter.init(new TestFilterConfig(props));
+//
+//      HttpServletRequest request = EasyMock.createNiceMock(
+//          HttpServletRequest.class);
+//      HttpServletResponse response = EasyMock.createNiceMock(
+//          HttpServletResponse.class);
+//      EasyMock.replay(request);
+//      EasyMock.replay(response);
+//
+//      TestFilterChain chain = new TestFilterChain();
+//      filter.doFilter(request, response, chain);
+//      Assert.assertTrue("doFilterCalled should not be false.",
+//          chain.doFilterCalled == true);
+//      Assert.assertTrue("Options value incorrect should be SAMEORIGIN but is: "
+//          + options, options.equals("SAMEORIGIN"));
+//
+//      Assert.assertTrue("X-Frame-Options count not equal to 1.", headers.size() == 1);
+//    } catch (ServletException se) {
+//      fail("Should NOT have thrown a ServletException.");
+//    }
+//  }
+
+  class TestFilterConfig implements FilterConfig {
+    Properties props = null;
+
+    public TestFilterConfig(Properties props) {
+      this.props = props;
+    }
+
+    @Override
+    public String getFilterName() {
+      return null;
+    }
+
+    /* (non-Javadoc)
+     * @see javax.servlet.FilterConfig#getServletContext()
+     */
+    @Override
+    public ServletContext getServletContext() {
+      return null;
+    }
+
+    /* (non-Javadoc)
+     * @see javax.servlet.FilterConfig#getInitParameter(java.lang.String)
+     */
+    @Override
+    public String getInitParameter(String name) {
+      return props.getProperty(name, null);
+    }
+
+    /* (non-Javadoc)
+     * @see javax.servlet.FilterConfig#getInitParameterNames()
+     */
+    @Override
+    public Enumeration<String> getInitParameterNames() {
+      return null;
+    }
+    
+  }
+
+  class TestFilterChain implements FilterChain {
+    boolean doFilterCalled = false;
+
+    /* (non-Javadoc)
+     * @see javax.servlet.FilterChain#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
+     */
+    @Override
+    public void doFilter(ServletRequest request, ServletResponse response)
+        throws IOException, ServletException {
+      doFilterCalled = true;
+      options = ((HttpServletResponse)response).getHeader(X_FRAME_OPTIONS);
+      headerNames = ((HttpServletResponse)response).getHeaderNames();
+      headers = ((HttpServletResponse)response).getHeaders(X_FRAME_OPTIONS);
+    }
+    
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/conf/gateway-log4j.properties
----------------------------------------------------------------------
diff --git a/gateway-release/home/conf/gateway-log4j.properties b/gateway-release/home/conf/gateway-log4j.properties
index 52327da..85c623e 100644
--- a/gateway-release/home/conf/gateway-log4j.properties
+++ b/gateway-release/home/conf/gateway-log4j.properties
@@ -45,7 +45,7 @@ log4j.appender.auditfile=org.apache.log4j.DailyRollingFileAppender
 log4j.appender.auditfile.File=${app.log.dir}/${app.audit.file}
 log4j.appender.auditfile.Append = true
 log4j.appender.auditfile.DatePattern = '.'yyyy-MM-dd
-log4j.appender.auditfile.layout = org.apache.hadoop.gateway.audit.log4j.layout.AuditLayout
+log4j.appender.auditfile.layout = org.apache.knox.gateway.audit.log4j.layout.AuditLayout
 
 #log4j.logger.org.apache.hadoop.gateway.access=TRACE,httpaccess
 #log4j.additivity.org.apache.hadoop.gateway.access=false

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/conf/topologies/admin.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/conf/topologies/admin.xml b/gateway-release/home/conf/topologies/admin.xml
index 2f3d9a9..efcd3c8 100644
--- a/gateway-release/home/conf/topologies/admin.xml
+++ b/gateway-release/home/conf/topologies/admin.xml
@@ -34,11 +34,11 @@
             </param>
             <param>
                 <name>main.ldapRealm</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
                 <name>main.ldapContextFactory</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
                 <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/conf/topologies/knoxsso.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/conf/topologies/knoxsso.xml b/gateway-release/home/conf/topologies/knoxsso.xml
index c0b48ce..e00f26b 100644
--- a/gateway-release/home/conf/topologies/knoxsso.xml
+++ b/gateway-release/home/conf/topologies/knoxsso.xml
@@ -47,11 +47,11 @@
             </param>
             <param>
                 <name>main.ldapRealm</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
                 <name>main.ldapContextFactory</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
                 <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/conf/topologies/manager.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/conf/topologies/manager.xml b/gateway-release/home/conf/topologies/manager.xml
index 8ca9024..fd063d1 100644
--- a/gateway-release/home/conf/topologies/manager.xml
+++ b/gateway-release/home/conf/topologies/manager.xml
@@ -44,11 +44,11 @@
             </param>
             <param>
                 <name>main.ldapRealm</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
                 <name>main.ldapContextFactory</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
                 <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/conf/topologies/sandbox.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/conf/topologies/sandbox.xml b/gateway-release/home/conf/topologies/sandbox.xml
index dabee2b..90961ef 100644
--- a/gateway-release/home/conf/topologies/sandbox.xml
+++ b/gateway-release/home/conf/topologies/sandbox.xml
@@ -34,11 +34,11 @@
             </param>
             <param>
                 <name>main.ldapRealm</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
                 <name>main.ldapContextFactory</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
                 <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/templates/ad.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/templates/ad.xml b/gateway-release/home/templates/ad.xml
index 3398f13..2c17a64 100644
--- a/gateway-release/home/templates/ad.xml
+++ b/gateway-release/home/templates/ad.xml
@@ -22,8 +22,8 @@
             <role>authentication</role>
             <name>ShiroProvider</name>
             <enabled>true</enabled>
-            <param name="main.ldapRealm" value="org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm"/>
-            <param name="main.ldapContextFactory" value="org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory"/>
+            <param name="main.ldapRealm" value="org.apache.knox.gateway.shirorealm.KnoxLdapRealm"/>
+            <param name="main.ldapContextFactory" value="org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory"/>
             <param name="main.ldapRealm.contextFactory" value="$ldapContextFactory"/>
 
             <param name="main.ldapRealm.contextFactory.url" value="ldap://ad.qa.your-domain.com:389"/>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/templates/dynamicgroup.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/templates/dynamicgroup.xml b/gateway-release/home/templates/dynamicgroup.xml
index 300c390..ab390bf 100644
--- a/gateway-release/home/templates/dynamicgroup.xml
+++ b/gateway-release/home/templates/dynamicgroup.xml
@@ -40,11 +40,11 @@
             -->
             <param>
               <name>main.ldapRealm</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
               <name>main.ldapGroupContextFactory</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
               <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/templates/hs2-grouplookup-cache.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/templates/hs2-grouplookup-cache.xml b/gateway-release/home/templates/hs2-grouplookup-cache.xml
index 6482b27..9f9efc1 100644
--- a/gateway-release/home/templates/hs2-grouplookup-cache.xml
+++ b/gateway-release/home/templates/hs2-grouplookup-cache.xml
@@ -40,11 +40,11 @@
             -->
             <param>
               <name>main.ldapRealm</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
               <name>main.ldapGroupContextFactory</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
               <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/templates/sample.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/templates/sample.xml b/gateway-release/home/templates/sample.xml
index 2544e85..91e1fe6 100644
--- a/gateway-release/home/templates/sample.xml
+++ b/gateway-release/home/templates/sample.xml
@@ -25,11 +25,11 @@
             <name>ShiroProvider</name>
             <param>
                 <name>main.ldapRealm</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
                 <name>main.ldapContextFactory</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
                 <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/templates/sandbox-1-3.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/templates/sandbox-1-3.xml b/gateway-release/home/templates/sandbox-1-3.xml
index d3f7090..a71445a 100644
--- a/gateway-release/home/templates/sandbox-1-3.xml
+++ b/gateway-release/home/templates/sandbox-1-3.xml
@@ -25,11 +25,11 @@
             <name>ShiroProvider</name>
             <param>
                 <name>main.ldapRealm</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
                 <name>main.ldapContextFactory</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
                 <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/templates/sandbox.knoxrealm.ehcache.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/templates/sandbox.knoxrealm.ehcache.xml b/gateway-release/home/templates/sandbox.knoxrealm.ehcache.xml
index 572b9f4..79fbe3b 100644
--- a/gateway-release/home/templates/sandbox.knoxrealm.ehcache.xml
+++ b/gateway-release/home/templates/sandbox.knoxrealm.ehcache.xml
@@ -40,11 +40,11 @@
             -->
             <param>
               <name>main.ldapRealm</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
               <name>main.ldapGroupContextFactory</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
               <name>main.ldapRealm.contextFactory</name>
@@ -104,7 +104,7 @@
             -->
             <param>
                 <name>main.cacheManager</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxCacheManager</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxCacheManager</value>
             </param>
             <param>
               <name>main.securityManager.cacheManager</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/templates/sandbox.knoxrealm.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/templates/sandbox.knoxrealm.xml b/gateway-release/home/templates/sandbox.knoxrealm.xml
index ab1d387..b8ab4a1 100644
--- a/gateway-release/home/templates/sandbox.knoxrealm.xml
+++ b/gateway-release/home/templates/sandbox.knoxrealm.xml
@@ -40,11 +40,11 @@
             -->
             <param>
               <name>main.ldapRealm</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
               <name>main.ldapGroupContextFactory</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
               <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/templates/sandbox.knoxrealm1.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/templates/sandbox.knoxrealm1.xml b/gateway-release/home/templates/sandbox.knoxrealm1.xml
index 1e63903..5ba1bac 100644
--- a/gateway-release/home/templates/sandbox.knoxrealm1.xml
+++ b/gateway-release/home/templates/sandbox.knoxrealm1.xml
@@ -40,11 +40,11 @@
             -->
             <param>
               <name>main.ldapRealm</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
               <name>main.ldapGroupContextFactory</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
               <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/templates/sandbox.knoxrealm2.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/templates/sandbox.knoxrealm2.xml b/gateway-release/home/templates/sandbox.knoxrealm2.xml
index bba56d0..2ef7327 100644
--- a/gateway-release/home/templates/sandbox.knoxrealm2.xml
+++ b/gateway-release/home/templates/sandbox.knoxrealm2.xml
@@ -40,11 +40,11 @@
             -->
             <param>
               <name>main.ldapRealm</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
               <name>main.ldapContextFactory</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
               <name>main.ldapRealm.contextFactory</name>
@@ -71,11 +71,11 @@
             -->
             <param>
               <name>main.ldapGroupRealm</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
               <name>main.ldapGroupContextFactory</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
               <name>main.ldapGroupRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/templates/sandbox.knoxrealmdg.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/templates/sandbox.knoxrealmdg.xml b/gateway-release/home/templates/sandbox.knoxrealmdg.xml
index 2c7d8eb..e691ac2 100755
--- a/gateway-release/home/templates/sandbox.knoxrealmdg.xml
+++ b/gateway-release/home/templates/sandbox.knoxrealmdg.xml
@@ -40,11 +40,11 @@
             -->
             <param>
               <name>main.ldapRealm</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
               <name>main.ldapGroupContextFactory</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
               <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/templates/staticgroup.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/templates/staticgroup.xml b/gateway-release/home/templates/staticgroup.xml
index b06d0cc..78d8e59 100644
--- a/gateway-release/home/templates/staticgroup.xml
+++ b/gateway-release/home/templates/staticgroup.xml
@@ -45,11 +45,11 @@
             -->
             <param>
               <name>main.ldapRealm</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
               <name>main.ldapGroupContextFactory</name>
-              <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+              <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
               <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/home/templates/ui.xml
----------------------------------------------------------------------
diff --git a/gateway-release/home/templates/ui.xml b/gateway-release/home/templates/ui.xml
index 9a4a26d..b8c324c 100644
--- a/gateway-release/home/templates/ui.xml
+++ b/gateway-release/home/templates/ui.xml
@@ -34,11 +34,11 @@
             </param>
             <param>
                 <name>main.ldapRealm</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
                 <name>main.ldapContextFactory</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
                 <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/src/main/resources/META-INF/services/org.apache.hadoop.gateway.services.GatewayServices
----------------------------------------------------------------------
diff --git a/gateway-release/src/main/resources/META-INF/services/org.apache.hadoop.gateway.services.GatewayServices b/gateway-release/src/main/resources/META-INF/services/org.apache.hadoop.gateway.services.GatewayServices
deleted file mode 100644
index 8cf264d..0000000
--- a/gateway-release/src/main/resources/META-INF/services/org.apache.hadoop.gateway.services.GatewayServices
+++ /dev/null
@@ -1,20 +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.
-##########################################################################
-
-
-org.apache.hadoop.gateway.services.DefaultGatewayServices

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-release/src/main/resources/META-INF/services/org.apache.knox.gateway.services.GatewayServices
----------------------------------------------------------------------
diff --git a/gateway-release/src/main/resources/META-INF/services/org.apache.knox.gateway.services.GatewayServices b/gateway-release/src/main/resources/META-INF/services/org.apache.knox.gateway.services.GatewayServices
new file mode 100644
index 0000000..484a498
--- /dev/null
+++ b/gateway-release/src/main/resources/META-INF/services/org.apache.knox.gateway.services.GatewayServices
@@ -0,0 +1,20 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+
+org.apache.knox.gateway.services.DefaultGatewayServices

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server-launcher/pom.xml
----------------------------------------------------------------------
diff --git a/gateway-server-launcher/pom.xml b/gateway-server-launcher/pom.xml
index 9ff77fe..cb62577 100644
--- a/gateway-server-launcher/pom.xml
+++ b/gateway-server-launcher/pom.xml
@@ -60,7 +60,7 @@
                             </descriptorRefs>
                             <archive>
                                 <manifest>
-                                    <mainClass>org.apache.hadoop.gateway.launcher.Launcher</mainClass>
+                                    <mainClass>org.apache.knox.gateway.launcher.Launcher</mainClass>
                                 </manifest>
                             </archive>
                         </configuration>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server-xforwarded-filter/src/main/java/org/apache/hadoop/gateway/filter/CompositeEnumeration.java
----------------------------------------------------------------------
diff --git a/gateway-server-xforwarded-filter/src/main/java/org/apache/hadoop/gateway/filter/CompositeEnumeration.java b/gateway-server-xforwarded-filter/src/main/java/org/apache/hadoop/gateway/filter/CompositeEnumeration.java
deleted file mode 100644
index c5190e6..0000000
--- a/gateway-server-xforwarded-filter/src/main/java/org/apache/hadoop/gateway/filter/CompositeEnumeration.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.hadoop.gateway.filter;
-
-import java.util.Enumeration;
-import java.util.NoSuchElementException;
-
-public class CompositeEnumeration<T> implements Enumeration<T> {
-
-  private int index = 0;
-  private Enumeration<T>[] array;
-
-  public CompositeEnumeration(Enumeration<T>... enumerations) {
-    if( enumerations == null ) {
-      throw new IllegalArgumentException( "enumerations==null" );
-    }
-    this.array = enumerations;
-  }
-
-  @Override
-  public boolean hasMoreElements() {
-    while( array.length > 0 && index < array.length ) {
-      if( array[index].hasMoreElements() ) {
-        return true;
-      } else {
-        index++;
-      }
-    }
-    return false;
-  }
-
-  @Override
-  public T nextElement() {
-    if( hasMoreElements() ) {
-      return array[index].nextElement();
-    } else {
-      throw new NoSuchElementException();
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server-xforwarded-filter/src/main/java/org/apache/hadoop/gateway/filter/XForwardedHeaderFilter.java
----------------------------------------------------------------------
diff --git a/gateway-server-xforwarded-filter/src/main/java/org/apache/hadoop/gateway/filter/XForwardedHeaderFilter.java b/gateway-server-xforwarded-filter/src/main/java/org/apache/hadoop/gateway/filter/XForwardedHeaderFilter.java
deleted file mode 100644
index 4b46db3..0000000
--- a/gateway-server-xforwarded-filter/src/main/java/org/apache/hadoop/gateway/filter/XForwardedHeaderFilter.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.hadoop.gateway.filter;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-
-public class XForwardedHeaderFilter extends AbstractGatewayFilter {
-
-  @Override
-  protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
-    chain.doFilter( new XForwardedHeaderRequestWrapper( request ), response );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server-xforwarded-filter/src/main/java/org/apache/hadoop/gateway/filter/XForwardedHeaderRequestWrapper.java
----------------------------------------------------------------------
diff --git a/gateway-server-xforwarded-filter/src/main/java/org/apache/hadoop/gateway/filter/XForwardedHeaderRequestWrapper.java b/gateway-server-xforwarded-filter/src/main/java/org/apache/hadoop/gateway/filter/XForwardedHeaderRequestWrapper.java
deleted file mode 100644
index 07dc943..0000000
--- a/gateway-server-xforwarded-filter/src/main/java/org/apache/hadoop/gateway/filter/XForwardedHeaderRequestWrapper.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.
- */
-package org.apache.hadoop.gateway.filter;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.Hashtable;
-
-public class XForwardedHeaderRequestWrapper extends GatewayRequestWrapper {
-
-  private static final String X_FORWARDED_FOR = "X-Forwarded-For";
-  private static final String X_FORWARDED_FOR_LOWER = X_FORWARDED_FOR.toLowerCase();
-  private static final String X_FORWARDED_PROTO = "X-Forwarded-Proto";
-  private static final String X_FORWARDED_PROTO_LOWER = X_FORWARDED_PROTO.toLowerCase();
-  private static final String X_FORWARDED_PORT = "X-Forwarded-Port";
-  private static final String X_FORWARDED_PORT_LOWER = X_FORWARDED_PORT.toLowerCase();
-  private static final String X_FORWARDED_HOST = "X-Forwarded-Host";
-  private static final String X_FORWARDED_HOST_LOWER = X_FORWARDED_HOST.toLowerCase();
-  private static final String X_FORWARDED_SERVER = "X-Forwarded-Server";
-  private static final String X_FORWARDED_SERVER_LOWER = X_FORWARDED_SERVER.toLowerCase();
-  private static final String X_FORWARDED_CONTEXT = "X-Forwarded-Context";
-  private static final String X_FORWARDED_CONTEXT_LOWER = X_FORWARDED_CONTEXT.toLowerCase();
-  private static final ArrayList<String> headerNames = new ArrayList<>();
-
-  static {
-    headerNames.add(X_FORWARDED_FOR);
-    headerNames.add(X_FORWARDED_PROTO);
-    headerNames.add(X_FORWARDED_PORT);
-    headerNames.add(X_FORWARDED_HOST);
-    headerNames.add(X_FORWARDED_SERVER);
-    headerNames.add(X_FORWARDED_CONTEXT);
-  }
-
-  Hashtable<String,String> proxyHeaders = new Hashtable<String, String>();
-
-  public XForwardedHeaderRequestWrapper(HttpServletRequest request) {
-    super( request );
-    setHeader( X_FORWARDED_FOR_LOWER, getForwardedFor( request ) );
-    setHeader( X_FORWARDED_PROTO_LOWER, getForwardedProto( request ) );
-    setHeader( X_FORWARDED_PORT_LOWER, getForwardedPort( request ) );
-    setHeader( X_FORWARDED_HOST_LOWER, getForwardedHost( request ) );
-    setHeader( X_FORWARDED_SERVER_LOWER, getForwardedServer( request ) );
-    setHeader( X_FORWARDED_CONTEXT_LOWER, getForwardedContext( request ) );
-  }
-
-  @Override
-  public Enumeration<String> getHeaderNames() {
-    return new CompositeEnumeration<>( Collections.enumeration(headerNames), super.getHeaderNames() );
-  }
-
-  @Override
-  public Enumeration<String> getHeaders( String name ) {
-    name = name.toLowerCase();
-    Enumeration<String> values;
-    String value = proxyHeaders.get( name );
-    if( value != null ) {
-      values = Collections.enumeration(Arrays.asList(value));
-    } else {
-      values = super.getHeaders( name );
-    }
-    return values;
-  }
-
-  @Override
-  public String getHeader( String name ) {
-    name = name.toLowerCase();
-    String value = proxyHeaders.get( name );
-    if( value == null ) {
-      value = super.getHeader( name );
-    }
-    return value;
-  }
-
-  private void setHeader( String name, String value ) {
-    if( name != null && value != null ) {
-      proxyHeaders.put( name, value );
-    }
-  }
-
-  private static String getForwardedFor( HttpServletRequest request ) {
-    String value;
-    String curr = request.getHeader( X_FORWARDED_FOR );
-    String addr = request.getRemoteAddr();
-    if( curr == null ) {
-      value = addr;
-    } else {
-      value = curr + "," + addr;
-    }
-    return value;
-  }
-
-  private static String getForwardedProto( HttpServletRequest request ) {
-    String value = request.getHeader( X_FORWARDED_PROTO );
-    if( value == null ) {
-      value = request.isSecure() ? "https" : "http";
-    }
-    return value;
-  }
-
-  private static String getForwardedPort( HttpServletRequest request ) {
-    String value = request.getHeader( X_FORWARDED_PORT );
-    if( value == null ) {
-      String forwardedHost = getForwardedHost( request );
-      int separator = forwardedHost.indexOf( ":" );
-      if ( separator > 0 ) {
-          value = forwardedHost.substring(separator + 1, forwardedHost.length());
-      } else {
-          // use default ports
-          value = request.isSecure() ? "443" : "80";
-      }
-    }
-    return value;
-  }
-
-  private static String getForwardedHost( HttpServletRequest request ) {
-    String value = request.getHeader( X_FORWARDED_HOST );
-    if( value == null ) {
-      value = request.getHeader( "Host" );
-    }
-    return value;
-  }
-
-  private static String getForwardedServer( HttpServletRequest request ) {
-    return request.getServerName();
-  }
-
-  private static String getForwardedContext( HttpServletRequest request ) {
-    String remote = request.getHeader( X_FORWARDED_CONTEXT );
-    String local = request.getContextPath();
-    return ( remote == null ? "" : remote ) + ( local == null ? "" : local );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server-xforwarded-filter/src/main/java/org/apache/knox/gateway/filter/CompositeEnumeration.java
----------------------------------------------------------------------
diff --git a/gateway-server-xforwarded-filter/src/main/java/org/apache/knox/gateway/filter/CompositeEnumeration.java b/gateway-server-xforwarded-filter/src/main/java/org/apache/knox/gateway/filter/CompositeEnumeration.java
new file mode 100644
index 0000000..f1b7b0b
--- /dev/null
+++ b/gateway-server-xforwarded-filter/src/main/java/org/apache/knox/gateway/filter/CompositeEnumeration.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.knox.gateway.filter;
+
+import java.util.Enumeration;
+import java.util.NoSuchElementException;
+
+public class CompositeEnumeration<T> implements Enumeration<T> {
+
+  private int index = 0;
+  private Enumeration<T>[] array;
+
+  public CompositeEnumeration(Enumeration<T>... enumerations) {
+    if( enumerations == null ) {
+      throw new IllegalArgumentException( "enumerations==null" );
+    }
+    this.array = enumerations;
+  }
+
+  @Override
+  public boolean hasMoreElements() {
+    while( array.length > 0 && index < array.length ) {
+      if( array[index].hasMoreElements() ) {
+        return true;
+      } else {
+        index++;
+      }
+    }
+    return false;
+  }
+
+  @Override
+  public T nextElement() {
+    if( hasMoreElements() ) {
+      return array[index].nextElement();
+    } else {
+      throw new NoSuchElementException();
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server-xforwarded-filter/src/main/java/org/apache/knox/gateway/filter/XForwardedHeaderFilter.java
----------------------------------------------------------------------
diff --git a/gateway-server-xforwarded-filter/src/main/java/org/apache/knox/gateway/filter/XForwardedHeaderFilter.java b/gateway-server-xforwarded-filter/src/main/java/org/apache/knox/gateway/filter/XForwardedHeaderFilter.java
new file mode 100644
index 0000000..f0c6603
--- /dev/null
+++ b/gateway-server-xforwarded-filter/src/main/java/org/apache/knox/gateway/filter/XForwardedHeaderFilter.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.knox.gateway.filter;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+public class XForwardedHeaderFilter extends AbstractGatewayFilter {
+
+  @Override
+  protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
+    chain.doFilter( new XForwardedHeaderRequestWrapper( request ), response );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server-xforwarded-filter/src/main/java/org/apache/knox/gateway/filter/XForwardedHeaderRequestWrapper.java
----------------------------------------------------------------------
diff --git a/gateway-server-xforwarded-filter/src/main/java/org/apache/knox/gateway/filter/XForwardedHeaderRequestWrapper.java b/gateway-server-xforwarded-filter/src/main/java/org/apache/knox/gateway/filter/XForwardedHeaderRequestWrapper.java
new file mode 100644
index 0000000..f2e051e
--- /dev/null
+++ b/gateway-server-xforwarded-filter/src/main/java/org/apache/knox/gateway/filter/XForwardedHeaderRequestWrapper.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.
+ */
+package org.apache.knox.gateway.filter;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.Hashtable;
+
+public class XForwardedHeaderRequestWrapper extends GatewayRequestWrapper {
+
+  private static final String X_FORWARDED_FOR = "X-Forwarded-For";
+  private static final String X_FORWARDED_FOR_LOWER = X_FORWARDED_FOR.toLowerCase();
+  private static final String X_FORWARDED_PROTO = "X-Forwarded-Proto";
+  private static final String X_FORWARDED_PROTO_LOWER = X_FORWARDED_PROTO.toLowerCase();
+  private static final String X_FORWARDED_PORT = "X-Forwarded-Port";
+  private static final String X_FORWARDED_PORT_LOWER = X_FORWARDED_PORT.toLowerCase();
+  private static final String X_FORWARDED_HOST = "X-Forwarded-Host";
+  private static final String X_FORWARDED_HOST_LOWER = X_FORWARDED_HOST.toLowerCase();
+  private static final String X_FORWARDED_SERVER = "X-Forwarded-Server";
+  private static final String X_FORWARDED_SERVER_LOWER = X_FORWARDED_SERVER.toLowerCase();
+  private static final String X_FORWARDED_CONTEXT = "X-Forwarded-Context";
+  private static final String X_FORWARDED_CONTEXT_LOWER = X_FORWARDED_CONTEXT.toLowerCase();
+  private static final ArrayList<String> headerNames = new ArrayList<>();
+
+  static {
+    headerNames.add(X_FORWARDED_FOR);
+    headerNames.add(X_FORWARDED_PROTO);
+    headerNames.add(X_FORWARDED_PORT);
+    headerNames.add(X_FORWARDED_HOST);
+    headerNames.add(X_FORWARDED_SERVER);
+    headerNames.add(X_FORWARDED_CONTEXT);
+  }
+
+  Hashtable<String,String> proxyHeaders = new Hashtable<String, String>();
+
+  public XForwardedHeaderRequestWrapper(HttpServletRequest request) {
+    super( request );
+    setHeader( X_FORWARDED_FOR_LOWER, getForwardedFor( request ) );
+    setHeader( X_FORWARDED_PROTO_LOWER, getForwardedProto( request ) );
+    setHeader( X_FORWARDED_PORT_LOWER, getForwardedPort( request ) );
+    setHeader( X_FORWARDED_HOST_LOWER, getForwardedHost( request ) );
+    setHeader( X_FORWARDED_SERVER_LOWER, getForwardedServer( request ) );
+    setHeader( X_FORWARDED_CONTEXT_LOWER, getForwardedContext( request ) );
+  }
+
+  @Override
+  public Enumeration<String> getHeaderNames() {
+    return new CompositeEnumeration<>( Collections.enumeration(headerNames), super.getHeaderNames() );
+  }
+
+  @Override
+  public Enumeration<String> getHeaders( String name ) {
+    name = name.toLowerCase();
+    Enumeration<String> values;
+    String value = proxyHeaders.get( name );
+    if( value != null ) {
+      values = Collections.enumeration(Arrays.asList(value));
+    } else {
+      values = super.getHeaders( name );
+    }
+    return values;
+  }
+
+  @Override
+  public String getHeader( String name ) {
+    name = name.toLowerCase();
+    String value = proxyHeaders.get( name );
+    if( value == null ) {
+      value = super.getHeader( name );
+    }
+    return value;
+  }
+
+  private void setHeader( String name, String value ) {
+    if( name != null && value != null ) {
+      proxyHeaders.put( name, value );
+    }
+  }
+
+  private static String getForwardedFor( HttpServletRequest request ) {
+    String value;
+    String curr = request.getHeader( X_FORWARDED_FOR );
+    String addr = request.getRemoteAddr();
+    if( curr == null ) {
+      value = addr;
+    } else {
+      value = curr + "," + addr;
+    }
+    return value;
+  }
+
+  private static String getForwardedProto( HttpServletRequest request ) {
+    String value = request.getHeader( X_FORWARDED_PROTO );
+    if( value == null ) {
+      value = request.isSecure() ? "https" : "http";
+    }
+    return value;
+  }
+
+  private static String getForwardedPort( HttpServletRequest request ) {
+    String value = request.getHeader( X_FORWARDED_PORT );
+    if( value == null ) {
+      String forwardedHost = getForwardedHost( request );
+      int separator = forwardedHost.indexOf( ":" );
+      if ( separator > 0 ) {
+          value = forwardedHost.substring(separator + 1, forwardedHost.length());
+      } else {
+          // use default ports
+          value = request.isSecure() ? "443" : "80";
+      }
+    }
+    return value;
+  }
+
+  private static String getForwardedHost( HttpServletRequest request ) {
+    String value = request.getHeader( X_FORWARDED_HOST );
+    if( value == null ) {
+      value = request.getHeader( "Host" );
+    }
+    return value;
+  }
+
+  private static String getForwardedServer( HttpServletRequest request ) {
+    return request.getServerName();
+  }
+
+  private static String getForwardedContext( HttpServletRequest request ) {
+    String remote = request.getHeader( X_FORWARDED_CONTEXT );
+    String local = request.getContextPath();
+    return ( remote == null ? "" : remote ) + ( local == null ? "" : local );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/CompositeEnumerationTest.java
----------------------------------------------------------------------
diff --git a/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/CompositeEnumerationTest.java b/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/CompositeEnumerationTest.java
deleted file mode 100644
index 93029dd..0000000
--- a/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/CompositeEnumerationTest.java
+++ /dev/null
@@ -1,117 +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.hadoop.gateway.filter;
-
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.NoSuchElementException;
-
-import static junit.framework.TestCase.fail;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-public class CompositeEnumerationTest {
-
-  @Test
-  public void testBasics() {
-
-    String[] a = new String[]{ "1", "2" };
-    Enumeration<String> ea = Collections.enumeration( Arrays.asList( a ) );
-
-    String[] b = new String[]{ "3", "4" };
-    Enumeration<String> eb = Collections.enumeration( Arrays.asList( b ) );
-
-    CompositeEnumeration<String> ce = new CompositeEnumeration<String>( ea, eb );
-
-    assertThat( ce.nextElement(), is( "1" ) );
-    assertThat( ce.nextElement(), is( "2" ) );
-    assertThat( ce.nextElement(), is( "3" ) );
-    assertThat( ce.nextElement(), is( "4" ) );
-    assertThat( ce.hasMoreElements(), is( false ) );
-
-  }
-
-  @Test
-  public void testSingleValues() {
-    String[] a = new String[]{ "1" };
-    Enumeration<String> ea = Collections.enumeration( Arrays.asList( a ) );
-
-    String[] b = new String[]{ "2" };
-    Enumeration<String> eb = Collections.enumeration( Arrays.asList( b ) );
-
-    CompositeEnumeration<String> ce = new CompositeEnumeration<String>( ea, eb );
-
-    assertThat( ce.nextElement(), is( "1" ) );
-    assertThat( ce.nextElement(), is( "2" ) );
-    assertThat( ce.hasMoreElements(), is( false ) );
-  }
-
-  @Test
-  public void testEmptyEnumerations() {
-
-    String[] a = new String[]{ "1", "2" };
-    String[] b = new String[]{ "3", "4" };
-    String[] c = new String[]{};
-
-    Enumeration<String> e1 = Collections.enumeration( Arrays.asList( a ) );
-    Enumeration<String> e2 = Collections.enumeration( Arrays.asList( c ) );
-    CompositeEnumeration<String> ce = new CompositeEnumeration<String>( e1, e2 );
-    assertThat( ce.nextElement(), is( "1" ) );
-    assertThat( ce.nextElement(), is( "2" ) );
-    assertThat( ce.hasMoreElements(), is( false ) );
-
-    e1 = Collections.enumeration( Arrays.asList( c ) );
-    e2 = Collections.enumeration( Arrays.asList( a ) );
-    ce = new CompositeEnumeration<String>( e1, e2 );
-    assertThat( ce.nextElement(), is( "1" ) );
-    assertThat( ce.nextElement(), is( "2" ) );
-    assertThat( ce.hasMoreElements(), is( false ) );
-
-    e1 = Collections.enumeration( Arrays.asList( c ) );
-    e2 = Collections.enumeration( Arrays.asList( c ) );
-    ce = new CompositeEnumeration<String>( e1, e2 );
-    assertThat( ce.hasMoreElements(), is( false ) );
-  }
-
-  @Test
-  public void testEmpty() {
-    CompositeEnumeration<String> ce = new CompositeEnumeration<String>();
-    assertThat( ce.hasMoreElements(), is( false ) );
-
-    try {
-      ce.nextElement();
-      fail( "Should have throws NoSuchElementExcpetion" );
-    } catch( NoSuchElementException e ) {
-      // Expected.
-    }
-  }
-
-  @Test
-  public void testNulls() {
-    try {
-      CompositeEnumeration<String> ce = new CompositeEnumeration<String>( null );
-      fail( "Expected IllegalArgumentException" );
-    } catch( IllegalArgumentException e ) {
-      // Expected.
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/TestFilterAdapter.java
----------------------------------------------------------------------
diff --git a/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/TestFilterAdapter.java b/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/TestFilterAdapter.java
deleted file mode 100644
index 9207625..0000000
--- a/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/TestFilterAdapter.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.hadoop.gateway.filter;
-
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-
-public abstract class TestFilterAdapter implements Filter {
-
-  public abstract void doFilter( HttpServletRequest request, HttpServletResponse response, FilterChain chain ) throws IOException, ServletException;
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {}
-
-  @Override
-  public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException {
-    doFilter( (HttpServletRequest)request, (HttpServletResponse)response, chain );
-  }
-
-  @Override
-  public void destroy() {}
-
-}


[37/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/hadoop/gateway/inboundurl/api/InboundUrlFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/hadoop/gateway/inboundurl/api/InboundUrlFunctionDescriptorTest.java b/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/hadoop/gateway/inboundurl/api/InboundUrlFunctionDescriptorTest.java
deleted file mode 100644
index 59d1f8a..0000000
--- a/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/hadoop/gateway/inboundurl/api/InboundUrlFunctionDescriptorTest.java
+++ /dev/null
@@ -1,48 +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.hadoop.gateway.inboundurl.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class InboundUrlFunctionDescriptorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof InboundUrlFunctionDescriptor ) {
-        String name = ((InboundUrlFunctionDescriptor)object).name();
-        assertThat( name, is("inboundurl"));
-        return;
-      }
-    }
-    fail( "Failed to find " + InboundUrlFunctionDescriptor.class.getName() + " via service loader." );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/hadoop/gateway/inboundurl/impl/InboundUrlFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/hadoop/gateway/inboundurl/impl/InboundUrlFunctionProcessorTest.java b/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/hadoop/gateway/inboundurl/impl/InboundUrlFunctionProcessorTest.java
deleted file mode 100644
index f78bf50..0000000
--- a/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/hadoop/gateway/inboundurl/impl/InboundUrlFunctionProcessorTest.java
+++ /dev/null
@@ -1,140 +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.hadoop.gateway.inboundurl.impl;
-
-import com.google.common.collect.Lists;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteActionRewriteDescriptorExt;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteResponse;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletFilter;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteContextImpl;
-import org.junit.Test;
-
-import java.util.*;
-
-import org.easymock.EasyMock;
-
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class InboundUrlFunctionProcessorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof InboundUrlFunctionProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + InboundUrlFunctionProcessor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testServiceResolve() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    InboundUrlFunctionProcessor proc = null;
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof InboundUrlFunctionProcessor ) {
-        proc = (InboundUrlFunctionProcessor) object ;
-      }
-    }
-    if( proc == null )
-      fail( "Failed to find " + InboundUrlFunctionProcessor.class.getName() + " via service loader." );
-
-    Map<String,UrlRewriteFunctionProcessor> functions = new HashMap<>();
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    UrlRewriter.Direction direction = UrlRewriter.Direction.OUT;
-
-    List<String> parameters = Collections.singletonList("host");
-
-    Template template = Parser.parseLiteral( "https://localhost:8443/gateway/default/datanode/?host=http://foo:50075" );
-    UrlRewriteContextImpl ctx = new UrlRewriteContextImpl( environment, this.getRewriteResponse(), functions, direction, template );
-
-    List<String> result = proc.resolve(ctx, parameters);
-    assertThat( result.get(0), is( "http://foo:50075" ) );
-  }
-
-  private UrlRewriteResponse getRewriteResponse() throws Exception {
-    UrlRewriteProcessor rewriter = EasyMock.createNiceMock( UrlRewriteProcessor.class );
-    EasyMock.expect( rewriter.getConfig() ).andReturn( null ).anyTimes();
-
-    ServletContext context = EasyMock.createNiceMock( ServletContext.class );
-    EasyMock.expect( context.getAttribute( UrlRewriteServletContextListener.PROCESSOR_ATTRIBUTE_NAME ) ).andReturn( rewriter ).anyTimes();
-
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect( config.getInitParameter( UrlRewriteServletFilter.RESPONSE_BODY_FILTER_PARAM ) ).andReturn( "test-filter" ).anyTimes();
-    EasyMock.expect( config.getServletContext() ).andReturn( context ).anyTimes();
-
-    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
-    EasyMock.expect( request.getParameterValues("host" ) ).andReturn( new String[]{"http://foo:50075"}  ).anyTimes();
-
-    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
-
-    EasyMock.replay( rewriter, context, config, request, response );
-
-    return new UrlRewriteResponse( config, request, response );
-  }
-
-
-  @Test
-  public void testQueryParam() throws Exception {
-    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( environment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();
-    EasyMock.expect( environment.resolve( "cluster.name" ) ).andReturn(Collections.singletonList("test-cluster-name")).anyTimes();
-
-    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "query.param.host" ) ).andReturn( Lists.newArrayList( "http://foo:50075" ) ).anyTimes();
-    EasyMock.replay( gatewayServices, environment, resolver );
-
-    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-location" );
-    rule.pattern( "{*}://{*}:{*}/{**}/?{**}" );
-    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
-    rewrite.template( "{$inboundurl[host]}" );
-    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
-    rewriter.initialize( environment, descriptor );
-    Template input = Parser.parseLiteral( "https://localhost:8443/gateway/default/datanode/?host=http://foo:50075" );
-    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.OUT, "test-location" );
-    assertThat( output.toString(), is( "http://foo:50075" ) );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/knox/gateway/inboundurl/api/InboundUrlFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/knox/gateway/inboundurl/api/InboundUrlFunctionDescriptorTest.java b/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/knox/gateway/inboundurl/api/InboundUrlFunctionDescriptorTest.java
new file mode 100644
index 0000000..e8afe82
--- /dev/null
+++ b/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/knox/gateway/inboundurl/api/InboundUrlFunctionDescriptorTest.java
@@ -0,0 +1,48 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.inboundurl.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class InboundUrlFunctionDescriptorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof InboundUrlFunctionDescriptor ) {
+        String name = ((InboundUrlFunctionDescriptor)object).name();
+        assertThat( name, is("inboundurl"));
+        return;
+      }
+    }
+    fail( "Failed to find " + InboundUrlFunctionDescriptor.class.getName() + " via service loader." );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/knox/gateway/inboundurl/impl/InboundUrlFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/knox/gateway/inboundurl/impl/InboundUrlFunctionProcessorTest.java b/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/knox/gateway/inboundurl/impl/InboundUrlFunctionProcessorTest.java
new file mode 100644
index 0000000..e3bf9f7
--- /dev/null
+++ b/gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/knox/gateway/inboundurl/impl/InboundUrlFunctionProcessorTest.java
@@ -0,0 +1,140 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.inboundurl.impl;
+
+import com.google.common.collect.Lists;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptorFactory;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteActionRewriteDescriptorExt;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteResponse;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteProcessor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletFilter;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+import org.apache.knox.gateway.util.urltemplate.Template;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteContextImpl;
+import org.junit.Test;
+
+import java.util.*;
+
+import org.easymock.EasyMock;
+
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class InboundUrlFunctionProcessorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof InboundUrlFunctionProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + InboundUrlFunctionProcessor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testServiceResolve() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    InboundUrlFunctionProcessor proc = null;
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof InboundUrlFunctionProcessor ) {
+        proc = (InboundUrlFunctionProcessor) object ;
+      }
+    }
+    if( proc == null )
+      fail( "Failed to find " + InboundUrlFunctionProcessor.class.getName() + " via service loader." );
+
+    Map<String,UrlRewriteFunctionProcessor> functions = new HashMap<>();
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    UrlRewriter.Direction direction = UrlRewriter.Direction.OUT;
+
+    List<String> parameters = Collections.singletonList("host");
+
+    Template template = Parser.parseLiteral( "https://localhost:8443/gateway/default/datanode/?host=http://foo:50075" );
+    UrlRewriteContextImpl ctx = new UrlRewriteContextImpl( environment, this.getRewriteResponse(), functions, direction, template );
+
+    List<String> result = proc.resolve(ctx, parameters);
+    assertThat( result.get(0), is( "http://foo:50075" ) );
+  }
+
+  private UrlRewriteResponse getRewriteResponse() throws Exception {
+    UrlRewriteProcessor rewriter = EasyMock.createNiceMock( UrlRewriteProcessor.class );
+    EasyMock.expect( rewriter.getConfig() ).andReturn( null ).anyTimes();
+
+    ServletContext context = EasyMock.createNiceMock( ServletContext.class );
+    EasyMock.expect( context.getAttribute( UrlRewriteServletContextListener.PROCESSOR_ATTRIBUTE_NAME ) ).andReturn( rewriter ).anyTimes();
+
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect( config.getInitParameter( UrlRewriteServletFilter.RESPONSE_BODY_FILTER_PARAM ) ).andReturn( "test-filter" ).anyTimes();
+    EasyMock.expect( config.getServletContext() ).andReturn( context ).anyTimes();
+
+    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
+    EasyMock.expect( request.getParameterValues("host" ) ).andReturn( new String[]{"http://foo:50075"}  ).anyTimes();
+
+    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
+
+    EasyMock.replay( rewriter, context, config, request, response );
+
+    return new UrlRewriteResponse( config, request, response );
+  }
+
+
+  @Test
+  public void testQueryParam() throws Exception {
+    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( environment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();
+    EasyMock.expect( environment.resolve( "cluster.name" ) ).andReturn(Collections.singletonList("test-cluster-name")).anyTimes();
+
+    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
+    EasyMock.expect( resolver.resolve( "query.param.host" ) ).andReturn( Lists.newArrayList( "http://foo:50075" ) ).anyTimes();
+    EasyMock.replay( gatewayServices, environment, resolver );
+
+    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteRuleDescriptor rule = descriptor.addRule( "test-location" );
+    rule.pattern( "{*}://{*}:{*}/{**}/?{**}" );
+    UrlRewriteActionRewriteDescriptorExt rewrite = rule.addStep( "rewrite" );
+    rewrite.template( "{$inboundurl[host]}" );
+    UrlRewriteProcessor rewriter = new UrlRewriteProcessor();
+    rewriter.initialize( environment, descriptor );
+    Template input = Parser.parseLiteral( "https://localhost:8443/gateway/default/datanode/?host=http://foo:50075" );
+    Template output = rewriter.rewrite( resolver, input, UrlRewriter.Direction.OUT, "test-location" );
+    assertThat( output.toString(), is( "http://foo:50075" ) );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceAddressFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceAddressFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceAddressFunctionDescriptor.java
deleted file mode 100644
index bfe8933..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceAddressFunctionDescriptor.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.svcregfunc.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-public class ServiceAddressFunctionDescriptor implements UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
-
-  public static final String FUNCTION_NAME = "serviceAddr";
-
-  @Override
-  public String name() {
-    return FUNCTION_NAME;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceHostFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceHostFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceHostFunctionDescriptor.java
deleted file mode 100644
index cff251b..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceHostFunctionDescriptor.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.svcregfunc.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-public class ServiceHostFunctionDescriptor implements UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
-
-  public static final String FUNCTION_NAME = "serviceHost";
-
-  @Override
-  public String name() {
-    return FUNCTION_NAME;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceMappedAddressFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceMappedAddressFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceMappedAddressFunctionDescriptor.java
deleted file mode 100644
index ae12de0..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceMappedAddressFunctionDescriptor.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.svcregfunc.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-public class ServiceMappedAddressFunctionDescriptor implements UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
-
-  public static final String FUNCTION_NAME = "serviceMappedAddr";
-
-  @Override
-  public String name() {
-    return FUNCTION_NAME;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceMappedHostFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceMappedHostFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceMappedHostFunctionDescriptor.java
deleted file mode 100644
index dd8beb2..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceMappedHostFunctionDescriptor.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.svcregfunc.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-public class ServiceMappedHostFunctionDescriptor implements UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
-
-  public static final String FUNCTION_NAME = "serviceMappedHost";
-
-  @Override
-  public String name() {
-    return FUNCTION_NAME;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceMappedUrlFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceMappedUrlFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceMappedUrlFunctionDescriptor.java
deleted file mode 100644
index 8ea8271..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceMappedUrlFunctionDescriptor.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.svcregfunc.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-public class ServiceMappedUrlFunctionDescriptor implements UrlRewriteFunctionDescriptor<ServiceMappedUrlFunctionDescriptor> {
-
-  public static final String FUNCTION_NAME = "serviceMappedUrl";
-
-  @Override
-  public String name() {
-    return FUNCTION_NAME;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePathFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePathFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePathFunctionDescriptor.java
deleted file mode 100644
index ab69264..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePathFunctionDescriptor.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.svcregfunc.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-public class ServicePathFunctionDescriptor implements UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
-
-  public static final String FUNCTION_NAME = "servicePath";
-
-  @Override
-  public String name() {
-    return FUNCTION_NAME;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePortFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePortFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePortFunctionDescriptor.java
deleted file mode 100644
index cc05975..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePortFunctionDescriptor.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.svcregfunc.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-public class ServicePortFunctionDescriptor implements UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
-
-  public static final String FUNCTION_NAME = "servicePort";
-
-  @Override
-  public String name() {
-    return FUNCTION_NAME;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptor.java
deleted file mode 100644
index dc73dee..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptor.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.svcregfunc.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-public class ServiceSchemeFunctionDescriptor implements UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
-
-  public static final String FUNCTION_NAME = "serviceScheme";
-
-  @Override
-  public String name() {
-    return FUNCTION_NAME;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceUrlFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceUrlFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceUrlFunctionDescriptor.java
deleted file mode 100644
index 788c164..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceUrlFunctionDescriptor.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.svcregfunc.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-public class ServiceUrlFunctionDescriptor implements UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
-
-  public static final String FUNCTION_NAME = "serviceUrl";
-
-  @Override
-  public String name() {
-    return FUNCTION_NAME;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceAddressFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceAddressFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceAddressFunctionProcessor.java
deleted file mode 100644
index e7bafae..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceAddressFunctionProcessor.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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.svcregfunc.api.ServiceAddressFunctionDescriptor;
-import org.apache.hadoop.gateway.util.urltemplate.Host;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Port;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class ServiceAddressFunctionProcessor
-    extends ServiceRegistryFunctionProcessorBase<ServiceAddressFunctionDescriptor>
-    implements UrlRewriteFunctionProcessor<ServiceAddressFunctionDescriptor> {
-
-  @Override
-  public String name() {
-    return ServiceAddressFunctionDescriptor.FUNCTION_NAME;
-  }
-
-  @Override
-  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
-    List<String> results = null;
-    if( parameters != null ) {
-      UrlRewriter.Direction direction = context.getDirection();
-      results = new ArrayList<String>( parameters.size() );
-      for( String parameter : parameters ) {
-        parameter = resolve( parameter );
-        results.add( parameter );
-      }
-    }
-    return results;
-  }
-
-  public String resolve( String parameter ) throws Exception {
-    String addr = parameter;
-    String url = lookupServiceUrl( parameter );
-    if( url != null ) {
-      Template template = Parser.parseLiteral( url );
-      Host host = template.getHost();
-      String hostStr = null;
-      if( host != null ) {
-        hostStr = host.getFirstValue().getPattern();
-      }
-
-      Port port = template.getPort();
-      String portStr = null;
-      if( port != null ) {
-        portStr = port.getFirstValue().getPattern();
-      }
-
-      if( hostStr != null && portStr != null ) {
-        addr = hostStr + ":" + portStr;
-      } else if( host != null && port == null ) {
-        addr = hostStr;
-      } else if( host == null && port != null ) {
-        addr = ":" + portStr;
-      }
-    }
-    return addr;
-  }
-
-}
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceHostFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceHostFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceHostFunctionProcessor.java
deleted file mode 100644
index 7448d12..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceHostFunctionProcessor.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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.svcregfunc.api.ServiceHostFunctionDescriptor;
-import org.apache.hadoop.gateway.util.urltemplate.Host;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class ServiceHostFunctionProcessor
-    extends ServiceRegistryFunctionProcessorBase<ServiceHostFunctionDescriptor>
-    implements UrlRewriteFunctionProcessor<ServiceHostFunctionDescriptor> {
-
-  @Override
-  public String name() {
-    return ServiceHostFunctionDescriptor.FUNCTION_NAME;
-  }
-
-  @Override
-  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
-    List<String> results = null;
-    if( parameters != null ) {
-      results = new ArrayList<String>( parameters.size() );
-      for( String parameter : parameters ) {
-        String url = lookupServiceUrl( parameter );
-        if( url != null ) {
-          Template template = Parser.parseLiteral( url );
-          Host host = template.getHost();
-          if( host != null ) {
-            parameter = host.getFirstValue().getPattern();
-          }
-        }
-        results.add( parameter );
-      }
-    }
-    return results;
-  }
-
-}
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessor.java
deleted file mode 100644
index c5c8116..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessor.java
+++ /dev/null
@@ -1,110 +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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.hostmap.HostMapper;
-import org.apache.hadoop.gateway.services.hostmap.HostMapperService;
-import org.apache.hadoop.gateway.svcregfunc.api.ServiceMappedAddressFunctionDescriptor;
-import org.apache.hadoop.gateway.util.urltemplate.Host;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Port;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter.Direction;
-
-public class ServiceMappedAddressFunctionProcessor
-    extends ServiceRegistryFunctionProcessorBase<ServiceMappedAddressFunctionDescriptor>
-    implements UrlRewriteFunctionProcessor<ServiceMappedAddressFunctionDescriptor> {
-
-  private HostMapper hostmap = null;
-
-  @Override
-  public String name() {
-    return ServiceMappedAddressFunctionDescriptor.FUNCTION_NAME;
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, ServiceMappedAddressFunctionDescriptor descriptor ) throws Exception {
-    super.initialize( environment, descriptor );
-    HostMapperService hostmapService = services().getService( GatewayServices.HOST_MAPPING_SERVICE );
-    if( hostmapService != null ) {
-      hostmap = hostmapService.getHostMapper( cluster() );
-    }
-  }
-
-  @Override
-  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
-    List<String> results = null;
-    if( parameters != null ) {
-      Direction direction = context.getDirection();
-      results = new ArrayList<String>( parameters.size() );
-      for( String parameter : parameters ) {
-        parameter = resolve( direction, parameter );
-        results.add( parameter );
-      }
-    }
-    return results;
-  }
-
-  public String resolve( Direction direction, String parameter ) throws Exception {
-    String addr = parameter;
-    String url = lookupServiceUrl( parameter );
-    if( url != null ) {
-      Template template = Parser.parseLiteral( url );
-      Host host = template.getHost();
-      String hostStr = null;
-      if( host != null ) {
-        hostStr = host.getFirstValue().getPattern();
-        if( hostmap != null ) {
-          switch( direction ) {
-            case IN:
-              hostStr = hostmap.resolveInboundHostName( hostStr );
-              break;
-            case OUT:
-              hostStr = hostmap.resolveOutboundHostName( hostStr );
-              break;
-          }
-        }
-      }
-
-      Port port = template.getPort();
-      String portStr = null;
-      if( port != null ) {
-        portStr = port.getFirstValue().getPattern();
-      }
-
-      if( hostStr != null && portStr != null ) {
-        addr = hostStr + ":" + portStr;
-      } else if( host != null && port == null ) {
-        addr = hostStr;
-      } else if( host == null && port != null ) {
-        addr = ":" + portStr;
-      }
-    }
-    return addr;
-  }
-
-}
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessor.java
deleted file mode 100644
index 770aecd..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessor.java
+++ /dev/null
@@ -1,87 +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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.hostmap.HostMapper;
-import org.apache.hadoop.gateway.services.hostmap.HostMapperService;
-import org.apache.hadoop.gateway.svcregfunc.api.ServiceMappedHostFunctionDescriptor;
-import org.apache.hadoop.gateway.util.urltemplate.Host;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class ServiceMappedHostFunctionProcessor
-    extends ServiceRegistryFunctionProcessorBase<ServiceMappedHostFunctionDescriptor>
-    implements UrlRewriteFunctionProcessor<ServiceMappedHostFunctionDescriptor> {
-
-  private HostMapper hostmap;
-
-  @Override
-  public String name() {
-    return ServiceMappedHostFunctionDescriptor.FUNCTION_NAME;
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, ServiceMappedHostFunctionDescriptor descriptor ) throws Exception {
-    super.initialize( environment, descriptor );
-    HostMapperService hostmapService = services().getService( GatewayServices.HOST_MAPPING_SERVICE );
-    if( hostmapService != null ) {
-      hostmap = hostmapService.getHostMapper( cluster() );
-    }
-  }
-
-  @Override
-  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
-    List<String> results = null;
-    if( parameters != null ) {
-      results = new ArrayList<String>( parameters.size() );
-      for( String parameter : parameters ) {
-        String url = lookupServiceUrl( parameter );
-        if( url != null ) {
-          Template template = Parser.parseLiteral( url );
-          Host host = template.getHost();
-          if( host != null ) {
-            String hostStr = host.getFirstValue().getPattern();
-            if( hostmap != null ) {
-              switch( context.getDirection() ) {
-                case IN:
-                  parameter = hostmap.resolveInboundHostName( hostStr );
-                  break;
-                case OUT:
-                  parameter = hostmap.resolveOutboundHostName( hostStr );
-                  break;
-              }
-            } else {
-              parameter = hostStr;
-            }
-          }
-        }
-        results.add( parameter );
-      }
-    }
-    return results;
-  }
-
-}
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessor.java
deleted file mode 100644
index 2747681..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessor.java
+++ /dev/null
@@ -1,90 +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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.hostmap.HostMapper;
-import org.apache.hadoop.gateway.services.hostmap.HostMapperService;
-import org.apache.hadoop.gateway.svcregfunc.api.ServiceMappedUrlFunctionDescriptor;
-
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.List;
-
-public class ServiceMappedUrlFunctionProcessor
-    extends ServiceRegistryFunctionProcessorBase<ServiceMappedUrlFunctionDescriptor>
-    implements UrlRewriteFunctionProcessor<ServiceMappedUrlFunctionDescriptor> {
-
-  private HostMapper hostmap;
-
-  @Override
-  public String name() {
-    return ServiceMappedUrlFunctionDescriptor.FUNCTION_NAME;
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, ServiceMappedUrlFunctionDescriptor descriptor ) throws Exception {
-    super.initialize( environment, descriptor );
-    HostMapperService hostmapService = services().getService( GatewayServices.HOST_MAPPING_SERVICE );
-    if( hostmapService != null ) {
-      hostmap = hostmapService.getHostMapper( cluster() );
-    }
-  }
-
-  @Override
-  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
-    List<String> results = null;
-    if( parameters != null ) {
-      UrlRewriter.Direction direction = context.getDirection();
-      results = new ArrayList<String>( parameters.size() );
-      for( String parameter : parameters ) {
-        parameter = resolve( direction, parameter );
-        results.add( parameter );
-      }
-    }
-    return results;
-  }
-
-  public String resolve( UrlRewriter.Direction direction, String parameter ) throws Exception {
-    String url = lookupServiceUrl( parameter );
-    if( url != null ) {
-      URI outputUri;
-      URI inputUri = new URI( url );
-      String host = inputUri.getHost();
-      if( host != null && hostmap != null ) {
-        switch( direction ) {
-          case IN:
-            host = hostmap.resolveInboundHostName( host );
-            break;
-          case OUT:
-            host = hostmap.resolveOutboundHostName( host );
-            break;
-        }
-      }
-      outputUri = new URI( inputUri.getScheme(), inputUri.getUserInfo(), host, inputUri.getPort(), inputUri.getPath(), inputUri.getQuery(), inputUri.getFragment() );
-      parameter = outputUri.toString();
-    }
-    return parameter;
-  }
-
-}
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePathFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePathFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePathFunctionProcessor.java
deleted file mode 100644
index 1269ca9..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePathFunctionProcessor.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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.svcregfunc.api.ServicePathFunctionDescriptor;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Path;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class ServicePathFunctionProcessor
-    extends ServiceRegistryFunctionProcessorBase<ServicePathFunctionDescriptor>
-    implements UrlRewriteFunctionProcessor<ServicePathFunctionDescriptor> {
-
-  @Override
-  public String name() {
-    return ServicePathFunctionDescriptor.FUNCTION_NAME;
-  }
-
-  @Override
-  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
-    List<String> results = null;
-    if( parameters != null ) {
-      results = new ArrayList<String>( parameters.size() );
-      for( String parameter : parameters ) {
-        String url = lookupServiceUrl( parameter );
-        if( url != null ) {
-          Template template = Parser.parseLiteral( url );
-          List<Path> path = template.getPath();
-          if( path != null ) {
-            parameter = toString( path );
-          }
-        }
-        results.add( parameter );
-      }
-    }
-    return results;
-  }
-
-  private String toString( List<Path> paths ) {
-    StringBuilder s = new StringBuilder();
-    for( Path path: paths ) {
-      s.append( '/' );
-      s.append( path.getFirstValue().getPattern() );
-    }
-    if( s.length() == 0 ) {
-      s.append( '/' );
-    }
-    return s.toString();
-  }
-
-}
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePortFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePortFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePortFunctionProcessor.java
deleted file mode 100644
index d05620c..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServicePortFunctionProcessor.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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.svcregfunc.api.ServicePortFunctionDescriptor;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Port;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class ServicePortFunctionProcessor
-    extends ServiceRegistryFunctionProcessorBase<ServicePortFunctionDescriptor>
-    implements UrlRewriteFunctionProcessor<ServicePortFunctionDescriptor> {
-
-  @Override
-  public String name() {
-    return ServicePortFunctionDescriptor.FUNCTION_NAME;
-  }
-
-  @Override
-  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
-    List<String> results = null;
-    if( parameters != null ) {
-      results = new ArrayList<String>( parameters.size() );
-      for( String parameter : parameters ) {
-        String url = lookupServiceUrl( parameter );
-        if( url != null ) {
-          Template template = Parser.parseLiteral( url );
-          Port port = template.getPort();
-          if( port != null ) {
-            parameter = port.getFirstValue().getPattern();
-          }
-        }
-        results.add( parameter );
-      }
-    }
-    return results;
-  }
-
-}
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionProcessorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionProcessorBase.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionProcessorBase.java
deleted file mode 100644
index f14ff7b..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionProcessorBase.java
+++ /dev/null
@@ -1,81 +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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.ha.provider.HaProvider;
-import org.apache.hadoop.gateway.ha.provider.HaServletContextListener;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-
-abstract class ServiceRegistryFunctionProcessorBase<T extends UrlRewriteFunctionDescriptor> implements UrlRewriteFunctionProcessor<T> {
-
-  private String cluster;
-  private GatewayServices services;
-  private ServiceRegistry registry;
-  private HaProvider haProvider;
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, T descriptor ) throws Exception {
-    if( environment == null ) {
-      throw new IllegalArgumentException( "environment==null" );
-    }
-    cluster = environment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE );
-    if( cluster == null ) {
-      throw new IllegalArgumentException( "cluster==null" );
-    }
-    services = environment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE );
-    if( services == null ) {
-      throw new IllegalArgumentException( "services==null" );
-    }
-    registry = services.getService( GatewayServices.SERVICE_REGISTRY_SERVICE );
-    if( registry == null ) {
-      throw new IllegalArgumentException( "registry==null" );
-    }
-    haProvider = environment.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME);
-  }
-
-  @Override
-  public void destroy() throws Exception {
-    registry = null;
-    cluster = null;
-  }
-
-  public String lookupServiceUrl( String role ) throws Exception {
-    if (haProvider != null && haProvider.isHaEnabled(role)) {
-       return haProvider.getActiveURL(role);
-    }
-    return registry.lookupServiceURL( cluster, role );
-  }
-
-  String cluster() {
-    return cluster;
-  }
-
-  GatewayServices services() {
-    return services;
-  }
-
-  ServiceRegistry registry() {
-    return registry;
-  }
-
-}
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessor.java
deleted file mode 100644
index 4c5f03b..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessor.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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.svcregfunc.api.ServiceSchemeFunctionDescriptor;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Scheme;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class ServiceSchemeFunctionProcessor
-    extends ServiceRegistryFunctionProcessorBase<ServiceSchemeFunctionDescriptor>
-    implements UrlRewriteFunctionProcessor<ServiceSchemeFunctionDescriptor> {
-
-  @Override
-  public String name() {
-    return ServiceSchemeFunctionDescriptor.FUNCTION_NAME;
-  }
-
-  @Override
-  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
-    List<String> results = null;
-    if( parameters != null ) {
-      results = new ArrayList<String>( parameters.size() );
-      for( String parameter : parameters ) {
-        String url = lookupServiceUrl( parameter );
-        if( url != null && !url.equals( parameter ) ) {
-          Template template = Parser.parseLiteral( url );
-          Scheme scheme = template.getScheme();
-          if( scheme != null ) {
-            parameter = scheme.getFirstValue().getPattern();
-          }
-        }
-        results.add( parameter );
-      }
-    }
-    return results;
-  }
-
-}
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceUrlFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceUrlFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceUrlFunctionProcessor.java
deleted file mode 100644
index 912fd3f..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceUrlFunctionProcessor.java
+++ /dev/null
@@ -1,64 +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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.svcregfunc.api.ServiceUrlFunctionDescriptor;
-
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.List;
-
-public class ServiceUrlFunctionProcessor
-    extends ServiceRegistryFunctionProcessorBase<ServiceUrlFunctionDescriptor>
-    implements UrlRewriteFunctionProcessor<ServiceUrlFunctionDescriptor> {
-
-  @Override
-  public String name() {
-    return ServiceUrlFunctionDescriptor.FUNCTION_NAME;
-  }
-
-  @Override
-  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
-    List<String> results = null;
-    if( parameters != null ) {
-      UrlRewriter.Direction direction = context.getDirection();
-      results = new ArrayList<String>( parameters.size() );
-      for( String parameter : parameters ) {
-        parameter = resolve( parameter );
-        results.add( parameter );
-      }
-    }
-    return results;
-  }
-
-  private String resolve( String parameter ) throws Exception {
-     String url = lookupServiceUrl( parameter );
-     if( url != null ) {
-        URI outputUri;
-        URI inputUri = new URI( url );
-        String host = inputUri.getHost();
-        outputUri = new URI( inputUri.getScheme(), inputUri.getUserInfo(), host, inputUri.getPort(), inputUri.getPath(), inputUri.getQuery(), inputUri.getFragment() );
-        parameter = outputUri.toString();
-     }
-     return parameter;
-  }
-}
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceAddressFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceAddressFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceAddressFunctionDescriptor.java
new file mode 100644
index 0000000..5ba0014
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceAddressFunctionDescriptor.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.knox.gateway.svcregfunc.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+public class ServiceAddressFunctionDescriptor implements
+    UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
+
+  public static final String FUNCTION_NAME = "serviceAddr";
+
+  @Override
+  public String name() {
+    return FUNCTION_NAME;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceHostFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceHostFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceHostFunctionDescriptor.java
new file mode 100644
index 0000000..37382d8
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceHostFunctionDescriptor.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.knox.gateway.svcregfunc.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+public class ServiceHostFunctionDescriptor implements
+    UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
+
+  public static final String FUNCTION_NAME = "serviceHost";
+
+  @Override
+  public String name() {
+    return FUNCTION_NAME;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceMappedAddressFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceMappedAddressFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceMappedAddressFunctionDescriptor.java
new file mode 100644
index 0000000..8c7ad62
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceMappedAddressFunctionDescriptor.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.svcregfunc.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+public class ServiceMappedAddressFunctionDescriptor implements UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
+
+  public static final String FUNCTION_NAME = "serviceMappedAddr";
+
+  @Override
+  public String name() {
+    return FUNCTION_NAME;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceMappedHostFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceMappedHostFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceMappedHostFunctionDescriptor.java
new file mode 100644
index 0000000..a852be9
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceMappedHostFunctionDescriptor.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.knox.gateway.svcregfunc.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+public class ServiceMappedHostFunctionDescriptor implements
+    UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
+
+  public static final String FUNCTION_NAME = "serviceMappedHost";
+
+  @Override
+  public String name() {
+    return FUNCTION_NAME;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceMappedUrlFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceMappedUrlFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceMappedUrlFunctionDescriptor.java
new file mode 100644
index 0000000..9b5d65a
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceMappedUrlFunctionDescriptor.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.knox.gateway.svcregfunc.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+public class ServiceMappedUrlFunctionDescriptor implements
+    UrlRewriteFunctionDescriptor<ServiceMappedUrlFunctionDescriptor> {
+
+  public static final String FUNCTION_NAME = "serviceMappedUrl";
+
+  @Override
+  public String name() {
+    return FUNCTION_NAME;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServicePathFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServicePathFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServicePathFunctionDescriptor.java
new file mode 100644
index 0000000..ca61b95
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServicePathFunctionDescriptor.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.svcregfunc.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+public class ServicePathFunctionDescriptor implements UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
+
+  public static final String FUNCTION_NAME = "servicePath";
+
+  @Override
+  public String name() {
+    return FUNCTION_NAME;
+  }
+
+}


[45/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaServiceConfigConstants.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaServiceConfigConstants.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaServiceConfigConstants.java
deleted file mode 100644
index 1d84819..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/HaServiceConfigConstants.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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.ha.provider.impl;
-
-public interface HaServiceConfigConstants {
-
-   public static final String CONFIG_PAIRS_DELIMITER = ";";
-
-   public static final String CONFIG_PAIR_DELIMITER = "=";
-
-   public static final String CONFIG_PARAM_MAX_FAILOVER_ATTEMPTS = "maxFailoverAttempts";
-
-   public static final String CONFIG_PARAM_FAILOVER_SLEEP = "failoverSleep";
-
-   public static final String CONFIG_PARAM_MAX_RETRY_ATTEMPTS = "maxRetryAttempts";
-
-   public static final String CONFIG_PARAM_RETRY_SLEEP = "retrySleep";
-
-   public static final String CONFIG_PARAM_ENABLED = "enabled";
-
-   public static final String CONFIG_PARAM_ZOOKEEPER_ENSEMBLE = "zookeeperEnsemble";
-
-   public static final String CONFIG_PARAM_ZOOKEEPER_NAMESPACE = "zookeeperNamespace";
-
-   public static final int DEFAULT_MAX_FAILOVER_ATTEMPTS = 3;
-
-   public static final int DEFAULT_FAILOVER_SLEEP = 1000;
-
-   public static final int DEFAULT_MAX_RETRY_ATTEMPTS = 3;
-
-   public static final int DEFAULT_RETRY_SLEEP = 1000;
-
-   public static final boolean DEFAULT_ENABLED = true;
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/i18n/HaMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/i18n/HaMessages.java b/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/i18n/HaMessages.java
deleted file mode 100644
index 1bad024..0000000
--- a/gateway-provider-ha/src/main/java/org/apache/hadoop/gateway/ha/provider/impl/i18n/HaMessages.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.hadoop.gateway.ha.provider.impl.i18n;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-
-@Messages(logger = "org.apache.hadoop.gateway")
-public interface HaMessages {
-
-   @Message(level = MessageLevel.ERROR, text = "Failed to Write HA Descriptor: {0}")
-   void failedToWriteHaDescriptor(Exception e);
-
-   @Message(level = MessageLevel.ERROR, text = "Failed to load HA Descriptor: {0}")
-   void failedToLoadHaDescriptor(Exception e);
-
-   @Message(level = MessageLevel.INFO, text = "No Active URL was found for service: {0}")
-   void noActiveUrlFound(String serviceName);
-
-   @Message(level = MessageLevel.INFO, text = "No Service by this name was found: {0}")
-   void noServiceFound(String serviceName);
-
-   @Message(level = MessageLevel.DEBUG, text = "Moving failed URL to the bottom {0}, new top is {1}")
-   void markedFailedUrl(String failedUrl, String top);
-
-  @Message(level = MessageLevel.ERROR, text = "Failed to get Zookeeper URLs : {0}")
-  void failedToGetZookeeperUrls(Exception e);
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/deploy/HaProviderDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/deploy/HaProviderDeploymentContributor.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/deploy/HaProviderDeploymentContributor.java
new file mode 100644
index 0000000..2f3664f
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/deploy/HaProviderDeploymentContributor.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.knox.gateway.ha.deploy;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.ha.provider.HaDescriptor;
+import org.apache.knox.gateway.ha.provider.HaServiceConfig;
+import org.apache.knox.gateway.ha.provider.HaServletContextListener;
+import org.apache.knox.gateway.ha.provider.impl.HaDescriptorFactory;
+import org.apache.knox.gateway.ha.provider.impl.HaDescriptorManager;
+import org.apache.knox.gateway.ha.provider.impl.i18n.HaMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+import org.jboss.shrinkwrap.api.asset.StringAsset;
+
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class HaProviderDeploymentContributor extends ProviderDeploymentContributorBase {
+
+   private static final String PROVIDER_ROLE_NAME = "ha";
+
+   private static final String PROVIDER_IMPL_NAME = "HaProvider";
+
+   private static final String HA_DESCRIPTOR_NAME = "ha.provider.descriptor";
+
+   private static final HaMessages LOG = MessagesFactory.get(HaMessages.class);
+
+   @Override
+   public String getRole() {
+      return PROVIDER_ROLE_NAME;
+   }
+
+   @Override
+   public String getName() {
+      return PROVIDER_IMPL_NAME;
+   }
+
+   @Override
+   public void contributeProvider(DeploymentContext context, Provider provider) {
+      Map<String, String> params = provider.getParams();
+      HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
+      for (Entry<String, String> entry : params.entrySet()) {
+         HaServiceConfig config = HaDescriptorFactory.createServiceConfig(entry.getKey(), entry.getValue());
+         descriptor.addServiceConfig(config);
+      }
+      StringWriter writer = new StringWriter();
+      try {
+         HaDescriptorManager.store(descriptor, writer);
+      } catch (IOException e) {
+         LOG.failedToWriteHaDescriptor(e);
+      }
+      String asset = writer.toString();
+      context.getWebArchive().addAsWebInfResource(
+            new StringAsset(asset),
+            HaServletContextListener.DESCRIPTOR_DEFAULT_FILE_NAME);
+      context.addDescriptor(HA_DESCRIPTOR_NAME, descriptor);
+   }
+
+   @Override
+   public void finalizeContribution(DeploymentContext context) {
+      if (context.getDescriptor(HA_DESCRIPTOR_NAME) != null) {
+         // Tell the provider the location of the descriptor.
+         // Doing this here instead of in 'contributeProvider' so that this ServletContextListener comes after the gateway services have been set.
+         context.getWebAppDescriptor().createListener().listenerClass(HaServletContextListener.class.getName());
+         context.getWebAppDescriptor().createContextParam()
+               .paramName(HaServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME)
+               .paramValue(HaServletContextListener.DESCRIPTOR_DEFAULT_LOCATION);
+      }
+   }
+
+   @Override
+   public void contributeFilter(DeploymentContext context, Provider provider, Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params) {
+      //no op
+   }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/dispatch/DefaultHaDispatch.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/dispatch/DefaultHaDispatch.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/dispatch/DefaultHaDispatch.java
new file mode 100644
index 0000000..0afb539
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/dispatch/DefaultHaDispatch.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.knox.gateway.ha.dispatch;
+
+import org.apache.knox.gateway.config.Configure;
+import org.apache.knox.gateway.config.Optional;
+import org.apache.knox.gateway.dispatch.DefaultDispatch;
+import org.apache.knox.gateway.filter.AbstractGatewayFilter;
+import org.apache.knox.gateway.ha.dispatch.i18n.HaDispatchMessages;
+import org.apache.knox.gateway.ha.provider.HaProvider;
+import org.apache.knox.gateway.ha.provider.HaServiceConfig;
+import org.apache.knox.gateway.ha.provider.impl.HaServiceConfigConstants;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpRequestBase;
+import org.apache.http.client.methods.HttpUriRequest;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.net.URI;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Default HA dispatch class that has a very basic failover mechanism
+ */
+public class DefaultHaDispatch extends DefaultDispatch {
+
+  protected static final String FAILOVER_COUNTER_ATTRIBUTE = "dispatch.ha.failover.counter";
+
+  private static final HaDispatchMessages LOG = MessagesFactory.get(HaDispatchMessages.class);
+
+  private int maxFailoverAttempts = HaServiceConfigConstants.DEFAULT_MAX_FAILOVER_ATTEMPTS;
+
+  private int failoverSleep = HaServiceConfigConstants.DEFAULT_FAILOVER_SLEEP;
+
+  private HaProvider haProvider;
+
+  @Optional
+  @Configure
+  private String serviceRole;
+
+  @Override
+  public void init() {
+    super.init();
+    LOG.initializingForResourceRole(getServiceRole());
+    if ( haProvider != null ) {
+      HaServiceConfig serviceConfig = haProvider.getHaDescriptor().getServiceConfig(getServiceRole());
+      maxFailoverAttempts = serviceConfig.getMaxFailoverAttempts();
+      failoverSleep = serviceConfig.getFailoverSleep();
+    }
+  }
+
+  public String getServiceRole() {
+    return serviceRole;
+  }
+
+  public void setServiceRole(String serviceRole) {
+    this.serviceRole = serviceRole;
+  }
+
+  public HaProvider getHaProvider() {
+    return haProvider;
+  }
+
+  @Configure
+  public void setHaProvider(HaProvider haProvider) {
+    this.haProvider = haProvider;
+  }
+
+  @Override
+  protected void executeRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse) throws IOException {
+    HttpResponse inboundResponse = null;
+    try {
+      inboundResponse = executeOutboundRequest(outboundRequest);
+      writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
+    } catch ( IOException e ) {
+      LOG.errorConnectingToServer(outboundRequest.getURI().toString(), e);
+      failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, e);
+    }
+  }
+
+
+  private void failoverRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse, HttpResponse inboundResponse, Exception exception) throws IOException {
+    LOG.failingOverRequest(outboundRequest.getURI().toString());
+    AtomicInteger counter = (AtomicInteger) inboundRequest.getAttribute(FAILOVER_COUNTER_ATTRIBUTE);
+    if ( counter == null ) {
+      counter = new AtomicInteger(0);
+    }
+    inboundRequest.setAttribute(FAILOVER_COUNTER_ATTRIBUTE, counter);
+    if ( counter.incrementAndGet() <= maxFailoverAttempts ) {
+      haProvider.markFailedURL(getServiceRole(), outboundRequest.getURI().toString());
+      //null out target url so that rewriters run again
+      inboundRequest.setAttribute(AbstractGatewayFilter.TARGET_REQUEST_URL_ATTRIBUTE_NAME, null);
+      URI uri = getDispatchUrl(inboundRequest);
+      ((HttpRequestBase) outboundRequest).setURI(uri);
+      if ( failoverSleep > 0 ) {
+        try {
+          Thread.sleep(failoverSleep);
+        } catch ( InterruptedException e ) {
+          LOG.failoverSleepFailed(getServiceRole(), e);
+        }
+      }
+      executeRequest(outboundRequest, inboundRequest, outboundResponse);
+    } else {
+      LOG.maxFailoverAttemptsReached(maxFailoverAttempts, getServiceRole());
+      if ( inboundResponse != null ) {
+        writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
+      } else {
+        throw new IOException(exception);
+      }
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/dispatch/i18n/HaDispatchMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/dispatch/i18n/HaDispatchMessages.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/dispatch/i18n/HaDispatchMessages.java
new file mode 100644
index 0000000..8efc773
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/dispatch/i18n/HaDispatchMessages.java
@@ -0,0 +1,41 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.dispatch.i18n;
+
+import org.apache.knox.gateway.i18n.messages.Message;
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.Messages;
+import org.apache.knox.gateway.i18n.messages.StackTrace;
+
+@Messages(logger = "org.apache.hadoop.gateway")
+public interface HaDispatchMessages {
+  @Message(level = MessageLevel.INFO, text = "Initializing Ha Dispatch for: {0}")
+  void initializingForResourceRole(String resourceRole);
+
+  @Message(level = MessageLevel.INFO, text = "Could not connect to server: {0} {1}")
+  void errorConnectingToServer(String uri, @StackTrace(level = MessageLevel.DEBUG) Exception e);
+
+  @Message(level = MessageLevel.INFO, text = "Failing over request to a different server: {0}")
+  void failingOverRequest(String uri);
+
+  @Message(level = MessageLevel.INFO, text = "Maximum attempts {0} to failover reached for service: {1}")
+  void maxFailoverAttemptsReached(int attempts, String service);
+
+  @Message(level = MessageLevel.INFO, text = "Error occurred while trying to sleep for failover : {0} {1}")
+  void failoverSleepFailed(String service, @StackTrace(level = MessageLevel.DEBUG) Exception e);
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaDescriptor.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaDescriptor.java
new file mode 100644
index 0000000..a7e5ea2
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaDescriptor.java
@@ -0,0 +1,34 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider;
+
+import java.util.List;
+
+public interface HaDescriptor {
+
+   public void addServiceConfig(HaServiceConfig serviceConfig);
+
+   public HaServiceConfig getServiceConfig(String serviceName);
+
+   public List<String> getServiceNames();
+
+   public List<String> getEnabledServiceNames();
+
+   public List<HaServiceConfig> getServiceConfigs();
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaProvider.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaProvider.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaProvider.java
new file mode 100644
index 0000000..c11be70
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaProvider.java
@@ -0,0 +1,67 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider;
+
+import java.util.List;
+
+public interface HaProvider {
+
+   public HaDescriptor getHaDescriptor();
+
+   /**
+    * Add a service name (role) as a HA service with the URLs that it is configured for
+    *
+    * @param serviceName the name of the service
+    * @param urls        the list of urls that can be used for that service
+    */
+   public void addHaService(String serviceName, List<String> urls);
+
+   /**
+    * Returns whether the service is enabled for HA
+    *
+    * @param serviceName the name of the service
+    * @return true if the service is enabled; false otherwise
+    */
+   public boolean isHaEnabled(String serviceName);
+
+   /**
+    * Returns the current URL that is known to be active for the service
+    *
+    * @param serviceName the name of the service
+    * @return the URL as a string or null if the service name is not found
+    */
+   public String getActiveURL(String serviceName);
+
+   /**
+    * Sets a given URL that is known to be active for the service
+    *
+    * @param serviceName the name of the service
+    * @param url the active url
+    */
+   public void setActiveURL(String serviceName, String url);
+
+   /**
+    * Mark the URL for the service as one that has failed. This method puts changes the active URL to
+    * the next available URL for the service.
+    *
+    * @param serviceName the name of the service
+    * @param url         the URL that has failed in some way
+    */
+   public void markFailedURL(String serviceName, String url);
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaServiceConfig.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaServiceConfig.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaServiceConfig.java
new file mode 100644
index 0000000..690137c
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaServiceConfig.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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider;
+
+public interface HaServiceConfig {
+
+   public void setServiceName(String name);
+
+   public String getServiceName();
+
+   public boolean isEnabled();
+
+   public void setEnabled(boolean enabled);
+
+   public void setMaxFailoverAttempts(int limit);
+
+   public int getMaxFailoverAttempts();
+
+   public void setFailoverSleep(int sleep);
+
+   public int getFailoverSleep();
+
+   public void setMaxRetryAttempts(int limit);
+
+   public int getMaxRetryAttempts();
+
+   public void setRetrySleep(int sleep);
+
+   public int getRetrySleep();
+
+   public String getZookeeperEnsemble();
+
+   public void setZookeeperEnsemble(String zookeeperEnsemble);
+
+   public String getZookeeperNamespace();
+
+   public void setZookeeperNamespace(String zookeeperNamespace);
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaServletContextListener.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaServletContextListener.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaServletContextListener.java
new file mode 100644
index 0000000..20a39ac
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/HaServletContextListener.java
@@ -0,0 +1,116 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider;
+
+import org.apache.knox.gateway.ha.provider.impl.DefaultHaProvider;
+import org.apache.knox.gateway.ha.provider.impl.HaDescriptorManager;
+import org.apache.knox.gateway.ha.provider.impl.i18n.HaMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+
+import javax.servlet.ServletContext;
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.List;
+
+public class HaServletContextListener implements ServletContextListener {
+
+   public static final String PROVIDER_ATTRIBUTE_NAME = "haProvider";
+
+   public static final String DESCRIPTOR_LOCATION_INIT_PARAM_NAME = "haDescriptorLocation";
+
+   public static final String DESCRIPTOR_DEFAULT_FILE_NAME = "ha.xml";
+
+   public static final String DESCRIPTOR_DEFAULT_LOCATION = "/WEB-INF/" + DESCRIPTOR_DEFAULT_FILE_NAME;
+
+   private static final HaMessages LOG = MessagesFactory.get(HaMessages.class);
+
+
+   @Override
+   public void contextInitialized(ServletContextEvent event) {
+      HaDescriptor descriptor;
+      ServletContext servletContext = event.getServletContext();
+      try {
+         URL url = locateDescriptor(servletContext);
+         descriptor = loadDescriptor(url);
+      } catch (IOException e) {
+         throw new IllegalStateException(e);
+      }
+      setupHaProvider(descriptor, servletContext);
+   }
+
+   @Override
+   public void contextDestroyed(ServletContextEvent event) {
+      event.getServletContext().removeAttribute(PROVIDER_ATTRIBUTE_NAME);
+   }
+
+   public static HaProvider getHaProvider(ServletContext context) {
+      return (HaProvider) context.getAttribute(PROVIDER_ATTRIBUTE_NAME);
+   }
+
+   private void setupHaProvider(HaDescriptor descriptor, ServletContext servletContext) {
+      GatewayServices services = (GatewayServices) servletContext.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
+      String clusterName = (String) servletContext.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE);
+      ServiceRegistry serviceRegistry = services.getService(GatewayServices.SERVICE_REGISTRY_SERVICE);
+      HaProvider provider = new DefaultHaProvider(descriptor);
+      List<String> serviceNames = descriptor.getEnabledServiceNames();
+      for (String serviceName : serviceNames) {
+         provider.addHaService(serviceName, serviceRegistry.lookupServiceURLs(clusterName, serviceName));
+      }
+      servletContext.setAttribute(PROVIDER_ATTRIBUTE_NAME, provider);
+   }
+
+   private static URL locateDescriptor(ServletContext context) throws IOException {
+      String param = context.getInitParameter(DESCRIPTOR_LOCATION_INIT_PARAM_NAME);
+      if (param == null) {
+         param = DESCRIPTOR_DEFAULT_LOCATION;
+      }
+      URL url;
+      try {
+         url = context.getResource(param);
+      } catch (MalformedURLException e) {
+         // Ignore it and try using the value directly as a URL.
+         url = null;
+      }
+      if (url == null) {
+         url = new URL(param);
+      }
+      if (url == null) {
+         throw new FileNotFoundException(param);
+      }
+      return url;
+   }
+
+   private static HaDescriptor loadDescriptor(URL url) throws IOException {
+      InputStream stream = url.openStream();
+      HaDescriptor descriptor = HaDescriptorManager.load(stream);
+      try {
+         stream.close();
+      } catch (IOException e) {
+         LOG.failedToLoadHaDescriptor(e);
+      }
+      return descriptor;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/URLManager.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/URLManager.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/URLManager.java
new file mode 100644
index 0000000..c5ee870
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/URLManager.java
@@ -0,0 +1,37 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider;
+
+import java.util.List;
+
+public interface URLManager {
+
+  public boolean supportsConfig(HaServiceConfig config);
+
+  public void setConfig(HaServiceConfig config);
+
+  public String getActiveURL();
+
+  public void setActiveURL(String url);
+
+  public List<String> getURLs();
+
+  public void setURLs(List<String> urls);
+
+  public void markFailed(String url);
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/URLManagerLoader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/URLManagerLoader.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/URLManagerLoader.java
new file mode 100644
index 0000000..df7ba21
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/URLManagerLoader.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.knox.gateway.ha.provider;
+
+import org.apache.knox.gateway.ha.provider.impl.DefaultURLManager;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+public class URLManagerLoader {
+
+  public static URLManager loadURLManager(HaServiceConfig config) {
+    if (config != null) {
+      ServiceLoader<URLManager> loader = ServiceLoader.load(URLManager.class);
+      if ( loader != null ) {
+        Iterator<URLManager> iterator = loader.iterator();
+        while ( iterator.hasNext() ) {
+          URLManager urlManager = iterator.next();
+          if ( urlManager.supportsConfig(config) ) {
+            urlManager.setConfig(config);
+            return urlManager;
+          }
+        }
+      }
+    }
+    return new DefaultURLManager();
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaDescriptor.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaDescriptor.java
new file mode 100644
index 0000000..b201bbe
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaDescriptor.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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider.impl;
+
+import com.google.common.collect.Lists;
+import org.apache.knox.gateway.ha.provider.HaDescriptor;
+import org.apache.knox.gateway.ha.provider.HaServiceConfig;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+
+public class DefaultHaDescriptor implements HaDescriptor {
+
+   private ConcurrentHashMap<String, HaServiceConfig> serviceConfigs;
+
+   public DefaultHaDescriptor() {
+      serviceConfigs = new ConcurrentHashMap<>();
+   }
+
+   @Override
+   public void addServiceConfig(HaServiceConfig serviceConfig) {
+      if (serviceConfig == null) {
+         throw new IllegalArgumentException("Service config must not be null");
+      }
+      serviceConfigs.put(serviceConfig.getServiceName(), serviceConfig);
+   }
+
+   @Override
+   public HaServiceConfig getServiceConfig(String serviceName) {
+      return serviceConfigs.get(serviceName);
+   }
+
+   @Override
+   public List<HaServiceConfig> getServiceConfigs() {
+      return Lists.newArrayList(serviceConfigs.values());
+   }
+
+   @Override
+   public List<String> getServiceNames() {
+      return Lists.newArrayList(serviceConfigs.keySet());
+   }
+
+   @Override
+   public List<String> getEnabledServiceNames() {
+      ArrayList<String> services = new ArrayList<String>(serviceConfigs.size());
+      Collection<HaServiceConfig> configs = serviceConfigs.values();
+      for (HaServiceConfig config : configs) {
+         if (config.isEnabled()) {
+            services.add(config.getServiceName());
+         }
+      }
+      return services;
+   }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaProvider.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaProvider.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaProvider.java
new file mode 100644
index 0000000..0039a26
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaProvider.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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider.impl;
+
+import org.apache.knox.gateway.ha.provider.HaDescriptor;
+import org.apache.knox.gateway.ha.provider.HaProvider;
+import org.apache.knox.gateway.ha.provider.HaServiceConfig;
+import org.apache.knox.gateway.ha.provider.URLManager;
+import org.apache.knox.gateway.ha.provider.URLManagerLoader;
+import org.apache.knox.gateway.ha.provider.impl.i18n.HaMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+
+import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+
+public class DefaultHaProvider implements HaProvider {
+
+  private static final HaMessages LOG = MessagesFactory.get(HaMessages.class);
+
+  private HaDescriptor descriptor;
+
+  private ConcurrentHashMap<String, URLManager> haServices;
+
+  public DefaultHaProvider(HaDescriptor descriptor) {
+    if ( descriptor == null ) {
+      throw new IllegalArgumentException("Descriptor can not be null");
+    }
+    this.descriptor = descriptor;
+    haServices = new ConcurrentHashMap<>();
+  }
+
+  @Override
+  public HaDescriptor getHaDescriptor() {
+    return descriptor;
+  }
+
+  @Override
+  public void addHaService(String serviceName, List<String> urls) {
+    HaServiceConfig haServiceConfig = descriptor.getServiceConfig(serviceName);
+    URLManager manager = URLManagerLoader.loadURLManager(haServiceConfig);
+    manager.setURLs(urls);
+    haServices.put(serviceName, manager);
+  }
+
+  @Override
+  public boolean isHaEnabled(String serviceName) {
+    HaServiceConfig config = descriptor.getServiceConfig(serviceName);
+    if ( config != null && config.isEnabled() ) {
+      return true;
+    }
+    return false;
+  }
+
+  @Override
+  public String getActiveURL(String serviceName) {
+    if ( haServices.containsKey(serviceName) ) {
+      return haServices.get(serviceName).getActiveURL();
+    }
+    LOG.noActiveUrlFound(serviceName);
+    return null;
+  }
+
+  @Override
+  public void setActiveURL(String serviceName, String url) {
+    if ( haServices.containsKey(serviceName) ) {
+      haServices.get(serviceName).setActiveURL(url);
+    } else {
+      LOG.noServiceFound(serviceName);
+    }
+
+  }
+
+  @Override
+  public void markFailedURL(String serviceName, String url) {
+    if ( haServices.containsKey(serviceName) ) {
+      haServices.get(serviceName).markFailed(url);
+    } else {
+      LOG.noServiceFound(serviceName);
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaServiceConfig.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaServiceConfig.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaServiceConfig.java
new file mode 100644
index 0000000..99a0583
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaServiceConfig.java
@@ -0,0 +1,124 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider.impl;
+
+import org.apache.knox.gateway.ha.provider.HaServiceConfig;
+
+public class DefaultHaServiceConfig implements HaServiceConfig, HaServiceConfigConstants {
+
+  private String name;
+
+  private boolean enabled = DEFAULT_ENABLED;
+
+  private int maxFailoverAttempts = DEFAULT_MAX_FAILOVER_ATTEMPTS;
+
+  private int failoverSleep = DEFAULT_FAILOVER_SLEEP;
+
+  private int maxRetryAttempts = DEFAULT_MAX_RETRY_ATTEMPTS;
+
+  private int retrySleep = DEFAULT_RETRY_SLEEP;
+
+  private String zookeeperEnsemble;
+
+  private String zookeeperNamespace;
+
+  public DefaultHaServiceConfig(String name) {
+    this.name = name;
+  }
+
+  @Override
+
+  public String getServiceName() {
+    return name;
+  }
+
+  @Override
+  public void setServiceName(String name) {
+    this.name = name;
+  }
+
+  @Override
+  public boolean isEnabled() {
+    return enabled;
+  }
+
+  @Override
+  public void setEnabled(boolean enabled) {
+    this.enabled = enabled;
+  }
+
+  @Override
+  public int getMaxFailoverAttempts() {
+    return maxFailoverAttempts;
+  }
+
+  @Override
+  public void setMaxFailoverAttempts(int maxFailoverAttempts) {
+    this.maxFailoverAttempts = maxFailoverAttempts;
+  }
+
+  @Override
+  public int getFailoverSleep() {
+    return failoverSleep;
+  }
+
+  @Override
+  public void setFailoverSleep(int failoverSleep) {
+    this.failoverSleep = failoverSleep;
+  }
+
+  @Override
+  public int getMaxRetryAttempts() {
+    return maxRetryAttempts;
+  }
+
+  @Override
+  public void setMaxRetryAttempts(int maxRetryAttempts) {
+    this.maxRetryAttempts = maxRetryAttempts;
+  }
+
+  @Override
+  public int getRetrySleep() {
+    return retrySleep;
+  }
+
+  @Override
+  public void setRetrySleep(int retrySleep) {
+    this.retrySleep = retrySleep;
+  }
+
+  @Override
+  public String getZookeeperEnsemble() {
+    return zookeeperEnsemble;
+  }
+
+  @Override
+  public void setZookeeperEnsemble(String zookeeperEnsemble) {
+    this.zookeeperEnsemble = zookeeperEnsemble;
+  }
+
+  @Override
+  public String getZookeeperNamespace() {
+    return zookeeperNamespace;
+  }
+
+  @Override
+  public void setZookeeperNamespace(String zookeeperNamespace) {
+    this.zookeeperNamespace = zookeeperNamespace;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultURLManager.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultURLManager.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultURLManager.java
new file mode 100644
index 0000000..a309c19
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/DefaultURLManager.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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider.impl;
+
+import com.google.common.collect.Lists;
+import org.apache.knox.gateway.ha.provider.HaServiceConfig;
+import org.apache.knox.gateway.ha.provider.URLManager;
+import org.apache.knox.gateway.ha.provider.impl.i18n.HaMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+
+import java.net.URI;
+import java.util.List;
+import java.util.concurrent.ConcurrentLinkedQueue;
+
+public class DefaultURLManager implements URLManager {
+
+  private static final HaMessages LOG = MessagesFactory.get(HaMessages.class);
+
+  private ConcurrentLinkedQueue<String> urls = new ConcurrentLinkedQueue<>();
+
+  public DefaultURLManager() {
+  }
+
+  @Override
+  public boolean supportsConfig(HaServiceConfig config) {
+    return true;
+  }
+
+  @Override
+  public void setConfig(HaServiceConfig config) {
+    //no-op
+  }
+
+  @Override
+  public String getActiveURL() {
+    return urls.peek();
+  }
+
+  @Override
+  public synchronized void setActiveURL(String url) {
+    String top = urls.peek();
+    if (top.equalsIgnoreCase(url)) {
+      return;
+    }
+    if (urls.contains(url)) {
+      urls.remove(url);
+      List<String> remainingList = getURLs();
+      urls.clear();
+      urls.add(url);
+      urls.addAll(remainingList);
+    }
+  }
+
+  @Override
+  public List<String> getURLs() {
+    return Lists.newArrayList(urls.iterator());
+  }
+
+  @Override
+  public synchronized void setURLs(List<String> urls) {
+    if ( urls != null && !urls.isEmpty()) {
+      this.urls.clear();
+      this.urls.addAll(urls);
+    }
+  }
+
+  @Override
+  public synchronized void markFailed(String url) {
+    String top = urls.peek();
+    boolean pushToBottom = false;
+    URI topUri = URI.create(top);
+    URI incomingUri = URI.create(url);
+    String topHostPort = topUri.getHost() + ":" + topUri.getPort();
+    String incomingHostPort = incomingUri.getHost() + ":" + incomingUri.getPort();
+    if ( topHostPort.equals(incomingHostPort) ) {
+      pushToBottom = true;
+    }
+    //put the failed url at the bottom
+    if ( pushToBottom ) {
+      String failed = urls.poll();
+      urls.offer(failed);
+      LOG.markedFailedUrl(failed, urls.peek());
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HS2ZookeeperURLManager.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HS2ZookeeperURLManager.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HS2ZookeeperURLManager.java
new file mode 100644
index 0000000..f3322ec
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HS2ZookeeperURLManager.java
@@ -0,0 +1,145 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider.impl;
+
+import org.apache.curator.framework.CuratorFramework;
+import org.apache.curator.framework.CuratorFrameworkFactory;
+import org.apache.curator.retry.ExponentialBackoffRetry;
+import org.apache.knox.gateway.ha.provider.HaServiceConfig;
+import org.apache.knox.gateway.ha.provider.impl.i18n.HaMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class HS2ZookeeperURLManager extends DefaultURLManager {
+
+  private static final HaMessages LOG = MessagesFactory.get(HaMessages.class);
+
+  private static final Pattern kvPattern = Pattern.compile("([^=;]*)=([^;]*)[;]?");
+
+  private String zooKeeperEnsemble;
+
+  private String zooKeeperNamespace;
+
+  private HashSet<String> failedSet;
+
+  public HS2ZookeeperURLManager() {
+    failedSet = new LinkedHashSet<>();
+  }
+
+  @Override
+  public boolean supportsConfig(HaServiceConfig config) {
+    if (!config.getServiceName().equalsIgnoreCase("HIVE")) {
+      return false;
+    }
+    String zookeeperEnsemble = config.getZookeeperEnsemble();
+    String zookeeperNamespace = config.getZookeeperNamespace();
+    if ( zookeeperEnsemble != null && zookeeperNamespace != null && zookeeperEnsemble.trim().length() > 0 && zookeeperNamespace.trim().length() > 0) {
+      return true;
+    }
+    return false;
+  }
+
+  @Override
+  public void setConfig(HaServiceConfig config) {
+    zooKeeperEnsemble = config.getZookeeperEnsemble();
+    zooKeeperNamespace = config.getZookeeperNamespace();
+    setURLs(lookupURLs());
+  }
+
+  public List<String> lookupURLs() {
+    List<String> serverHosts = new ArrayList<>();
+    CuratorFramework zooKeeperClient =
+        CuratorFrameworkFactory.builder().connectString(zooKeeperEnsemble)
+            .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
+    try {
+      zooKeeperClient.start();
+      List<String> serverNodes = zooKeeperClient.getChildren().forPath("/" + zooKeeperNamespace);
+      for ( String serverNode : serverNodes ) {
+        String serverInfo =
+            new String(
+                zooKeeperClient.getData().forPath("/" + zooKeeperNamespace + "/" + serverNode),
+                Charset.forName("UTF-8"));
+        String serverURL = constructURL(serverInfo);
+        serverHosts.add(serverURL);
+      }
+    } catch ( Exception e ) {
+      LOG.failedToGetZookeeperUrls(e);
+      throw new RuntimeException(e);
+    } finally {
+      // Close the client connection with ZooKeeper
+      if ( zooKeeperClient != null ) {
+        zooKeeperClient.close();
+      }
+    }
+    return serverHosts;
+  }
+
+  private String constructURL(String serverInfo) {
+    Matcher matcher = kvPattern.matcher(serverInfo);
+    String scheme = "http";
+    String host = null;
+    String port = "10001";
+    String httpPath = "cliservice";
+    while (matcher.find()) {
+      if ( (matcher.group(1) != null) && matcher.group(2) != null ) {
+        switch ( matcher.group(1) ) {
+          case "hive.server2.thrift.bind.host" :
+            host = matcher.group(2);
+            break;
+          case "hive.server2.thrift.http.port" :
+            port = matcher.group(2);
+            break;
+          case "hive.server2.thrift.http.path" :
+            httpPath = matcher.group(2);
+            break;
+          case "hive.server2.use.SSL" :
+            if (Boolean.parseBoolean(matcher.group(2))) {
+              scheme = "https";
+            }
+        }
+      }
+    }
+    StringBuffer buffer = new StringBuffer();
+    buffer.append(scheme);
+    buffer.append("://");
+    buffer.append(host);
+    buffer.append(":");
+    buffer.append(port);
+    buffer.append("/");
+    buffer.append(httpPath);
+    return buffer.toString();
+  }
+
+  @Override
+  public synchronized void markFailed(String url) {
+    failedSet.add(url);
+    //refresh the list when we have hit all urls once
+    if (failedSet.size() >= getURLs().size()) {
+      failedSet.clear();
+      setURLs(lookupURLs());
+    }
+    super.markFailed(url);
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorConstants.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorConstants.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorConstants.java
new file mode 100644
index 0000000..5ea6b4a
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorConstants.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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider.impl;
+
+/**
+ * The constants for xml elements and attributes are meant to help render/consume the following:
+ * <p/>
+ * <ha>
+ * <service name='foo' failoverLimit='3' enabled='true'/>
+ * </ha>
+ */
+public interface HaDescriptorConstants {
+
+   public static final String ROOT_ELEMENT = "ha";
+
+   public static final String SERVICE_ELEMENT = "service";
+
+   public static final String SERVICE_NAME_ATTRIBUTE = "name";
+
+   public static final String MAX_FAILOVER_ATTEMPTS = "maxFailoverAttempts";
+
+   public static final String FAILOVER_SLEEP = "failoverSleep";
+
+   public static final String MAX_RETRY_ATTEMPTS = "maxRetryAttempts";
+
+   public static final String RETRY_SLEEP = "retrySleep";
+
+   public static final String ENABLED_ATTRIBUTE = "enabled";
+
+   public static final String ZOOKEEPER_ENSEMBLE = "zookeeperEnsemble";
+
+   public static final String ZOOKEEPER_NAMESPACE = "zookeeperNamespace";
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorFactory.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorFactory.java
new file mode 100644
index 0000000..741d7c5
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorFactory.java
@@ -0,0 +1,94 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider.impl;
+
+import org.apache.knox.gateway.ha.provider.HaDescriptor;
+import org.apache.knox.gateway.ha.provider.HaServiceConfig;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public abstract class HaDescriptorFactory implements HaServiceConfigConstants {
+
+   public static HaDescriptor createDescriptor() {
+      return new DefaultHaDescriptor();
+   }
+
+   public static HaServiceConfig createServiceConfig(String serviceName, String config) {
+      Map<String, String> configMap = parseHaConfiguration(config);
+      String enabledValue = configMap.get(CONFIG_PARAM_ENABLED);
+      String maxFailoverAttempts = configMap.get(CONFIG_PARAM_MAX_FAILOVER_ATTEMPTS);
+      String failoverSleep = configMap.get(CONFIG_PARAM_FAILOVER_SLEEP);
+      String maxRetryAttempts = configMap.get(CONFIG_PARAM_MAX_RETRY_ATTEMPTS);
+      String retrySleep = configMap.get(CONFIG_PARAM_RETRY_SLEEP);
+      String zookeeperEnsemble = configMap.get(CONFIG_PARAM_ZOOKEEPER_ENSEMBLE);
+      String zookeeperNamespace = configMap.get(CONFIG_PARAM_ZOOKEEPER_NAMESPACE);
+      return createServiceConfig(serviceName, enabledValue, maxFailoverAttempts,
+          failoverSleep, maxRetryAttempts, retrySleep,
+          zookeeperEnsemble, zookeeperNamespace);
+   }
+
+   public static HaServiceConfig createServiceConfig(String serviceName, String enabledValue,
+                                                     String maxFailoverAttemptsValue, String failoverSleepValue,
+                                                     String maxRetryAttemptsValue, String retrySleepValue,
+                                                     String zookeeperEnsemble, String zookeeperNamespace) {
+      boolean enabled = DEFAULT_ENABLED;
+      int maxFailoverAttempts = DEFAULT_MAX_FAILOVER_ATTEMPTS;
+      int failoverSleep = DEFAULT_FAILOVER_SLEEP;
+      int maxRetryAttempts = DEFAULT_MAX_RETRY_ATTEMPTS;
+      int retrySleep = DEFAULT_RETRY_SLEEP;
+      if (enabledValue != null && enabledValue.trim().length() > 0) {
+         enabled = Boolean.parseBoolean(enabledValue);
+      }
+      if (maxFailoverAttemptsValue != null && maxFailoverAttemptsValue.trim().length() > 0) {
+         maxFailoverAttempts = Integer.parseInt(maxFailoverAttemptsValue);
+      }
+      if (failoverSleepValue != null && failoverSleepValue.trim().length() > 0) {
+         failoverSleep = Integer.parseInt(failoverSleepValue);
+      }
+      if (maxRetryAttemptsValue != null && maxRetryAttemptsValue.trim().length() > 0) {
+         maxRetryAttempts = Integer.parseInt(maxRetryAttemptsValue);
+      }
+      if (retrySleepValue != null && retrySleepValue.trim().length() > 0) {
+         retrySleep = Integer.parseInt(retrySleepValue);
+      }
+      DefaultHaServiceConfig serviceConfig = new DefaultHaServiceConfig(serviceName);
+      serviceConfig.setEnabled(enabled);
+      serviceConfig.setMaxFailoverAttempts(maxFailoverAttempts);
+      serviceConfig.setFailoverSleep(failoverSleep);
+      serviceConfig.setMaxRetryAttempts(maxRetryAttempts);
+      serviceConfig.setRetrySleep(retrySleep);
+      serviceConfig.setZookeeperEnsemble(zookeeperEnsemble);
+      serviceConfig.setZookeeperNamespace(zookeeperNamespace);
+      return serviceConfig;
+   }
+
+   private static Map<String, String> parseHaConfiguration(String configuration) {
+      Map<String, String> parameters = new HashMap<>();
+      if (configuration != null) {
+         String[] pairs = configuration.split(CONFIG_PAIRS_DELIMITER);
+         for (String pair : pairs) {
+            String[] tokens = pair.split(CONFIG_PAIR_DELIMITER);
+            if (tokens.length == 2) {
+               parameters.put(tokens[0], tokens[1]);
+            }
+         }
+      }
+      return parameters;
+   }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorManager.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorManager.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorManager.java
new file mode 100644
index 0000000..5e5402d
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorManager.java
@@ -0,0 +1,109 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider.impl;
+
+import org.apache.knox.gateway.ha.provider.HaDescriptor;
+import org.apache.knox.gateway.ha.provider.HaServiceConfig;
+import org.apache.knox.gateway.ha.provider.impl.i18n.HaMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.util.XmlUtils;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Writer;
+import java.util.List;
+
+public class HaDescriptorManager implements HaDescriptorConstants {
+
+   private static final HaMessages LOG = MessagesFactory.get(HaMessages.class);
+
+   public static void store(HaDescriptor descriptor, Writer writer) throws IOException {
+      try {
+         Document document = XmlUtils.createDocument();
+
+         Element root = document.createElement(ROOT_ELEMENT);
+         document.appendChild(root);
+
+         List<HaServiceConfig> serviceConfigs = descriptor.getServiceConfigs();
+         if (serviceConfigs != null && !serviceConfigs.isEmpty()) {
+            for (HaServiceConfig config : serviceConfigs) {
+               Element serviceElement = document.createElement(SERVICE_ELEMENT);
+               serviceElement.setAttribute(SERVICE_NAME_ATTRIBUTE, config.getServiceName());
+               serviceElement.setAttribute(MAX_FAILOVER_ATTEMPTS, Integer.toString(config.getMaxFailoverAttempts()));
+               serviceElement.setAttribute(FAILOVER_SLEEP, Integer.toString(config.getFailoverSleep()));
+               serviceElement.setAttribute(MAX_RETRY_ATTEMPTS, Integer.toString(config.getMaxRetryAttempts()));
+               serviceElement.setAttribute(RETRY_SLEEP, Integer.toString(config.getRetrySleep()));
+               serviceElement.setAttribute(ENABLED_ATTRIBUTE, Boolean.toString(config.isEnabled()));
+               if (config.getZookeeperEnsemble() != null) {
+                 serviceElement.setAttribute(ZOOKEEPER_ENSEMBLE, config.getZookeeperEnsemble());
+               }
+               if (config.getZookeeperNamespace() != null) {
+                 serviceElement.setAttribute(ZOOKEEPER_NAMESPACE, config.getZookeeperNamespace());
+               }
+               root.appendChild(serviceElement);
+            }
+         }
+
+         Transformer t = XmlUtils.getTransformer( true, true, 2, false );
+         XmlUtils.writeXml( document, writer, t );
+      } catch (ParserConfigurationException e) {
+         LOG.failedToWriteHaDescriptor(e);
+         throw new IOException(e);
+      } catch (TransformerException e) {
+         LOG.failedToWriteHaDescriptor(e);
+         throw new IOException(e);
+      }
+   }
+
+   public static HaDescriptor load(InputStream inputStream) throws IOException {
+      HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
+      try {
+         Document document = XmlUtils.readXml( inputStream );
+         NodeList nodeList = document.getElementsByTagName(SERVICE_ELEMENT);
+         if (nodeList != null && nodeList.getLength() > 0) {
+            for (int i = 0; i < nodeList.getLength(); i++) {
+               Element element = (Element) nodeList.item(i);
+               HaServiceConfig config = HaDescriptorFactory.createServiceConfig(element.getAttribute(SERVICE_NAME_ATTRIBUTE),
+                     element.getAttribute(ENABLED_ATTRIBUTE),
+                     element.getAttribute(MAX_FAILOVER_ATTEMPTS),
+                     element.getAttribute(FAILOVER_SLEEP),
+                     element.getAttribute(MAX_RETRY_ATTEMPTS),
+                     element.getAttribute(RETRY_SLEEP),
+                     element.getAttribute(ZOOKEEPER_ENSEMBLE),
+                     element.getAttribute(ZOOKEEPER_NAMESPACE));
+               descriptor.addServiceConfig(config);
+            }
+         }
+      } catch (ParserConfigurationException e) {
+         LOG.failedToLoadHaDescriptor(e);
+         throw new IOException(e);
+      } catch (SAXException e) {
+         LOG.failedToLoadHaDescriptor(e);
+         throw new IOException(e);
+      }
+      return descriptor;
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaServiceConfigConstants.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaServiceConfigConstants.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaServiceConfigConstants.java
new file mode 100644
index 0000000..6cec6cc
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaServiceConfigConstants.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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider.impl;
+
+public interface HaServiceConfigConstants {
+
+   public static final String CONFIG_PAIRS_DELIMITER = ";";
+
+   public static final String CONFIG_PAIR_DELIMITER = "=";
+
+   public static final String CONFIG_PARAM_MAX_FAILOVER_ATTEMPTS = "maxFailoverAttempts";
+
+   public static final String CONFIG_PARAM_FAILOVER_SLEEP = "failoverSleep";
+
+   public static final String CONFIG_PARAM_MAX_RETRY_ATTEMPTS = "maxRetryAttempts";
+
+   public static final String CONFIG_PARAM_RETRY_SLEEP = "retrySleep";
+
+   public static final String CONFIG_PARAM_ENABLED = "enabled";
+
+   public static final String CONFIG_PARAM_ZOOKEEPER_ENSEMBLE = "zookeeperEnsemble";
+
+   public static final String CONFIG_PARAM_ZOOKEEPER_NAMESPACE = "zookeeperNamespace";
+
+   public static final int DEFAULT_MAX_FAILOVER_ATTEMPTS = 3;
+
+   public static final int DEFAULT_FAILOVER_SLEEP = 1000;
+
+   public static final int DEFAULT_MAX_RETRY_ATTEMPTS = 3;
+
+   public static final int DEFAULT_RETRY_SLEEP = 1000;
+
+   public static final boolean DEFAULT_ENABLED = true;
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/i18n/HaMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/i18n/HaMessages.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/i18n/HaMessages.java
new file mode 100644
index 0000000..3848c46
--- /dev/null
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/i18n/HaMessages.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.knox.gateway.ha.provider.impl.i18n;
+
+import org.apache.knox.gateway.i18n.messages.Message;
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.Messages;
+
+@Messages(logger = "org.apache.hadoop.gateway")
+public interface HaMessages {
+
+   @Message(level = MessageLevel.ERROR, text = "Failed to Write HA Descriptor: {0}")
+   void failedToWriteHaDescriptor(Exception e);
+
+   @Message(level = MessageLevel.ERROR, text = "Failed to load HA Descriptor: {0}")
+   void failedToLoadHaDescriptor(Exception e);
+
+   @Message(level = MessageLevel.INFO, text = "No Active URL was found for service: {0}")
+   void noActiveUrlFound(String serviceName);
+
+   @Message(level = MessageLevel.INFO, text = "No Service by this name was found: {0}")
+   void noServiceFound(String serviceName);
+
+   @Message(level = MessageLevel.DEBUG, text = "Moving failed URL to the bottom {0}, new top is {1}")
+   void markedFailedUrl(String failedUrl, String top);
+
+  @Message(level = MessageLevel.ERROR, text = "Failed to get Zookeeper URLs : {0}")
+  void failedToGetZookeeperUrls(Exception e);
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index 995a093..0000000
--- a/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.ha.deploy.HaProviderDeploymentContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.hadoop.gateway.ha.provider.URLManager
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.hadoop.gateway.ha.provider.URLManager b/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.hadoop.gateway.ha.provider.URLManager
deleted file mode 100644
index d1ec0b9..0000000
--- a/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.hadoop.gateway.ha.provider.URLManager
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.ha.provider.impl.HS2ZookeeperURLManager
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..4e1a86a
--- /dev/null
+++ b/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.ha.deploy.HaProviderDeploymentContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.knox.gateway.ha.provider.URLManager
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.knox.gateway.ha.provider.URLManager b/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.knox.gateway.ha.provider.URLManager
new file mode 100644
index 0000000..e579be8
--- /dev/null
+++ b/gateway-provider-ha/src/main/resources/META-INF/services/org.apache.knox.gateway.ha.provider.URLManager
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.ha.provider.impl.HS2ZookeeperURLManager
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/deploy/HaProviderDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/deploy/HaProviderDeploymentContributorTest.java b/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/deploy/HaProviderDeploymentContributorTest.java
deleted file mode 100644
index c39ca85..0000000
--- a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/deploy/HaProviderDeploymentContributorTest.java
+++ /dev/null
@@ -1,46 +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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.ha.deploy;
-
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-
-public class HaProviderDeploymentContributorTest {
-
-   @Test
-   public void testServiceLoader() throws Exception {
-      ServiceLoader loader = ServiceLoader.load( ProviderDeploymentContributor.class );
-      Iterator iterator = loader.iterator();
-      assertThat( "Service iterator empty.", iterator.hasNext() );
-      while( iterator.hasNext() ) {
-         Object object = iterator.next();
-         if( object instanceof HaProviderDeploymentContributor ) {
-            return;
-         }
-      }
-      fail( "Failed to find " + HaProviderDeploymentContributor.class.getName() + " via service loader." );
-   }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/dispatch/DefaultHaDispatchTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/dispatch/DefaultHaDispatchTest.java b/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/dispatch/DefaultHaDispatchTest.java
deleted file mode 100644
index 0436532..0000000
--- a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/dispatch/DefaultHaDispatchTest.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.hadoop.gateway.ha.dispatch;
-
-import org.apache.hadoop.gateway.ha.provider.HaDescriptor;
-import org.apache.hadoop.gateway.ha.provider.HaProvider;
-import org.apache.hadoop.gateway.ha.provider.HaServletContextListener;
-import org.apache.hadoop.gateway.ha.provider.impl.DefaultHaProvider;
-import org.apache.hadoop.gateway.ha.provider.impl.HaDescriptorFactory;
-import org.apache.hadoop.gateway.servlet.SynchronousServletOutputStreamAdapter;
-import org.apache.http.client.methods.HttpRequestBase;
-import org.apache.http.client.methods.HttpUriRequest;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.params.BasicHttpParams;
-import org.easymock.EasyMock;
-import org.easymock.IAnswer;
-import org.junit.Assert;
-import org.junit.Test;
-
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.concurrent.atomic.AtomicInteger;
-
-public class DefaultHaDispatchTest {
-
-  @Test
-  public void testConnectivityFailover() throws Exception {
-    String serviceName = "OOZIE";
-    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
-    descriptor.addServiceConfig(HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
-    HaProvider provider = new DefaultHaProvider(descriptor);
-    URI uri1 = new URI( "http://unreachable-host" );
-    URI uri2 = new URI( "http://reachable-host" );
-    ArrayList<String> urlList = new ArrayList<String>();
-    urlList.add(uri1.toString());
-    urlList.add(uri2.toString());
-    provider.addHaService(serviceName, urlList);
-    FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class);
-    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);
-
-    EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes();
-    EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(provider).anyTimes();
-
-    BasicHttpParams params = new BasicHttpParams();
-
-    HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class);
-    EasyMock.expect(outboundRequest.getMethod()).andReturn( "GET" ).anyTimes();
-    EasyMock.expect(outboundRequest.getURI()).andReturn( uri1  ).anyTimes();
-    EasyMock.expect(outboundRequest.getParams()).andReturn( params ).anyTimes();
-
-    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
-    EasyMock.expect(inboundRequest.getRequestURL()).andReturn( new StringBuffer(uri2.toString()) ).once();
-    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0)).once();
-    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1)).once();
-
-    HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class);
-    EasyMock.expect(outboundResponse.getOutputStream()).andAnswer( new IAnswer<SynchronousServletOutputStreamAdapter>() {
-      @Override
-      public SynchronousServletOutputStreamAdapter answer() throws Throwable {
-        return new SynchronousServletOutputStreamAdapter() {
-          @Override
-          public void write( int b ) throws IOException {
-            throw new IOException( "unreachable-host" );
-          }
-        };
-      }
-    }).once();
-    EasyMock.replay(filterConfig, servletContext, outboundRequest, inboundRequest, outboundResponse);
-    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
-    DefaultHaDispatch dispatch = new DefaultHaDispatch();
-    dispatch.setHttpClient(new DefaultHttpClient());
-    dispatch.setHaProvider(provider);
-    dispatch.setServiceRole(serviceName);
-    dispatch.init();
-    long startTime = System.currentTimeMillis();
-    try {
-      dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
-    } catch (IOException e) {
-      //this is expected after the failover limit is reached
-    }
-    long elapsedTime = System.currentTimeMillis() - startTime;
-    Assert.assertEquals(uri2.toString(), provider.getActiveURL(serviceName));
-    //test to make sure the sleep took place
-    Assert.assertTrue(elapsedTime > 1000);
-  }
-}


[06/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/filter/ShiroSubjectIdentityAdapter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/filter/ShiroSubjectIdentityAdapter.java b/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/filter/ShiroSubjectIdentityAdapter.java
deleted file mode 100644
index b625f34..0000000
--- a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/filter/ShiroSubjectIdentityAdapter.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.
- */
-package org.apache.hadoop.gateway.filter;
-
-import java.io.IOException;
-import java.security.Principal;
-import java.security.PrivilegedExceptionAction;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.concurrent.Callable;
-
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-
-import org.apache.hadoop.gateway.audit.api.Action;
-import org.apache.hadoop.gateway.audit.api.ActionOutcome;
-import org.apache.hadoop.gateway.audit.api.AuditService;
-import org.apache.hadoop.gateway.audit.api.AuditServiceFactory;
-import org.apache.hadoop.gateway.audit.api.Auditor;
-import org.apache.hadoop.gateway.audit.api.ResourceType;
-import org.apache.hadoop.gateway.audit.log4j.audit.AuditConstants;
-import org.apache.hadoop.gateway.security.GroupPrincipal;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.apache.shiro.SecurityUtils;
-import org.apache.shiro.subject.Subject;
-
-public class ShiroSubjectIdentityAdapter implements Filter {
-  
-  private static final String SUBJECT_USER_GROUPS = "subject.userGroups";
-  private static AuditService auditService = AuditServiceFactory.getAuditService();
-  private static Auditor auditor = auditService.getAuditor(
-      AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
-      AuditConstants.KNOX_COMPONENT_NAME );
-  
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-  }
-
-  public void destroy() {
-  }
-
-  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
-      throws IOException, ServletException {
-    
-    Subject subject = SecurityUtils.getSubject();
-    
-    // trigger call to shiro authorization realm
-    // we use shiro authorization realm to look up groups
-    subject.hasRole("authenticatedUser");
-
-    CallableChain callableChain = new CallableChain(request, response, chain);
-    SecurityUtils.getSubject().execute(callableChain);
-  }
-  
-  private static class CallableChain implements Callable<Void> {
-    private FilterChain chain = null;
-    ServletRequest request = null;
-    ServletResponse response = null;
-    
-    CallableChain(ServletRequest request, ServletResponse response, FilterChain chain) {
-      this.request = request;
-      this.response = response;
-      this.chain = chain;
-    }
-
-    @Override
-    public Void call() throws Exception {
-      PrivilegedExceptionAction<Void> action = new PrivilegedExceptionAction<Void>() {
-        @Override
-        public Void run() throws Exception {
-          chain.doFilter( request, response );
-          return null;
-        }
-      };
-      Subject shiroSubject = SecurityUtils.getSubject();
-
-      if (shiroSubject == null || shiroSubject.getPrincipal() == null) {
-        throw new IllegalStateException("Unable to determine authenticated user from Shiro, please check that your Knox Shiro configuration is correct");
-      }
-
-      final String principal = (String) shiroSubject.getPrincipal().toString();
-      HashSet emptySet = new HashSet();
-      Set<Principal> principals = new HashSet<>();
-      Principal p = new PrimaryPrincipal(principal);
-      principals.add(p);
-      auditService.getContext().setUsername( principal ); //KM: Audit Fix
-      String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
-      auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
-
-      Set<String> userGroups = null;
-      // map ldap groups saved in session to Java Subject GroupPrincipal(s)
-      if (SecurityUtils.getSubject().getSession().getAttribute(SUBJECT_USER_GROUPS) != null) {
-        userGroups = (Set<String>)SecurityUtils.getSubject().getSession().getAttribute(SUBJECT_USER_GROUPS);
-      } else { // KnoxLdapRealm case
-        if(  shiroSubject.getPrincipal() instanceof String ) { 
-           userGroups = new HashSet<>(shiroSubject.getPrincipals().asSet());
-           userGroups.remove(principal);
-        } else { // KnoxPamRealm case
-           Set<Principal> shiroPrincipals = new HashSet<>(shiroSubject.getPrincipals().asSet());
-           userGroups = new HashSet<>(); // Here we are creating a new UserGroup
-                                               // so we don't need to remove a Principal
-                                               // In the case of LDAP the userGroup may have already Principal
-                                               // added to the list of groups, so it is not needed.
-           for( Principal shiroPrincipal: shiroPrincipals ) {
-                userGroups.add(shiroPrincipal.toString() );
-           }
-        }
-      }
-      for (String userGroup : userGroups) {
-        Principal gp = new GroupPrincipal(userGroup);
-        principals.add(gp);
-      }
-      auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS, "Groups: " + userGroups );
-      
-//      The newly constructed Sets check whether this Subject has been set read-only 
-//      before permitting subsequent modifications. The newly created Sets also prevent 
-//      illegal modifications by ensuring that callers have sufficient permissions.
-//
-//      To modify the Principals Set, the caller must have AuthPermission("modifyPrincipals"). 
-//      To modify the public credential Set, the caller must have AuthPermission("modifyPublicCredentials"). 
-//      To modify the private credential Set, the caller must have AuthPermission("modifyPrivateCredentials").
-      javax.security.auth.Subject subject = new javax.security.auth.Subject(true, principals, emptySet, emptySet);
-      javax.security.auth.Subject.doAs( subject, action );
-      
-      return null;
-    }
-    
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxCacheManager.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxCacheManager.java b/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxCacheManager.java
deleted file mode 100644
index cf2d529..0000000
--- a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxCacheManager.java
+++ /dev/null
@@ -1,27 +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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.shirorealm;
-
-import org.apache.shiro.cache.ehcache.EhCacheManager;
-
-public class KnoxCacheManager extends EhCacheManager {
-
-  public KnoxCacheManager() {
-    setCacheManager(net.sf.ehcache.CacheManager.create());
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxLdapContextFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxLdapContextFactory.java b/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxLdapContextFactory.java
deleted file mode 100644
index b4d0c5c..0000000
--- a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxLdapContextFactory.java
+++ /dev/null
@@ -1,128 +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.hadoop.gateway.shirorealm;
-
-import java.util.Hashtable;
-
-import javax.naming.Context;
-import javax.naming.NamingException;
-import javax.naming.ldap.LdapContext;
-
-import org.apache.hadoop.gateway.GatewayMessages;
-import org.apache.hadoop.gateway.GatewayServer;
-import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.config.impl.GatewayConfigImpl;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.security.AliasService;
-import org.apache.hadoop.gateway.services.security.AliasServiceException;
-import org.apache.hadoop.gateway.util.KnoxCLI;
-import org.apache.shiro.realm.ldap.JndiLdapContextFactory;
-
-/**
- * An extension of {@link JndiLdapContextFactory} that allows a different authentication mechanism
- * for system-level authentications (as used by authorization lookups, for example)
- * compared to regular authentication.
- * 
- * <p>
- * See {@link IsisLdapRealm} for typical configuration within <tt>shiro.ini</tt>.
- */
-public class KnoxLdapContextFactory extends JndiLdapContextFactory {
-
-    private static GatewayMessages LOG = MessagesFactory.get( GatewayMessages.class );
-  
-    private String systemAuthenticationMechanism = "simple";
-    private String clusterName = "";
-
-    public KnoxLdapContextFactory() {
-      setAuthenticationMechanism("simple");
-    }
-    
-    @SuppressWarnings({ "unchecked", "rawtypes" })
-    @Override
-    protected LdapContext createLdapContext(Hashtable env) throws NamingException {
-        if(getSystemUsername() != null && getSystemUsername().equals(env.get(Context.SECURITY_PRINCIPAL))) {
-            env.put(Context.SECURITY_AUTHENTICATION, getSystemAuthenticationMechanism());
-        }
-        return super.createLdapContext(env);
-    }
-
-    public String getSystemAuthenticationMechanism() {
-        return systemAuthenticationMechanism != null? systemAuthenticationMechanism: getAuthenticationMechanism();
-    }
-    
-    public void setSystemAuthenticationMechanism(String systemAuthenticationMechanism) {
-        this.systemAuthenticationMechanism = systemAuthenticationMechanism;
-    }
-    
-    @Override
-    public void setSystemPassword(String systemPass) {
-     
-      if ( systemPass == null ) {
-        return;
-      }
-      
-      systemPass = systemPass.trim();
-      if (systemPass.length() == 0) {
-        return;
-      }
-      
-      if (!systemPass.startsWith("S{ALIAS=")) {
-        super.setSystemPassword( systemPass );
-        return;
-      }
-      
-      systemPass= systemPass.substring( "S{ALIAS=".length(), systemPass.length() - 1 );
-      String aliasName = systemPass;
-      
-      GatewayServices services = GatewayServer.getGatewayServices();
-      AliasService aliasService = (AliasService)services.getService(GatewayServices.ALIAS_SERVICE);
-      
-      String clusterName = getClusterName();
-      //System.err.println("FACTORY systempass 30: " + systemPass);
-      //System.err.println("FACTORY clustername 40: " + clusterName);
-      //System.err.println("FACTORY SystemProperty GatewayHome 50: " + System.getProperty(GatewayConfig.GATEWAY_HOME_VAR));
-      char[] password = null;
-      try {
-        password = aliasService.getPasswordFromAliasForCluster(clusterName, systemPass);
-      } catch (AliasServiceException e) {
-        LOG.unableToGetPassword(e);
-      }
-      //System.err.println("FACTORY password: " + ((password == null) ? "NULL" : new String(password)));
-      if ( password != null ) {
-        //System.err.println("FACTORY SUCCESS 20 system password :" + new String(password));
-        super.setSystemPassword( new String(password) );
-      } else {
-        //System.err.println("FACTORY FORCING system password to blank");
-        super.setSystemPassword("" );
-        LOG.aliasValueNotFound(clusterName, aliasName);
-      }
-    }
-    
-    public String getClusterName() {
-      return clusterName;
-    }
-
-    public void setClusterName(String clusterName) {
-      if (clusterName != null) {
-        this.clusterName = clusterName.trim();
-      }
-    }
-    
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxLdapRealm.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxLdapRealm.java b/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxLdapRealm.java
deleted file mode 100644
index c81125a..0000000
--- a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxLdapRealm.java
+++ /dev/null
@@ -1,768 +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.hadoop.gateway.shirorealm;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.naming.AuthenticationException;
-import javax.naming.Context;
-import javax.naming.NamingEnumeration;
-import javax.naming.NamingException;
-import javax.naming.PartialResultException;
-import javax.naming.SizeLimitExceededException;
-import javax.naming.directory.Attribute;
-import javax.naming.directory.SearchControls;
-import javax.naming.directory.SearchResult;
-import javax.naming.ldap.Control;
-import javax.naming.ldap.LdapContext;
-import javax.naming.ldap.LdapName;
-import javax.naming.ldap.PagedResultsControl;
-import javax.naming.ldap.PagedResultsResponseControl;
-
-import org.apache.hadoop.gateway.GatewayMessages;
-import org.apache.hadoop.gateway.audit.api.Action;
-import org.apache.hadoop.gateway.audit.api.ActionOutcome;
-import org.apache.hadoop.gateway.audit.api.AuditService;
-import org.apache.hadoop.gateway.audit.api.AuditServiceFactory;
-import org.apache.hadoop.gateway.audit.api.Auditor;
-import org.apache.hadoop.gateway.audit.api.ResourceType;
-import org.apache.hadoop.gateway.audit.log4j.audit.AuditConstants;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.shirorealm.impl.i18n.KnoxShiroMessages;
-import org.apache.shiro.SecurityUtils;
-import org.apache.shiro.authc.AuthenticationInfo;
-import org.apache.shiro.authc.AuthenticationToken;
-import org.apache.shiro.authc.SimpleAuthenticationInfo;
-import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
-import org.apache.shiro.authz.AuthorizationInfo;
-import org.apache.shiro.authz.SimpleAuthorizationInfo;
-import org.apache.shiro.crypto.hash.DefaultHashService;
-import org.apache.shiro.crypto.hash.Hash;
-import org.apache.shiro.crypto.hash.HashRequest;
-import org.apache.shiro.crypto.hash.HashService;
-import org.apache.shiro.realm.ldap.JndiLdapRealm;
-import org.apache.shiro.realm.ldap.LdapContextFactory;
-import org.apache.shiro.realm.ldap.LdapUtils;
-import org.apache.shiro.subject.MutablePrincipalCollection;
-import org.apache.shiro.subject.PrincipalCollection;
-import org.apache.shiro.util.StringUtils;
-
-/**
- * Implementation of {@link org.apache.shiro.realm.ldap.JndiLdapRealm} that also
- * returns each user's groups.
- * This implementation is heavily based on org.apache.isis.security.shiro.IsisLdapRealm.
- * 
- * This implementation saves looked up ldap groups in Shiro Session to make them
- * easy to be looked up outside of this object
- * 
- * <p>
- * Sample config for <tt>shiro.ini</tt>:
- * 
- * [main]
- * ldapRealm=org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm
- * ldapGroupContextFactory=org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory
- * ldapRealm.contextFactory=$ldapGroupContextFactory
- * ldapRealm.contextFactory.authenticationMechanism=simple
- * ldapRealm.contextFactory.url=ldap://localhost:33389
- * ldapRealm.userDnTemplate=uid={0},ou=people,dc=hadoop,dc=apache,dc=org
- * ldapRealm.authorizationEnabled=true
- * ldapRealm.contextFactory.systemAuthenticationMechanism=simple
- * ldapRealm.searchBase=ou=groups,dc=hadoop,dc=apache,dc=org
- * ldapRealm.groupObjectClass=groupofnames
- * ldapRealm.memberAttribute=member
- * ldapRealm.memberAttributeValueTemplate=cn={0},ou=people,dc=hadoop,dc=apache,dc=org
- * ldapRealm.contextFactory.systemUsername=uid=guest,ou=people,dc=hadoop,dc=apache,dc=org
- * ldapRealm.contextFactory.clusterName=sandbox
- * ldapRealm.contextFactory.systemPassword=S{ALIAS=ldcSystemPassword}
- * [urls]
- * **=authcBasic
- *
- * # optional mapping from physical groups to logical application roles
- * ldapRealm.rolesByGroup = \
- *    LDN_USERS: user_role,\
- *    NYK_USERS: user_role,\
- *    HKG_USERS: user_role,\
- *    GLOBAL_ADMIN: admin_role,\
- *    DEMOS: self-install_role
- * 
- * ldapRealm.permissionsByRole=\
- *    user_role = *:ToDoItemsJdo:*:*,\
- *                *:ToDoItem:*:*; \
- *    self-install_role = *:ToDoItemsFixturesService:install:* ; \
- *    admin_role = *
- * 
- * securityManager.realms = $ldapRealm
- * 
- * </pre>
- */
-public class KnoxLdapRealm extends JndiLdapRealm {
-
-    private static GatewayMessages LOG = MessagesFactory.get( GatewayMessages.class );
-    KnoxShiroMessages ShiroLog = MessagesFactory.get( KnoxShiroMessages.class );
-    private static AuditService auditService = AuditServiceFactory.getAuditService();
-    private static Auditor auditor = auditService.getAuditor(
-        AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
-        AuditConstants.KNOX_COMPONENT_NAME );
-
-    private static Pattern TEMPLATE_PATTERN = Pattern.compile( "\\{(\\d+?)\\}" );
-    private static String DEFAULT_PRINCIPAL_REGEX = "(.*)";
-    private static final String MEMBER_SUBSTITUTION_TOKEN = "{0}";
-
-    private static final SearchControls SUBTREE_SCOPE = new SearchControls();
-    private static final SearchControls ONELEVEL_SCOPE = new SearchControls();
-    private static final SearchControls OBJECT_SCOPE = new SearchControls();
-
-    private static final String  SUBJECT_USER_ROLES = "subject.userRoles";
-    private static final String  SUBJECT_USER_GROUPS = "subject.userGroups";
-
-    private static final String  MEMBER_URL = "memberUrl";
-
-    private static final String POSIX_GROUP = "posixGroup";
-
-    private static final String HASHING_ALGORITHM = "SHA-256";
-
-    static {
-          SUBTREE_SCOPE.setSearchScope(SearchControls.SUBTREE_SCOPE);
-          ONELEVEL_SCOPE.setSearchScope(SearchControls.ONELEVEL_SCOPE);
-          OBJECT_SCOPE.setSearchScope( SearchControls.OBJECT_SCOPE );
-      }
-
- 
-    private String searchBase;
-    private String userSearchBase;
-    private String principalRegex = DEFAULT_PRINCIPAL_REGEX;
-    private Pattern principalPattern = Pattern.compile( DEFAULT_PRINCIPAL_REGEX );
-    private String userDnTemplate = "{0}";
-    private String userSearchFilter = null;
-    private String userSearchAttributeTemplate = "{0}";
-    private String userSearchScope = "subtree";
-
-    private String groupSearchBase;
-
-    private String groupObjectClass = "groupOfNames";
-    
-    //  typical value: member, uniqueMember, meberUrl
-    private String memberAttribute = "member";
-
-    private String groupIdAttribute = "cn";
-    
-    private String memberAttributeValuePrefix = "uid={0}";
-    private String memberAttributeValueSuffix = "";
-    
-    private final Map<String,String> rolesByGroup = new LinkedHashMap<String, String>();
-    private final Map<String,List<String>> permissionsByRole = new LinkedHashMap<String, List<String>>();
-    
-    private boolean authorizationEnabled;
-
-    private String userSearchAttributeName;
-    private String userObjectClass = "person";
-
-    private HashService hashService = new DefaultHashService();
-
-    public KnoxLdapRealm() {
-      HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher(HASHING_ALGORITHM);
-      setCredentialsMatcher(credentialsMatcher);
-    }
-
-  @Override
-  //KNOX-534 overriding this method to be able to audit authentication exceptions
-  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws org.apache.shiro.authc.AuthenticationException {
-    try {
-      return super.doGetAuthenticationInfo(token);
-    } catch ( org.apache.shiro.authc.AuthenticationException e ) {
-      auditor.audit( Action.AUTHENTICATION , token.getPrincipal().toString(), ResourceType.PRINCIPAL, ActionOutcome.FAILURE, e.getMessage() );
-      ShiroLog.failedLoginInfo(token);
-      ShiroLog.failedLoginStackTrace(e);
-      ShiroLog.failedLoginAttempt(e.getCause());
-
-      throw e;
-    }
-  }
-
-  /**
-     * Get groups from LDAP.
-     * 
-     * @param principals
-     *            the principals of the Subject whose AuthenticationInfo should
-     *            be queried from the LDAP server.
-     * @param ldapContextFactory
-     *            factory used to retrieve LDAP connections.
-     * @return an {@link AuthorizationInfo} instance containing information
-     *         retrieved from the LDAP server.
-     * @throws NamingException
-     *             if any LDAP errors occur during the search.
-     */
-    @Override
-    protected AuthorizationInfo queryForAuthorizationInfo(final PrincipalCollection principals, 
-        final LdapContextFactory ldapContextFactory) throws NamingException {
-      if (!isAuthorizationEnabled()) {
-        return null;
-      }
-      final Set<String> roleNames = getRoles(principals, ldapContextFactory);
-        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(roleNames);
-        Set<String> stringPermissions = permsFor(roleNames);
-        simpleAuthorizationInfo.setStringPermissions(stringPermissions);
-        return simpleAuthorizationInfo;
-    }
-
-    private Set<String> getRoles(PrincipalCollection principals,
-        final LdapContextFactory ldapContextFactory) throws NamingException {
-        final String username = (String) getAvailablePrincipal(principals);
-
-        LdapContext systemLdapCtx = null;
-        try {
-            systemLdapCtx = ldapContextFactory.getSystemLdapContext();
-            return rolesFor(principals, username, systemLdapCtx, ldapContextFactory);
-        } catch (AuthenticationException e) {
-          LOG.failedToGetSystemLdapConnection(e);
-          return Collections.emptySet();
-        } finally {
-            LdapUtils.closeContext(systemLdapCtx);
-        }
-    }
-
-    private Set<String> rolesFor(PrincipalCollection principals, final String userName, final LdapContext ldapCtx,
-        final LdapContextFactory ldapContextFactory) throws NamingException {
-      final Set<String> roleNames = new HashSet<>();
-      final Set<String> groupNames = new HashSet<>();
-
-      String userDn;
-      if (userSearchAttributeName == null || userSearchAttributeName.isEmpty()) {
-        // memberAttributeValuePrefix and memberAttributeValueSuffix were computed from memberAttributeValueTemplate
-        userDn = memberAttributeValuePrefix + userName + memberAttributeValueSuffix;
-      } else {
-        userDn = getUserDn(userName);
-      }
-
-      // Activate paged results
-      int pageSize = 100;
-      int numResults = 0;
-      byte[] cookie = null;
-      try {
-        ldapCtx.addToEnvironment(Context.REFERRAL, "ignore");
-
-        ldapCtx.setRequestControls(new Control[]{new PagedResultsControl(pageSize, Control.NONCRITICAL)});
-
-        do {
-          // ldapsearch -h localhost -p 33389 -D uid=guest,ou=people,dc=hadoop,dc=apache,dc=org -w  guest-password
-          //       -b dc=hadoop,dc=apache,dc=org -s sub '(objectclass=*)'
-
-          NamingEnumeration<SearchResult> searchResultEnum = null;
-          try {
-            searchResultEnum = ldapCtx.search(
-                getGroupSearchBase(),
-                "objectClass=" + groupObjectClass,
-                SUBTREE_SCOPE);
-
-            while (searchResultEnum != null && searchResultEnum.hasMore()) { // searchResults contains all the groups in search scope
-              numResults++;
-              final SearchResult group = searchResultEnum.next();
-              addRoleIfMember(userDn, group, roleNames, groupNames, ldapContextFactory);
-            }
-          } catch (PartialResultException e) {
-            LOG.ignoringPartialResultException();
-          } finally {
-            if (searchResultEnum != null) {
-              searchResultEnum.close();
-            }
-          }
-
-          // Examine the paged results control response
-          Control[] controls = ldapCtx.getResponseControls();
-          if (controls != null) {
-            for (Control control : controls) {
-              if (control instanceof PagedResultsResponseControl) {
-                PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
-                cookie = prrc.getCookie();
-              }
-            }
-          }
-
-          // Re-activate paged results
-          ldapCtx.setRequestControls(new Control[]{new PagedResultsControl(pageSize, cookie, Control.CRITICAL)});
-        } while (cookie != null);
-      } catch (SizeLimitExceededException e) {
-        LOG.sizeLimitExceededOnlyRetrieved(numResults);
-//        System.out.println("Only retrieved first " + numResults + " groups due to SizeLimitExceededException.");
-      } catch(IOException e) {
-        LOG.unableToSetupPagedResults();
-//        System.out.println("Unabled to setup paged results");
-      }
-
-      // save role names and group names in session so that they can be easily looked up outside of this object
-      SecurityUtils.getSubject().getSession().setAttribute(SUBJECT_USER_ROLES, roleNames);
-      SecurityUtils.getSubject().getSession().setAttribute(SUBJECT_USER_GROUPS, groupNames);
-      if (!groupNames.isEmpty() && (principals instanceof MutablePrincipalCollection)) {
-        ((MutablePrincipalCollection)principals).addAll(groupNames, getName());
-      }
-      LOG.lookedUpUserRoles(roleNames, userName);
-
-      return roleNames;
-    }
-
-  private void addRoleIfMember(final String userDn, final SearchResult group,
-      final Set<String> roleNames, final Set<String> groupNames,
-      final LdapContextFactory ldapContextFactory) throws NamingException {
-
-    NamingEnumeration<? extends Attribute> attributeEnum = null;
-    NamingEnumeration<?> e = null;
-    try {
-      LdapName userLdapDn = new LdapName(userDn);
-      Attribute attribute = group.getAttributes().get(getGroupIdAttribute());
-      String groupName = attribute.get().toString();
-      
-      attributeEnum = group
-          .getAttributes().getAll();
-      while (attributeEnum.hasMore()) {
-        final Attribute attr = attributeEnum.next();
-        if (!memberAttribute.equalsIgnoreCase(attr.getID())) {
-          continue;
-        }
-        e = attr.getAll();
-        while (e.hasMore()) {
-          String attrValue = e.next().toString();
-          if (memberAttribute.equalsIgnoreCase(MEMBER_URL)) {
-            boolean dynamicGroupMember = isUserMemberOfDynamicGroup(userLdapDn,
-                attrValue, // memberUrl value
-                ldapContextFactory);
-            if (dynamicGroupMember) {
-              groupNames.add(groupName);
-              String roleName = roleNameFor(groupName);
-              if (roleName != null) {
-                roleNames.add(roleName);
-              } else {
-                roleNames.add(groupName);
-              }
-            }
-          } else {
-            if (groupObjectClass.equalsIgnoreCase(POSIX_GROUP)){
-              attrValue = memberAttributeValuePrefix + attrValue + memberAttributeValueSuffix;
-            }
-            if (userLdapDn.equals(new LdapName(attrValue))) {
-              groupNames.add(groupName);
-              String roleName = roleNameFor(groupName);
-              if (roleName != null) {
-                roleNames.add(roleName);
-              } else {
-                roleNames.add(groupName);
-              }
-              break;
-            }
-          }
-        }
-      }
-    }
-    finally {
-      try {
-        if (attributeEnum != null) {
-          attributeEnum.close();
-        }
-      }
-      finally {
-        if (e != null) {
-          e.close();
-        }
-      }
-    }
-  }
-
-    private String roleNameFor(String groupName) {
-        return !rolesByGroup.isEmpty() ? rolesByGroup.get(groupName) : groupName;
-    }
-
-
-    private Set<String> permsFor(Set<String> roleNames) {
-        Set<String> perms = new LinkedHashSet<String>(); // preserve order
-        for(String role: roleNames) {
-            List<String> permsForRole = permissionsByRole.get(role);
-            if(permsForRole != null) {
-                perms.addAll(permsForRole);
-            }
-        }
-        return perms;
-    }
-
-    public String getSearchBase() {
-        return searchBase;
-    }
-
-    public void setSearchBase(String searchBase) {
-      this.searchBase = searchBase;
-    }
-
-    public String getUserSearchBase() {
-      return  (userSearchBase != null && !userSearchBase.isEmpty()) ? 
-          userSearchBase : searchBase;
-    }
-
-    public void setUserSearchBase(String userSearchBase) {
-      this.userSearchBase = userSearchBase;
-    }
-
-    public String getGroupSearchBase() {
-      return (groupSearchBase != null && !groupSearchBase.isEmpty()) ? 
-          groupSearchBase : searchBase;
-    }
-
-    public void setGroupSearchBase(String groupSearchBase) {
-      this.groupSearchBase = groupSearchBase;
-    }
-
-    public String getGroupObjectClass() {
-      return groupObjectClass;
-    }
-    
-    public void setGroupObjectClass(String groupObjectClassAttribute) {
-        this.groupObjectClass = groupObjectClassAttribute;
-    }
-
-    public String getMemberAttribute() {
-      return memberAttribute;
-    }
-    
-    public void setMemberAttribute(String memberAttribute) {
-        this.memberAttribute = memberAttribute;
-    }
-    
-    public String getGroupIdAttribute() {
-      return groupIdAttribute;
-    }
-    
-    public void setGroupIdAttribute(String groupIdAttribute) {
-        this.groupIdAttribute = groupIdAttribute;
-    }
-    
-    public void setMemberAttributeValueTemplate(String template) {
-        if (!StringUtils.hasText(template)) {
-            String msg = "User DN template cannot be null or empty.";
-            throw new IllegalArgumentException(msg);
-        }
-        int index = template.indexOf(MEMBER_SUBSTITUTION_TOKEN);
-        if (index < 0) {
-            String msg = "Member attribute value template must contain the '" +
-                    MEMBER_SUBSTITUTION_TOKEN + "' replacement token to understand how to " +
-                    "parse the group members.";
-            throw new IllegalArgumentException(msg);
-        }
-        String prefix = template.substring(0, index);
-        String suffix = template.substring(prefix.length() + MEMBER_SUBSTITUTION_TOKEN.length());
-        this.memberAttributeValuePrefix = prefix;
-        this.memberAttributeValueSuffix = suffix;
-    }
-
-    public void setRolesByGroup(Map<String, String> rolesByGroup) {
-        this.rolesByGroup.putAll(rolesByGroup);
-    }
-
-    public void setPermissionsByRole(String permissionsByRoleStr) {
-        permissionsByRole.putAll(parsePermissionByRoleString(permissionsByRoleStr));
-    }
-    
-    public boolean isAuthorizationEnabled() {
-      return authorizationEnabled;
-    }
-
-    public void setAuthorizationEnabled(boolean authorizationEnabled) {
-      this.authorizationEnabled = authorizationEnabled;
-    }
-
-    public String getUserSearchAttributeName() {
-        return userSearchAttributeName;
-    }
-
-    public void setUserSearchAttributeName(String userSearchAttributeName) {
-      if (userSearchAttributeName != null) {
-        userSearchAttributeName = userSearchAttributeName.trim();
-      }
-      this.userSearchAttributeName = userSearchAttributeName;
-    }
-
-    public String getUserObjectClass() {
-      return userObjectClass;
-    }
-    
-    public void setUserObjectClass(String userObjectClass) {
-        this.userObjectClass = userObjectClass;
-    }
-
-    private Map<String, List<String>> parsePermissionByRoleString(String permissionsByRoleStr) {
-      Map<String,List<String>> perms = new HashMap<>();
-   
-      // split by semicolon ; then by eq = then by  comma ,
-      StringTokenizer stSem = new StringTokenizer(permissionsByRoleStr, ";");
-      while (stSem.hasMoreTokens()) {
-        String roleAndPerm = stSem.nextToken();
-        StringTokenizer stEq = new StringTokenizer(roleAndPerm, "=");
-        if (stEq.countTokens() != 2) {
-          continue;
-        }
-        String role = stEq.nextToken().trim();
-        String perm = stEq.nextToken().trim();
-        StringTokenizer stCom = new StringTokenizer(perm, ",");
-        List<String> permList = new ArrayList<String>();
-        while (stCom.hasMoreTokens()) {
-          permList.add(stCom.nextToken().trim());
-        }
-        perms.put(role,  permList);
-      }
-      return perms;
-  }
-
-  boolean isUserMemberOfDynamicGroup(LdapName userLdapDn, String memberUrl,
-      final LdapContextFactory ldapContextFactory) throws NamingException {
-
-    // ldap://host:port/dn?attributes?scope?filter?extensions
-
-    boolean member = false;
-
-    if (memberUrl == null) {
-      return false;
-    }
-    String[] tokens = memberUrl.split("\\?");
-    if (tokens.length < 4) {
-      return false;
-    }
-
-    String searchBaseString = tokens[0]
-        .substring(tokens[0].lastIndexOf("/") + 1);
-    String searchScope = tokens[2];
-    String searchFilter = tokens[3];
-
-    LdapName searchBaseDn = new LdapName(searchBaseString);
-
-    // do scope test
-    if (searchScope.equalsIgnoreCase("base")) {
-      return false;
-    }
-    if (!userLdapDn.toString().endsWith(searchBaseDn.toString())) {
-      return false;
-    }
-    if (searchScope.equalsIgnoreCase("one")
-        && (userLdapDn.size() != searchBaseDn.size() - 1)) {
-      return false;
-    }
-    // search for the filter, substituting base with userDn
-    // search for base_dn=userDn, scope=base, filter=filter
-    LdapContext systemLdapCtx = null;
-    systemLdapCtx = ldapContextFactory.getSystemLdapContext();
-    NamingEnumeration<SearchResult> searchResultEnum = null;
-    try {
-      searchResultEnum = systemLdapCtx
-        .search(userLdapDn, searchFilter,
-            searchScope.equalsIgnoreCase("sub") ? SUBTREE_SCOPE
-                : ONELEVEL_SCOPE);
-      if (searchResultEnum.hasMore()) {
-        return true;
-      }
-    }
-    finally {
-        try {
-          if (searchResultEnum != null) {
-            searchResultEnum.close();
-          }
-        }
-        finally {
-          LdapUtils.closeContext(systemLdapCtx);
-        }
-    }
-    return member;
-  }
-
-  public String getPrincipalRegex() {
-    return principalRegex;
-  }
-
-  public void setPrincipalRegex( String regex ) {
-    if( regex == null || regex.trim().isEmpty() ) {
-      principalPattern = Pattern.compile( DEFAULT_PRINCIPAL_REGEX );
-      principalRegex = DEFAULT_PRINCIPAL_REGEX;
-    } else {
-      regex = regex.trim();
-      Pattern pattern = Pattern.compile( regex );
-      principalPattern = pattern;
-      principalRegex = regex;
-    }
-  }
-
-  public String getUserSearchAttributeTemplate() {
-    return userSearchAttributeTemplate;
-  }
-
-  public void setUserSearchAttributeTemplate( final String template ) {
-    this.userSearchAttributeTemplate = ( template == null ? null : template.trim() );
-  }
-
-  public String getUserSearchFilter() {
-    return userSearchFilter;
-  }
-
-  public void setUserSearchFilter( final String filter ) {
-    this.userSearchFilter = ( filter == null ? null : filter.trim() );
-  }
-
-  public String getUserSearchScope() {
-    return userSearchScope;
-  }
-
-  public void setUserSearchScope( final String scope ) {
-    this.userSearchScope = ( scope == null ? null : scope.trim().toLowerCase() );
-  }
-
-  private SearchControls getUserSearchControls() {
-    SearchControls searchControls = SUBTREE_SCOPE;
-    if ( "onelevel".equalsIgnoreCase( userSearchScope ) ) {
-      searchControls = ONELEVEL_SCOPE;
-    } else if ( "object".equalsIgnoreCase( userSearchScope ) ) {
-      searchControls = OBJECT_SCOPE;
-    }
-    return searchControls;
-  }
-
-  @Override
-  public void setUserDnTemplate( final String template ) throws IllegalArgumentException {
-    userDnTemplate = template;
-  }
-
-  private Matcher matchPrincipal( final String principal ) {
-    Matcher matchedPrincipal = principalPattern.matcher( principal );
-    if( !matchedPrincipal.matches() ) {
-      throw new IllegalArgumentException( "Principal " + principal + " does not match " + principalRegex );
-    }
-    return matchedPrincipal;
-  }
-
-  /**
-     * Returns the LDAP User Distinguished Name (DN) to use when acquiring an
-     * {@link javax.naming.ldap.LdapContext LdapContext} from the {@link LdapContextFactory}.
-     * <p/>
-     * If the the {@link #getUserDnTemplate() userDnTemplate} property has been set, this implementation will construct
-     * the User DN by substituting the specified {@code principal} into the configured template.  If the
-     * {@link #getUserDnTemplate() userDnTemplate} has not been set, the method argument will be returned directly
-     * (indicating that the submitted authentication token principal <em>is</em> the User DN).
-     *
-     * @param principal the principal to substitute into the configured {@link #getUserDnTemplate() userDnTemplate}.
-     * @return the constructed User DN to use at runtime when acquiring an {@link javax.naming.ldap.LdapContext}.
-     * @throws IllegalArgumentException if the method argument is null or empty
-     * @throws IllegalStateException    if the {@link #getUserDnTemplate userDnTemplate} has not been set.
-     * @see LdapContextFactory#getLdapContext(Object, Object)
-     */
-    @Override
-    protected String getUserDn( final String principal ) throws IllegalArgumentException, IllegalStateException {
-      String userDn;
-      Matcher matchedPrincipal = matchPrincipal( principal );
-      String userSearchBase = getUserSearchBase();
-      String userSearchAttributeName = getUserSearchAttributeName();
-
-      // If not searching use the userDnTemplate and return.
-      if ( ( userSearchBase == null || userSearchBase.isEmpty() ) ||
-          ( userSearchAttributeName == null &&
-              userSearchFilter == null &&
-              !"object".equalsIgnoreCase( userSearchScope ) ) ) {
-        userDn = expandTemplate( userDnTemplate, matchedPrincipal );
-        LOG.computedUserDn( userDn, principal );
-        return userDn;
-      }
-
-      // Create the searchBase and searchFilter from config.
-      String searchBase = expandTemplate( getUserSearchBase(), matchedPrincipal );
-      String searchFilter = null;
-      if ( userSearchFilter == null ) {
-        if ( userSearchAttributeName == null ) {
-          searchFilter = String.format( "(objectclass=%1$s)", getUserObjectClass() );
-        } else {
-          searchFilter = String.format(
-              "(&(objectclass=%1$s)(%2$s=%3$s))",
-              getUserObjectClass(),
-              userSearchAttributeName,
-              expandTemplate( getUserSearchAttributeTemplate(), matchedPrincipal ) );
-        }
-      } else {
-        searchFilter = expandTemplate( userSearchFilter, matchedPrincipal );
-      }
-      SearchControls searchControls = getUserSearchControls();
-
-      // Search for userDn and return.
-      LdapContext systemLdapCtx = null;
-      NamingEnumeration<SearchResult> searchResultEnum = null;
-      try {
-        systemLdapCtx = getContextFactory().getSystemLdapContext();
-        LOG.searchBaseFilterScope(searchBase, searchFilter, userSearchScope);
-        searchResultEnum = systemLdapCtx.search( searchBase, searchFilter, searchControls );
-        // SearchResults contains all the entries in search scope
-        if (searchResultEnum.hasMore()) {
-          SearchResult searchResult = searchResultEnum.next();
-          userDn = searchResult.getNameInNamespace();
-          LOG.searchedAndFoundUserDn(userDn, principal);
-          return userDn;
-        } else {
-          throw new IllegalArgumentException("Illegal principal name: " + principal);
-        }
-      } catch (AuthenticationException e) {
-        LOG.failedToGetSystemLdapConnection(e);
-        throw new IllegalArgumentException("Illegal principal name: " + principal);
-      } catch (NamingException e) {
-        throw new IllegalArgumentException("Hit NamingException: " + e.getMessage());
-      } finally {
-        try {
-          if (searchResultEnum != null) {
-            searchResultEnum.close();
-          }
-        } catch (NamingException e) {
-          // Ignore exception on close.
-        }
-        finally {
-          LdapUtils.closeContext(systemLdapCtx);
-        }
-      }
-    }
-
-    @Override
-    protected AuthenticationInfo createAuthenticationInfo(AuthenticationToken token, Object ldapPrincipal, Object ldapCredentials, LdapContext ldapContext) throws NamingException {
-      HashRequest.Builder builder = new HashRequest.Builder();
-      Hash credentialsHash = hashService.computeHash(builder.setSource(token.getCredentials()).setAlgorithmName(HASHING_ALGORITHM).build());
-      return new SimpleAuthenticationInfo(token.getPrincipal(), credentialsHash.toHex(), credentialsHash.getSalt(), getName());
-    }
-
-  private static final String expandTemplate( final String template, final Matcher input ) {
-    String output = template;
-    Matcher matcher = TEMPLATE_PATTERN.matcher( output );
-    while( matcher.find() ) {
-      String lookupStr = matcher.group( 1 );
-      int lookupIndex = Integer.parseInt( lookupStr );
-      String lookupValue = input.group( lookupIndex );
-      output = matcher.replaceFirst( lookupValue == null ? "" : lookupValue );
-      matcher = TEMPLATE_PATTERN.matcher( output );
-    }
-    return output;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxPamRealm.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxPamRealm.java b/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxPamRealm.java
deleted file mode 100644
index 45cdd45..0000000
--- a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/KnoxPamRealm.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.hadoop.gateway.shirorealm;
-
-import java.util.LinkedHashSet;
-import java.util.Set;
-import org.apache.hadoop.gateway.GatewayMessages;
-import org.apache.hadoop.gateway.audit.api.Action;
-import org.apache.hadoop.gateway.audit.api.ActionOutcome;
-import org.apache.hadoop.gateway.audit.api.ResourceType;
-import org.apache.hadoop.gateway.audit.api.AuditService;
-import org.apache.hadoop.gateway.audit.api.AuditServiceFactory;
-import org.apache.hadoop.gateway.audit.api.Auditor;
-import org.apache.hadoop.gateway.audit.log4j.audit.AuditConstants;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.shirorealm.impl.i18n.KnoxShiroMessages;
-import org.apache.shiro.SecurityUtils;
-import org.apache.shiro.authc.AuthenticationException;
-
-import org.apache.shiro.authc.AuthenticationInfo;
-import org.apache.shiro.authc.AuthenticationToken;
-import org.apache.shiro.authc.SimpleAuthenticationInfo;
-import org.apache.shiro.authc.UsernamePasswordToken;
-import org.apache.shiro.authz.AuthorizationInfo;
-import org.apache.shiro.authz.SimpleAuthorizationInfo;
-import org.apache.shiro.realm.AuthorizingRealm;
-import org.apache.shiro.subject.PrincipalCollection;
-import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
-import org.apache.shiro.crypto.hash.*;
-import org.jvnet.libpam.PAM;
-import org.jvnet.libpam.PAMException;
-import org.jvnet.libpam.UnixUser;
-
-/**
- * A Unix-style
- * <a href="http://www.kernel.org/pub/linux/libs/pam/index.html">PAM</a>
- * {@link org.apache.shiro.realm.Realm Realm} that uses
- * <a href="https://github.com/kohsuke/libpam4j">libpam4j</a> to interface with
- * the PAM system libraries.
- * <p>
- * This is a single Shiro {@code Realm} that interfaces with the OS's
- * {@code PAM} subsystem which itself can be connected to several authentication
- * methods (unix-crypt,Samba, LDAP, etc.)
- * <p>
- * This {@code Realm} can also take part in Shiro's Pluggable Realms concept.
- * <p>
- * Using a {@code KnoxPamRealm} requires a PAM {@code service} name. This is the
- * name of the file under {@code /etc/pam.d} that is used to initialise and
- * configure the PAM subsytem. Normally, this file reflects the application
- * using it. For example {@code gdm}, {@code su}, etc. There is no default value
- * for this propery.
- * <p>
- * For example, defining this realm in Shiro .ini:
- *
- * <pre>
- * [main]
- * pamRealm = org.apache.shiro.realm.libpam4j.KnoxPamRealm
- * pamRealm.service = [ knox-pam-ldap-service | knox-pam-os-service | knox-pam-winbind-service ]
- * [urls]
- * **=authcBasic
- * </pre>
- *
- */
-
-public class KnoxPamRealm extends AuthorizingRealm {
-  private static final String HASHING_ALGORITHM = "SHA-256";
-  private static final String SUBJECT_USER_ROLES = "subject.userRoles";
-  private static final String SUBJECT_USER_GROUPS = "subject.userGroups";
-  private HashService hashService = new DefaultHashService();
-  KnoxShiroMessages ShiroLog = MessagesFactory.get(KnoxShiroMessages.class);
-  GatewayMessages GatewayLog = MessagesFactory.get(GatewayMessages.class);
-  private static AuditService auditService = AuditServiceFactory.getAuditService();
-  private static Auditor auditor = auditService.getAuditor(AuditConstants.DEFAULT_AUDITOR_NAME,
-      AuditConstants.KNOX_SERVICE_NAME, AuditConstants.KNOX_COMPONENT_NAME);
-
-  private String service;
-
-  public KnoxPamRealm() {
-    HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher(HASHING_ALGORITHM);
-    setCredentialsMatcher(credentialsMatcher);
-  }
-
-  public void setService(String service) {
-    this.service = service;
-  }
-
-  public String getService() {
-    return this.service;
-  }
-
-  @Override
-  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
-    Set<String> roles = new LinkedHashSet<String>();
-
-    UnixUserPrincipal user = principals.oneByType(UnixUserPrincipal.class);
-    if (user != null) {
-      roles.addAll(user.getUnixUser().getGroups());
-    }
-    SecurityUtils.getSubject().getSession().setAttribute(SUBJECT_USER_ROLES, roles);
-    SecurityUtils.getSubject().getSession().setAttribute(SUBJECT_USER_GROUPS, roles);
-
-    /* Coverity Scan CID 1361682 */
-    String userName = null;
-
-    if (user != null) {
-      userName = user.getName();
-    }
-
-    GatewayLog.lookedUpUserRoles(roles, userName);
-    return new SimpleAuthorizationInfo(roles);
-  }
-
-  @Override
-  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
-    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
-    UnixUser user = null;
-    try {
-      user = (new PAM(this.getService())).authenticate(upToken.getUsername(), new String(upToken.getPassword()));
-    } catch (PAMException e) {
-      handleAuthFailure(token, e.getMessage(), e);
-    }
-    HashRequest.Builder builder = new HashRequest.Builder();
-    Hash credentialsHash = hashService
-        .computeHash(builder.setSource(token.getCredentials()).setAlgorithmName(HASHING_ALGORITHM).build());
-    /* Coverity Scan CID 1361684 */
-    if (credentialsHash == null) {
-      handleAuthFailure(token, "Failed to compute hash", null);
-    }
-    return new SimpleAuthenticationInfo(new UnixUserPrincipal(user), credentialsHash.toHex(), credentialsHash.getSalt(),
-        getName());
-  }
-
-  private void handleAuthFailure(AuthenticationToken token, String errorMessage, Exception e) {
-    auditor.audit(Action.AUTHENTICATION, token.getPrincipal().toString(), ResourceType.PRINCIPAL, ActionOutcome.FAILURE,
-        errorMessage);
-    ShiroLog.failedLoginInfo(token);
-
-    if (e != null) {
-      ShiroLog.failedLoginAttempt(e.getCause());
-      throw new AuthenticationException(e);
-    }
-
-    throw new AuthenticationException(errorMessage);
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/UnixUserPrincipal.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/UnixUserPrincipal.java b/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/UnixUserPrincipal.java
deleted file mode 100644
index a659888..0000000
--- a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/UnixUserPrincipal.java
+++ /dev/null
@@ -1,46 +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.hadoop.gateway.shirorealm;
-
-import java.security.Principal;
-import org.jvnet.libpam.UnixUser;
-
-public class UnixUserPrincipal implements Principal {
-	private final UnixUser userName;
-
-	public UnixUserPrincipal(UnixUser userName) {
-		this.userName = userName;
-	}
-
-	@Override
-	public String getName() {
-		return userName.getUserName();
-	}
-
-	public UnixUser getUnixUser() {
-		return userName;
-	}
-
-	@Override
-	public String toString() {
-		return String.valueOf(userName.getUserName());
-	}
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/impl/i18n/KnoxShiroMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/impl/i18n/KnoxShiroMessages.java b/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/impl/i18n/KnoxShiroMessages.java
deleted file mode 100644
index c9de024..0000000
--- a/gateway-provider-security-shiro/src/main/java/org/apache/hadoop/gateway/shirorealm/impl/i18n/KnoxShiroMessages.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.hadoop.gateway.shirorealm.impl.i18n;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-
-import org.apache.hadoop.gateway.i18n.messages.StackTrace;
-import org.apache.shiro.authc.AuthenticationToken;
-import org.apache.shiro.subject.Subject;
-
-@Messages(logger = "org.apache.hadoop.gateway")
-public interface KnoxShiroMessages {
-
-  @Message(level = MessageLevel.ERROR, text = "Shiro unable to login: {0}")
-  void failedLoginAttempt(Throwable e);
-
-  @Message(level = MessageLevel.INFO, text = "Could not login: {0}")
-  void failedLoginInfo(AuthenticationToken token);
-
-  @Message( level = MessageLevel.DEBUG, text = "Failed to Authenticate with LDAP server: {1}" )
-  void failedLoginStackTrace( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message(level = MessageLevel.INFO, text = "Successfully logged in: {0}, {1}")
-  void successfulLoginAttempt(Subject subject, AuthenticationToken authToken);
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/deploy/impl/ShiroConfig.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/deploy/impl/ShiroConfig.java b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/deploy/impl/ShiroConfig.java
new file mode 100644
index 0000000..4049a93
--- /dev/null
+++ b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/deploy/impl/ShiroConfig.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.knox.gateway.deploy.impl;
+
+import org.apache.knox.gateway.topology.Provider;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class ShiroConfig {
+  
+  private Map<String, Map<String, String>> sections = new LinkedHashMap<String, Map<String, String>>();
+ 
+  public ShiroConfig(Provider provider, String clusterName) {
+    Map<String, String> params = provider.getParams();
+    String name = null;
+    String sectionName = null;
+    String value = null;
+    for(Entry<String, String> entry : params.entrySet()) {
+      int sectionDot = entry.getKey().indexOf('.');
+      if (sectionDot > 0) {
+        sectionName = entry.getKey().substring(0, sectionDot);
+        name = entry.getKey().substring(sectionDot + 1);
+        value = entry.getValue().trim();
+        if (value.startsWith("${ALIAS=") && value.endsWith("}")) {
+          String baseName = name.substring(0, name.lastIndexOf("."));
+          addNameValueToSection(baseName + ".clusterName", clusterName, sectionName);
+          addNameValueToSection(name, "S" + value.substring(1), sectionName);
+        } else {
+          addNameValueToSection(name, value, sectionName);
+        }
+      }
+    }
+  }
+
+  private void addNameValueToSection(String name, String value, String sectionName) {
+    Map<String, String> section = sections.get(sectionName);
+    if (section == null) {
+      section = new LinkedHashMap<String, String>();
+      sections.put(sectionName, section);
+    }
+    section.put(name, value);
+  }
+  
+  public String toString() {
+    StringBuilder sb = new StringBuilder();
+    for(Entry<String, Map<String, String>> section : sections.entrySet()) {
+      sb.append("[").append(section.getKey()).append("]\n");
+      for(Entry<String, String> entry : section.getValue().entrySet()) {
+        sb.append(entry.getKey()).append("=").append(entry.getValue()).append("\n");
+      }
+    }
+    return sb.toString();
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/deploy/impl/ShiroDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/deploy/impl/ShiroDeploymentContributor.java b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/deploy/impl/ShiroDeploymentContributor.java
new file mode 100644
index 0000000..111b13b
--- /dev/null
+++ b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/deploy/impl/ShiroDeploymentContributor.java
@@ -0,0 +1,140 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.deploy.impl;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.filter.RedirectToUrlFilter;
+import org.apache.knox.gateway.filter.ResponseCookieFilter;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+import org.jboss.shrinkwrap.api.asset.StringAsset;
+import org.jboss.shrinkwrap.descriptor.api.webapp30.WebAppDescriptor;
+import org.jboss.shrinkwrap.descriptor.api.webcommon30.SessionConfigType;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+public class ShiroDeploymentContributor extends ProviderDeploymentContributorBase {
+
+  private static final String LISTENER_CLASSNAME = "org.apache.shiro.web.env.EnvironmentLoaderListener";
+  private static final String SHIRO_FILTER_CLASSNAME = "org.apache.shiro.web.servlet.ShiroFilter";
+  private static final String POST_FILTER_CLASSNAME = "ShiroSubjectIdentityAdapter";
+  private static final String COOKIE_FILTER_CLASSNAME = "ResponseCookieFilter";
+  private static final String REDIRECT_FILTER_CLASSNAME = "RedirectToUrlFilter";
+  private static final String SESSION_TIMEOUT = "sessionTimeout";
+  private static final String REMEMBER_ME = "rememberme";
+  private static final String SHRIO_CONFIG_FILE_NAME = "shiro.ini";
+  private static final int DEFAULT_SESSION_TIMEOUT = 30; // 30min
+
+  @Override
+  public String getRole() {
+    return "authentication";
+  }
+
+  @Override
+  public String getName() {
+    return "ShiroProvider";
+  }
+
+  @Override
+  public void contributeProvider( DeploymentContext context, Provider provider ) {
+    // Many filter based authentication mechanisms require a ServletContextListener
+    // to be added and the Knox deployment machinery provides the ability to add this
+    // through the DeploymentContext.
+
+    // Writing provider specific config out to the war for cluster specific config can be
+    // accomplished through the DeploymentContext as well. The JBoss shrinkwrap API can be
+    // used to write the asset to the war.
+
+    // add servletContextListener
+    context.getWebAppDescriptor().createListener().listenerClass( LISTENER_CLASSNAME );
+
+    // add session timeout
+    int st = DEFAULT_SESSION_TIMEOUT;
+    SessionConfigType<WebAppDescriptor> sessionConfig = context.getWebAppDescriptor().createSessionConfig();
+    Map<String, String> params = provider.getParams();
+    String sts = params.get( SESSION_TIMEOUT );
+    if( sts != null && sts.trim().length() != 0 ) {
+      st = Integer.parseInt( sts.trim() );
+    }
+    if( st <= 0 ) {
+      // user default session timeout
+      st = DEFAULT_SESSION_TIMEOUT;
+    }
+    sessionConfig.sessionTimeout( st );
+    sessionConfig.getOrCreateCookieConfig().httpOnly( true );
+    sessionConfig.getOrCreateCookieConfig().secure( true );
+
+    String clusterName = context.getTopology().getName();
+    ShiroConfig config = new ShiroConfig( provider, clusterName );
+    String configStr = config.toString();
+    if( config != null ) {
+      context.getWebArchive().addAsWebInfResource( new StringAsset( configStr ), SHRIO_CONFIG_FILE_NAME );
+    }
+  }
+
+  @Override
+  public void contributeFilter( DeploymentContext context, Provider provider,
+      Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
+    // Leveraging a third party filter is a primary usecase for Knox
+    // in order to do so, we need to make sure that the end result of the third party integration
+    // puts a standard javax.security.auth.Subject on the current thread through a doAs.
+    // As many filters do not use the standard java Subject, often times a post processing filter will
+    // need to be added in order to canonicalize the result into an expected security context.
+
+    // You may also need to do some additional processing of the response in order to not return cookies or other
+    // filter specifics that are not needed for integration with Knox. Below we do that in the pre-processing filter.
+    if (params == null) {
+      params = new ArrayList<FilterParamDescriptor>();
+    }
+    Map<String, String> providerParams = provider.getParams();
+    String redirectToUrl = providerParams.get(RedirectToUrlFilter.REDIRECT_TO_URL);
+    if (redirectToUrl != null) {
+      params.add( resource.createFilterParam()
+          .name(RedirectToUrlFilter.REDIRECT_TO_URL)
+          .value(redirectToUrl));
+      resource.addFilter().name( "Redirect" + getName() ).role(
+          getRole() ).impl( REDIRECT_FILTER_CLASSNAME ).params( params );
+      params.clear();
+    }
+
+    String cookies = providerParams.get( ResponseCookieFilter.RESTRICTED_COOKIES );
+    if (cookies == null) {
+      params.add( resource.createFilterParam()
+          .name( ResponseCookieFilter.RESTRICTED_COOKIES )
+          .value( REMEMBER_ME ) );
+    }
+    else {
+      params.add( resource.createFilterParam()
+          .name(ResponseCookieFilter.RESTRICTED_COOKIES ).value( cookies ) );
+    }
+
+    resource.addFilter().name( "Pre" + getName() ).role(
+        getRole() ).impl( COOKIE_FILTER_CLASSNAME ).params( params );
+    params.clear();
+
+    resource.addFilter().name( getName() ).role(
+        getRole() ).impl( SHIRO_FILTER_CLASSNAME ).params( params );
+    resource.addFilter().name( "Post" + getName() ).role(
+        getRole() ).impl( POST_FILTER_CLASSNAME ).params( params );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/filter/RedirectToUrlFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/filter/RedirectToUrlFilter.java b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/filter/RedirectToUrlFilter.java
new file mode 100644
index 0000000..2ecdd85
--- /dev/null
+++ b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/filter/RedirectToUrlFilter.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.knox.gateway.filter;
+
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+public class RedirectToUrlFilter extends AbstractGatewayFilter {
+  public static final String REDIRECT_TO_URL = "redirectToUrl";
+
+  protected String redirectUrl = null;
+
+  @Override
+  public void init(FilterConfig filterConfig) throws ServletException {
+    super.init(filterConfig);
+    redirectUrl = filterConfig.getInitParameter(REDIRECT_TO_URL);
+  }
+
+  @Override
+  protected void doFilter( HttpServletRequest request,
+      HttpServletResponse response, FilterChain chain ) throws IOException, ServletException {
+    if (redirectUrl != null && request.getHeader("Authorization") == null) {
+      response.sendRedirect(redirectUrl + getOriginalQueryString(request));
+    }
+    chain.doFilter( request, response );
+  }
+
+  private String getOriginalQueryString(HttpServletRequest request) {
+    String originalQueryString = request.getQueryString();
+    return (originalQueryString == null) ? "" : "?" + originalQueryString;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/filter/ResponseCookieFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/filter/ResponseCookieFilter.java b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/filter/ResponseCookieFilter.java
new file mode 100644
index 0000000..9ea9302
--- /dev/null
+++ b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/filter/ResponseCookieFilter.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.knox.gateway.filter;
+
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpServletResponseWrapper;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class ResponseCookieFilter extends AbstractGatewayFilter {
+  public static final String RESTRICTED_COOKIES = "restrictedCookies";
+
+  protected static List<String> restrictedCookies = new ArrayList<String>();
+
+  @Override
+  public void init(FilterConfig filterConfig) throws ServletException {
+    super.init(filterConfig);
+    String cookies = filterConfig.getInitParameter(RESTRICTED_COOKIES);
+    if (cookies != null) {
+      restrictedCookies = Arrays.asList(cookies.split(","));
+    }
+  }
+
+  @Override
+  protected void doFilter( HttpServletRequest request, HttpServletResponse response, FilterChain chain ) throws IOException, ServletException {
+    ResponseWrapper responseWrapper = new ResponseWrapper( response );
+    chain.doFilter( request, responseWrapper );
+  }
+
+  // inner class wraps response to prevent adding of not allowed headers
+  private static class ResponseWrapper extends HttpServletResponseWrapper {
+    public ResponseWrapper( HttpServletResponse response ) {
+      super( response );
+    }
+
+    public void addCookie( Cookie cookie ) {
+      if( cookie != null && isAllowedHeader( cookie.getName() ) ) {
+        super.addCookie( cookie );
+      }
+    }
+
+    public void setHeader( String name, String value ) {
+      if( isAllowedHeader( name ) ) {
+        super.setHeader( name, value );
+      }
+    }
+
+    public void addHeader( String name, String value ) {
+      if( isAllowedHeader( name ) ) {
+        super.addHeader( name, value );
+      }
+    }
+
+    private boolean isAllowedHeader( String value ) {
+      if( value != null ) {
+        for( String v : restrictedCookies ) {
+          if( value.contains( v ) ) {
+            return false;
+          }
+        }
+      }
+      return true;
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/filter/ShiroSubjectIdentityAdapter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/filter/ShiroSubjectIdentityAdapter.java b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/filter/ShiroSubjectIdentityAdapter.java
new file mode 100644
index 0000000..6fb1340
--- /dev/null
+++ b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/filter/ShiroSubjectIdentityAdapter.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.
+ */
+package org.apache.knox.gateway.filter;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.security.PrivilegedExceptionAction;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.Callable;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+import org.apache.knox.gateway.audit.api.Action;
+import org.apache.knox.gateway.audit.api.ActionOutcome;
+import org.apache.knox.gateway.audit.api.AuditService;
+import org.apache.knox.gateway.audit.api.AuditServiceFactory;
+import org.apache.knox.gateway.audit.api.Auditor;
+import org.apache.knox.gateway.audit.api.ResourceType;
+import org.apache.knox.gateway.audit.log4j.audit.AuditConstants;
+import org.apache.knox.gateway.security.GroupPrincipal;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.apache.shiro.SecurityUtils;
+import org.apache.shiro.subject.Subject;
+
+public class ShiroSubjectIdentityAdapter implements Filter {
+  
+  private static final String SUBJECT_USER_GROUPS = "subject.userGroups";
+  private static AuditService auditService = AuditServiceFactory.getAuditService();
+  private static Auditor auditor = auditService.getAuditor(
+      AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
+      AuditConstants.KNOX_COMPONENT_NAME );
+  
+
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+  }
+
+  public void destroy() {
+  }
+
+  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
+      throws IOException, ServletException {
+    
+    Subject subject = SecurityUtils.getSubject();
+    
+    // trigger call to shiro authorization realm
+    // we use shiro authorization realm to look up groups
+    subject.hasRole("authenticatedUser");
+
+    CallableChain callableChain = new CallableChain(request, response, chain);
+    SecurityUtils.getSubject().execute(callableChain);
+  }
+  
+  private static class CallableChain implements Callable<Void> {
+    private FilterChain chain = null;
+    ServletRequest request = null;
+    ServletResponse response = null;
+    
+    CallableChain(ServletRequest request, ServletResponse response, FilterChain chain) {
+      this.request = request;
+      this.response = response;
+      this.chain = chain;
+    }
+
+    @Override
+    public Void call() throws Exception {
+      PrivilegedExceptionAction<Void> action = new PrivilegedExceptionAction<Void>() {
+        @Override
+        public Void run() throws Exception {
+          chain.doFilter( request, response );
+          return null;
+        }
+      };
+      Subject shiroSubject = SecurityUtils.getSubject();
+
+      if (shiroSubject == null || shiroSubject.getPrincipal() == null) {
+        throw new IllegalStateException("Unable to determine authenticated user from Shiro, please check that your Knox Shiro configuration is correct");
+      }
+
+      final String principal = (String) shiroSubject.getPrincipal().toString();
+      HashSet emptySet = new HashSet();
+      Set<Principal> principals = new HashSet<>();
+      Principal p = new PrimaryPrincipal(principal);
+      principals.add(p);
+      auditService.getContext().setUsername( principal ); //KM: Audit Fix
+      String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
+      auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
+
+      Set<String> userGroups = null;
+      // map ldap groups saved in session to Java Subject GroupPrincipal(s)
+      if (SecurityUtils.getSubject().getSession().getAttribute(SUBJECT_USER_GROUPS) != null) {
+        userGroups = (Set<String>)SecurityUtils.getSubject().getSession().getAttribute(SUBJECT_USER_GROUPS);
+      } else { // KnoxLdapRealm case
+        if(  shiroSubject.getPrincipal() instanceof String ) { 
+           userGroups = new HashSet<>(shiroSubject.getPrincipals().asSet());
+           userGroups.remove(principal);
+        } else { // KnoxPamRealm case
+           Set<Principal> shiroPrincipals = new HashSet<>(shiroSubject.getPrincipals().asSet());
+           userGroups = new HashSet<>(); // Here we are creating a new UserGroup
+                                               // so we don't need to remove a Principal
+                                               // In the case of LDAP the userGroup may have already Principal
+                                               // added to the list of groups, so it is not needed.
+           for( Principal shiroPrincipal: shiroPrincipals ) {
+                userGroups.add(shiroPrincipal.toString() );
+           }
+        }
+      }
+      for (String userGroup : userGroups) {
+        Principal gp = new GroupPrincipal(userGroup);
+        principals.add(gp);
+      }
+      auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS, "Groups: " + userGroups );
+      
+//      The newly constructed Sets check whether this Subject has been set read-only 
+//      before permitting subsequent modifications. The newly created Sets also prevent 
+//      illegal modifications by ensuring that callers have sufficient permissions.
+//
+//      To modify the Principals Set, the caller must have AuthPermission("modifyPrincipals"). 
+//      To modify the public credential Set, the caller must have AuthPermission("modifyPublicCredentials"). 
+//      To modify the private credential Set, the caller must have AuthPermission("modifyPrivateCredentials").
+      javax.security.auth.Subject subject = new javax.security.auth.Subject(true, principals, emptySet, emptySet);
+      javax.security.auth.Subject.doAs( subject, action );
+      
+      return null;
+    }
+    
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxCacheManager.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxCacheManager.java b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxCacheManager.java
new file mode 100644
index 0000000..123d16e
--- /dev/null
+++ b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxCacheManager.java
@@ -0,0 +1,27 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.shirorealm;
+
+import org.apache.shiro.cache.ehcache.EhCacheManager;
+
+public class KnoxCacheManager extends EhCacheManager {
+
+  public KnoxCacheManager() {
+    setCacheManager(net.sf.ehcache.CacheManager.create());
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxLdapContextFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxLdapContextFactory.java b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxLdapContextFactory.java
new file mode 100644
index 0000000..aa28594
--- /dev/null
+++ b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxLdapContextFactory.java
@@ -0,0 +1,125 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT 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.knox.gateway.shirorealm;
+
+import java.util.Hashtable;
+
+import javax.naming.Context;
+import javax.naming.NamingException;
+import javax.naming.ldap.LdapContext;
+
+import org.apache.knox.gateway.GatewayMessages;
+import org.apache.knox.gateway.GatewayServer;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.AliasService;
+import org.apache.knox.gateway.services.security.AliasServiceException;
+import org.apache.shiro.realm.ldap.JndiLdapContextFactory;
+
+/**
+ * An extension of {@link JndiLdapContextFactory} that allows a different authentication mechanism
+ * for system-level authentications (as used by authorization lookups, for example)
+ * compared to regular authentication.
+ * 
+ * <p>
+ * See {@link IsisLdapRealm} for typical configuration within <tt>shiro.ini</tt>.
+ */
+public class KnoxLdapContextFactory extends JndiLdapContextFactory {
+
+    private static GatewayMessages LOG = MessagesFactory.get( GatewayMessages.class );
+  
+    private String systemAuthenticationMechanism = "simple";
+    private String clusterName = "";
+
+    public KnoxLdapContextFactory() {
+      setAuthenticationMechanism("simple");
+    }
+    
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    @Override
+    protected LdapContext createLdapContext(Hashtable env) throws NamingException {
+        if(getSystemUsername() != null && getSystemUsername().equals(env.get(Context.SECURITY_PRINCIPAL))) {
+            env.put(Context.SECURITY_AUTHENTICATION, getSystemAuthenticationMechanism());
+        }
+        return super.createLdapContext(env);
+    }
+
+    public String getSystemAuthenticationMechanism() {
+        return systemAuthenticationMechanism != null? systemAuthenticationMechanism: getAuthenticationMechanism();
+    }
+    
+    public void setSystemAuthenticationMechanism(String systemAuthenticationMechanism) {
+        this.systemAuthenticationMechanism = systemAuthenticationMechanism;
+    }
+    
+    @Override
+    public void setSystemPassword(String systemPass) {
+     
+      if ( systemPass == null ) {
+        return;
+      }
+      
+      systemPass = systemPass.trim();
+      if (systemPass.length() == 0) {
+        return;
+      }
+      
+      if (!systemPass.startsWith("S{ALIAS=")) {
+        super.setSystemPassword( systemPass );
+        return;
+      }
+      
+      systemPass= systemPass.substring( "S{ALIAS=".length(), systemPass.length() - 1 );
+      String aliasName = systemPass;
+      
+      GatewayServices services = GatewayServer.getGatewayServices();
+      AliasService aliasService = (AliasService)services.getService(GatewayServices.ALIAS_SERVICE);
+      
+      String clusterName = getClusterName();
+      //System.err.println("FACTORY systempass 30: " + systemPass);
+      //System.err.println("FACTORY clustername 40: " + clusterName);
+      //System.err.println("FACTORY SystemProperty GatewayHome 50: " + System.getProperty(GatewayConfig.GATEWAY_HOME_VAR));
+      char[] password = null;
+      try {
+        password = aliasService.getPasswordFromAliasForCluster(clusterName, systemPass);
+      } catch (AliasServiceException e) {
+        LOG.unableToGetPassword(e);
+      }
+      //System.err.println("FACTORY password: " + ((password == null) ? "NULL" : new String(password)));
+      if ( password != null ) {
+        //System.err.println("FACTORY SUCCESS 20 system password :" + new String(password));
+        super.setSystemPassword( new String(password) );
+      } else {
+        //System.err.println("FACTORY FORCING system password to blank");
+        super.setSystemPassword("" );
+        LOG.aliasValueNotFound(clusterName, aliasName);
+      }
+    }
+    
+    public String getClusterName() {
+      return clusterName;
+    }
+
+    public void setClusterName(String clusterName) {
+      if (clusterName != null) {
+        this.clusterName = clusterName.trim();
+      }
+    }
+    
+}
\ No newline at end of file


[21/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStreamFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStreamFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStreamFilter.java
new file mode 100644
index 0000000..48e8282
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStreamFilter.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.knox.gateway.filter.rewrite.spi;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+// The rewriter will try to find either a stream or reader createFilter for the mime/type and name.
+public interface UrlRewriteStreamFilter {
+
+  String[] getTypes();
+
+  String[] getNames();
+
+  InputStream filter(
+      InputStream stream,
+      String encoding,
+      UrlRewriter rewriter,
+      Resolver resolver,
+      UrlRewriter.Direction direction,
+      UrlRewriteFilterContentDescriptor config )
+          throws IOException;
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index b17abbb..0000000
--- a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
deleted file mode 100644
index 7a086ca..0000000
--- a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
+++ /dev/null
@@ -1,21 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.filter.rewrite.api.FrontendFunctionDescriptor
-org.apache.hadoop.gateway.filter.rewrite.impl.html.HtmlImportFunctionDescriptor
-org.apache.hadoop.gateway.filter.rewrite.impl.html.HtmlPrefixDescriptor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
deleted file mode 100644
index 158a9f6..0000000
--- a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
+++ /dev/null
@@ -1,22 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptorExt
-org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteCheckDescriptorExt
-org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteControlDescriptorExt
-org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteActionRewriteDescriptorExt

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
deleted file mode 100644
index 23c11a7..0000000
--- a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
+++ /dev/null
@@ -1,21 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.filter.rewrite.impl.FrontendFunctionProcessor
-org.apache.hadoop.gateway.filter.rewrite.impl.html.HtmlImportFunctionProcessor
-org.apache.hadoop.gateway.filter.rewrite.impl.html.HtmlPrefixProcessor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
deleted file mode 100644
index 9c7931d..0000000
--- a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
+++ /dev/null
@@ -1,23 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteRuleProcessorImpl
-org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteMatchProcessorExt
-org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteCheckProcessorExt
-org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteControlProcessorExt
-org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteActionRewriteProcessorExt

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStreamFilter
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStreamFilter b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStreamFilter
deleted file mode 100644
index 06d4eb6..0000000
--- a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStreamFilter
+++ /dev/null
@@ -1,24 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.filter.rewrite.impl.json.JsonUrlRewriteStreamFilter
-org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlUrlRewriteStreamFilter
-org.apache.hadoop.gateway.filter.rewrite.impl.html.HtmlUrlRewriteStreamFilter
-org.apache.hadoop.gateway.filter.rewrite.impl.form.FormUrlRewriteStreamFilter
-org.apache.hadoop.gateway.filter.rewrite.impl.noop.NoOpUrlRewriteStreamFilter
-org.apache.hadoop.gateway.filter.rewrite.impl.javascript.JavaScriptUrlRewriteStreamFilter
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..dd88d81
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
new file mode 100644
index 0000000..3b67183
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
@@ -0,0 +1,21 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.filter.rewrite.api.FrontendFunctionDescriptor
+org.apache.knox.gateway.filter.rewrite.impl.html.HtmlImportFunctionDescriptor
+org.apache.knox.gateway.filter.rewrite.impl.html.HtmlPrefixDescriptor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
new file mode 100644
index 0000000..be275cc
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
@@ -0,0 +1,22 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptorExt
+org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteCheckDescriptorExt
+org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteControlDescriptorExt
+org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteActionRewriteDescriptorExt

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
new file mode 100644
index 0000000..099f40d
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
@@ -0,0 +1,21 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.filter.rewrite.impl.FrontendFunctionProcessor
+org.apache.knox.gateway.filter.rewrite.impl.html.HtmlImportFunctionProcessor
+org.apache.knox.gateway.filter.rewrite.impl.html.HtmlPrefixProcessor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
new file mode 100644
index 0000000..fb26555
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
@@ -0,0 +1,23 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteRuleProcessorImpl
+org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteMatchProcessorExt
+org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteCheckProcessorExt
+org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteControlProcessorExt
+org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteActionRewriteProcessorExt

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStreamFilter
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStreamFilter b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStreamFilter
new file mode 100644
index 0000000..0d347e1
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStreamFilter
@@ -0,0 +1,24 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.filter.rewrite.impl.json.JsonUrlRewriteStreamFilter
+org.apache.knox.gateway.filter.rewrite.impl.xml.XmlUrlRewriteStreamFilter
+org.apache.knox.gateway.filter.rewrite.impl.html.HtmlUrlRewriteStreamFilter
+org.apache.knox.gateway.filter.rewrite.impl.form.FormUrlRewriteStreamFilter
+org.apache.knox.gateway.filter.rewrite.impl.noop.NoOpUrlRewriteStreamFilter
+org.apache.knox.gateway.filter.rewrite.impl.javascript.JavaScriptUrlRewriteStreamFilter
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/FrontendFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/FrontendFunctionDescriptorTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/FrontendFunctionDescriptorTest.java
deleted file mode 100644
index dfb439e..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/FrontendFunctionDescriptorTest.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.hadoop.gateway.filter.rewrite.api;
-
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.fail;
-
-public class FrontendFunctionDescriptorTest {
-
-  @SuppressWarnings("rawtypes")
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof FrontendFunctionDescriptor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + FrontendFunctionDescriptor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    FrontendFunctionDescriptor descriptor = new FrontendFunctionDescriptor();
-    assertThat( descriptor.name(), is( "frontend" ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest.java
deleted file mode 100644
index 410f60b..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest.java
+++ /dev/null
@@ -1,412 +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.hadoop.gateway.filter.rewrite.api;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.hadoop.gateway.util.urltemplate.Expander;
-import org.apache.hadoop.gateway.util.urltemplate.Matcher;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-public class UrlRewriteProcessorTest {
-
-  private static URL getTestResourceUrl( String name ) throws FileNotFoundException {
-    name = UrlRewriteProcessorTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
-    URL url = ClassLoader.getSystemResource( name );
-    if( url == null ) {
-      throw new FileNotFoundException( name );
-    }
-    return url;
-  }
-
-  private static InputStream getTestResourceStream( String name ) throws IOException {
-    URL url = getTestResourceUrl( name );
-    InputStream stream = url.openStream();
-    return stream;
-  }
-
-  private static Reader getTestResourceReader( String name, String charset ) throws IOException {
-    return new InputStreamReader( getTestResourceStream( name ), charset );
-  }
-
-  @Test
-  public void testBasicPathRewrite() throws IOException, URISyntaxException {
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
-    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
-    EasyMock.replay( environment, request, response );
-
-    UrlRewriteProcessor processor = new UrlRewriteProcessor();
-    UrlRewriteRulesDescriptor config = UrlRewriteRulesDescriptorFactory.load(
-        "xml", getTestResourceReader( "rewrite.xml", "UTF-8" ) );
-    processor.initialize( environment, config );
-
-    Template inputUrl = Parser.parseLiteral( "test-scheme://test-host:1/test-input-path" );
-    Template outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.IN, null );
-
-    assertThat( "Expect rewrite to produce a new URL",
-        outputUrl, notNullValue() );
-    assertThat(
-        "Expect rewrite to contain the correct path.",
-        outputUrl.toString(), is( "test-scheme://test-host:1/test-output-path" ) );
-    processor.destroy();
-  }
-
-  @Test
-  public void testMultipleIdenticalRewriteOutputRules() throws IOException, URISyntaxException {
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
-    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
-    EasyMock.replay( environment, request, response );
-
-    UrlRewriteProcessor processor = new UrlRewriteProcessor();
-    UrlRewriteRulesDescriptor config = UrlRewriteRulesDescriptorFactory.load(
-        "xml", getTestResourceReader( "rewrite-with-same-rules.xml", "UTF-8" ) );
-    processor.initialize( environment, config );
-
-    Template inputUrl = Parser.parseLiteral( "scheme://input-mock-host:42/test-input-path" );
-    Template outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, null );
-
-    assertThat( "Expect rewrite to produce a new URL",
-        outputUrl, notNullValue() );
-    // Should always pick the first one.
-    assertThat(
-        "Expect rewrite to contain the correct path.",
-        outputUrl.toString(), is( "output-mock-scheme-1://output-mock-host-1:42/test-input-path" ) );
-
-    inputUrl = Parser.parseLiteral( "mock-scheme://input-mock-host:42/no-query" );
-    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, null );
-
-    assertThat(
-        "Expect rewrite to contain the correct path.",
-        outputUrl.toString(), is( "mock-scheme://output-mock-host-3:42/no-query" ) );
-
-    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, "test-rule-4" );
-
-    assertThat(
-        "Expect rewrite to contain the correct path.",
-        outputUrl.toString(), is( "mock-scheme://output-mock-host-4:42/no-query" ) );
-
-    processor.destroy();
-  }
-
-  @Test
-  public void testIdenticalRewriteOutputRulesWithScopes() throws IOException, URISyntaxException {
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
-    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
-    ArrayList<String> roles = new ArrayList<>();
-    roles.add("service-1");
-    EasyMock.expect(environment.resolve("service.role")).andReturn(roles).anyTimes();
-    EasyMock.replay( environment, request, response );
-
-    UrlRewriteProcessor processor = new UrlRewriteProcessor();
-    UrlRewriteRulesDescriptor config = UrlRewriteRulesDescriptorFactory.load(
-        "xml", getTestResourceReader( "rewrite-with-same-rules-different-scope.xml", "UTF-8" ) );
-    processor.initialize( environment, config );
-
-    Template inputUrl = Parser.parseLiteral( "scheme://input-mock-host:42/test-input-path" );
-    Template outputUrl = processor.rewrite( environment, inputUrl, UrlRewriter.Direction.OUT, null );
-
-    assertThat( "Expect rewrite to produce a new URL",
-        outputUrl, notNullValue() );
-    assertThat(
-        "Expect rewrite to contain the correct path.",
-        outputUrl.toString(), is( "output-mock-scheme-2://output-mock-host-2:42/test-input-path" ) );
-
-    inputUrl = Parser.parseLiteral( "mock-scheme://input-mock-host:42/no-query" );
-    outputUrl = processor.rewrite( environment, inputUrl, UrlRewriter.Direction.OUT, null );
-
-    roles.remove(0);
-    roles.add("service-2");
-
-    assertThat(
-        "Expect rewrite to contain the correct path.",
-        outputUrl.toString(), is( "mock-scheme://output-mock-host-5:42/no-query" ) );
-
-    outputUrl = processor.rewrite( environment, inputUrl, UrlRewriter.Direction.OUT, "service-2/test-rule-4" );
-
-    //no scope information should pick the first one
-    assertThat(
-        "Expect rewrite to contain the correct path.",
-        outputUrl.toString(), is( "mock-scheme://output-mock-host-4:42/no-query" ) );
-
-    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, "service-2/test-rule-4" );
-
-    assertThat(
-        "Expect rewrite to contain the correct path.",
-        outputUrl.toString(), is( "mock-scheme://output-mock-host-4:42/no-query" ) );
-
-    //Test the IN direction
-    inputUrl = Parser.parseLiteral( "scheme://input-mock-host:42/test-input-path" );
-    outputUrl = processor.rewrite( environment, inputUrl, UrlRewriter.Direction.IN, null );
-
-    assertThat( "Expect rewrite to produce a new URL",
-        outputUrl, notNullValue() );
-    assertThat(
-        "Expect rewrite to contain the correct path.",
-        outputUrl.toString(), is( "input-mock-scheme-2://input-mock-host-2:42/test-input-path" ) );
-
-    processor.destroy();
-  }
-
-  @Test
-  public void testRewriteViaRuleNameWithAmbiguousRules() throws IOException, URISyntaxException {
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
-    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
-    EasyMock.replay( environment, request, response );
-
-    UrlRewriteProcessor processor = new UrlRewriteProcessor();
-    UrlRewriteRulesDescriptor config = UrlRewriteRulesDescriptorFactory.load(
-        "xml", getTestResourceReader( "rewrite-with-same-rules.xml", "UTF-8" ) );
-    processor.initialize( environment, config );
-
-    Template inputUrl = Parser.parseLiteral( "input-mock-scheme-1://input-mock-host-1:42/test-input-path" );
-    Template outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, "test-rule-2" );
-
-    assertThat( "Expect rewrite to produce a new URL",
-        outputUrl, notNullValue() );
-    assertThat(
-        "Expect rewrite to contain the correct path.",
-        outputUrl.toString(), is( "output-mock-scheme-2://output-mock-host-2:42/test-input-path" ) );
-
-    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, "test-rule-1" );
-
-    assertThat( "Expect rewrite to produce a new URL",
-        outputUrl, notNullValue() );
-    assertThat(
-        "Expect rewrite to contain the correct path.",
-        outputUrl.toString(), is( "output-mock-scheme-1://output-mock-host-1:42/test-input-path" ) );
-
-    processor.destroy();
-  }
-
-  @Test
-  public void testRewriteViaRuleWithComplexFlow() throws Exception {
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
-    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
-    EasyMock.replay( environment, request, response );
-
-    UrlRewriteProcessor processor = new UrlRewriteProcessor();
-    UrlRewriteRulesDescriptor config = UrlRewriteRulesDescriptorFactory.load(
-        "xml", getTestResourceReader( "rewrite.xml", "UTF-8" ) );
-    processor.initialize( environment, config );
-
-    Template inputUrl;
-    Template outputUrl;
-
-    inputUrl = Parser.parseLiteral( "test-scheme://test-host:777/test-path" );
-    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.IN, "test-rule-with-complex-flow" );
-    assertThat(
-        "Expect rewrite to contain the correct path.",
-        outputUrl.toString(), is( "test-scheme-output://test-host-output:42/test-path-output/test-path" ) );
-
-    inputUrl = Parser.parseLiteral( "test-scheme://test-host:42/~/test-path" );
-    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.IN, "test-rule-with-complex-flow" );
-    assertThat(
-        "Expect rewrite to contain the correct path.",
-        outputUrl.toString(), is( "test-scheme-output://test-host-output:777/test-path-output/test-home/test-path" ) );
-
-    processor.destroy();
-  }
-
-  @Test
-  public void testRewriteViaRuleWithWildcardTemplateAndOptionalQuery() throws Exception {
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
-    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
-    EasyMock.replay( environment, request, response );
-
-    UrlRewriteProcessor processor = new UrlRewriteProcessor();
-    UrlRewriteRulesDescriptor config = UrlRewriteRulesDescriptorFactory.load(
-        "xml", getTestResourceReader( "rewrite.xml", "UTF-8" ) );
-    processor.initialize( environment, config );
-
-    Template inputUrl;
-    Template outputUrl;
-
-    inputUrl = Parser.parseLiteral( "test-scheme-input://test-host-input:42/test-path-input-one/test-path-input-two?test-query-name=test-query-value" );
-    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, "test-rule-2" );
-
-    assertThat(
-        "Expect rewrite to contain the correct path and query.",
-        outputUrl.toString(), is( "test-scheme-output://test-host-output:777/test-path-output/test-path-input-one/test-path-input-two?test-query-name=test-query-value" ) );
-
-    inputUrl = Parser.parseLiteral( "test-scheme-input://test-host-input:42/test-path-input-one/test-path-input-two" );
-    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, "test-rule-2" );
-
-    assertThat(
-        "Expect rewrite to contain the correct path.",
-        outputUrl.toString(), is( "test-scheme-output://test-host-output:777/test-path-output/test-path-input-one/test-path-input-two" ) );
-
-    processor.destroy();
-  }
-
-  /**
-   * Tests the rewrite pattern used for re-writing Solr urls passed through Knox.
-   * 
-   * @throws Exception
-   */
-  @Test
-  public void testSolrRewrite() throws Exception {
-    URI inputUri, outputUri;
-    Matcher<Void> matcher;
-    Matcher<Void>.Match match;
-    Template input, pattern, template;
-
-    inputUri = new URI(
-        "https://hortonworks.sandbox.hdp.24.test:8443/gateway/sandbox/solr/TestCollection/select?q=*.*&wt=json&indent=true");
-
-    input = Parser.parseLiteral(inputUri.toString());
-    pattern = Parser.parseTemplate("*://*:*/**/solr/{collection=**}/{query=**}?{**}");
-    template = Parser.parseTemplate("http://sandbox.hortonworks.com/solr/{collection=**}/{query=**}?{**}");
-
-    matcher = new Matcher<Void>();
-    matcher.add(pattern, null);
-    match = matcher.match(input);
-
-    outputUri = Expander.expand(template, match.getParams(), null);
-
-    final String reWrittenScheme = outputUri.getScheme();
-    assertEquals("http", reWrittenScheme);
-
-    final String reWrittenHost = outputUri.getHost();
-    assertEquals("sandbox.hortonworks.com", reWrittenHost);
-
-    final String reWrittenPath = outputUri.getPath();
-    assertEquals("/solr/TestCollection/select", reWrittenPath);
-
-    // Whole thing is (non-deterministicly ordered around the &s):
-    // "q=*.*&wt=json&indent=true"
-    final String reWrittenQuery = outputUri.getQuery();
-
-    // Check individual parameters are present, and have the right value.
-    final Map<String, String> reWrittenParams = mapUrlParameters(reWrittenQuery);
-    assertTrue(reWrittenParams.containsKey("q"));
-    assertEquals("*.*", reWrittenParams.get("q"));
-    assertTrue(reWrittenParams.containsKey("wt"));
-    assertEquals("json", reWrittenParams.get("wt"));
-    assertEquals("true", reWrittenParams.get("indent"));
-  }
-
-
-  @Test
-  public void testSolrRewriteDefaultPort() throws Exception {
-    URI inputUri, outputUri;
-    Matcher<Void> matcher;
-    Matcher<Void>.Match match;
-    Template input, pattern, template;
-
-    inputUri = new URI(
-                "https://hortonworks.sandbox.hdp.24.test/gateway/sandbox/solr/TestCollection/select?q=*.*&wt=json&indent=true");
-
-    input = Parser.parseLiteral(inputUri.toString());
-    pattern = Parser.parseTemplate("*://*:*/**/solr/{collection=**}/{query=**}?{**}");
-    template = Parser.parseTemplate("http://sandbox.hortonworks.com/solr/{collection=**}/{query=**}?{**}");
-
-    matcher = new Matcher<Void>();
-    matcher.add(pattern, null);
-    match = matcher.match(input);
-
-    outputUri = Expander.expand(template, match.getParams(), null);
-
-    final String reWrittenScheme = outputUri.getScheme();
-    assertEquals("http", reWrittenScheme);
-
-    final String reWrittenHost = outputUri.getHost();
-    assertEquals("sandbox.hortonworks.com", reWrittenHost);
-
-    final String reWrittenPath = outputUri.getPath();
-    assertEquals("/solr/TestCollection/select", reWrittenPath);
-
-    // Whole thing is (non-deterministicly ordered around the &s):
-    // "q=*.*&wt=json&indent=true"
-    final String reWrittenQuery = outputUri.getQuery();
-
-    // Check individual parameters are present, and have the right value.
-    final Map<String, String> reWrittenParams = mapUrlParameters(reWrittenQuery);
-    assertTrue(reWrittenParams.containsKey("q"));
-    assertEquals("*.*", reWrittenParams.get("q"));
-    assertTrue(reWrittenParams.containsKey("wt"));
-    assertEquals("json", reWrittenParams.get("wt"));
-    assertEquals("true", reWrittenParams.get("indent"));
-  }
-
-
-  /**
-   * Turn a string containing URL parameters, e.g.
-   * 
-   * <pre>
-   * a=b&c=d&e=f
-   * </pre>
-   * 
-   * into a map such as
-   * <table>
-   * <tr>
-   * <th>Key</th>
-   * <th>Value</th>
-   * </tr>
-   * <tr>
-   * <td>a</td>
-   * <td>b</td>
-   * </tr>
-   * <tr>
-   * <td>c</td>
-   * <td>d</td>
-   * </tr>
-   * </table>
-   * 
-   * @param urlParameters the URL parameter string. Expected to contain something of the form
-   *        "a=b&c=d" etc (i.e. Key=Value separated by &).
-   * @return a map, with the key-values pairs representing the URL parameters.
-   */
-  private Map<String, String> mapUrlParameters(String urlParameters) {
-    final Map<String, String> map = new HashMap<>();
-    for (String pair : urlParameters.split("&")) {
-      String[] kv = pair.split("=");
-      map.put(kv[0], kv[1]);
-    }
-    return map;
-  }
-
-  
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest.java
deleted file mode 100644
index fe3f71e..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest.java
+++ /dev/null
@@ -1,253 +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.hadoop.gateway.filter.rewrite.api;
-
-import org.apache.log4j.Level;
-import org.apache.log4j.Logger;
-import org.hamcrest.Matchers;
-import org.junit.Test;
-import org.xmlmatchers.transform.XmlConverters;
-
-import javax.xml.transform.Source;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.io.StringWriter;
-import java.net.URL;
-import java.util.List;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
-import static org.xmlmatchers.XmlMatchers.hasXPath;
-
-public class UrlRewriteRulesDescriptorFactoryTest {
-
-  @Test
-  public void testCreate() throws Exception {
-    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
-    assertThat( descriptor, notNullValue() );
-    assertThat( descriptor.getRules(), notNullValue() );
-    assertThat( descriptor.getRules().isEmpty(), is( true ) );
-
-    UrlRewriteRuleDescriptor rule = descriptor.newRule();
-    assertThat( rule, notNullValue() );
-    assertThat( descriptor.getRules().isEmpty(), is( true ) );
-    rule.name( "first" );
-    descriptor.addRule( rule );
-    assertThat( descriptor.getRules().size(), is( 1 ) );
-    assertThat( descriptor.getRule( "first" ), sameInstance( rule ) );
-
-    rule = descriptor.addRule( "second" );
-    assertThat( descriptor.getRules().size(), is( 2 ) );
-  }
-
-  private static URL getTestResourceUrl( String name ) throws FileNotFoundException {
-    name = UrlRewriteRulesDescriptorFactoryTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
-    URL url = ClassLoader.getSystemResource( name );
-    if( url == null ) {
-      throw new FileNotFoundException( name );
-    }
-    return url;
-  }
-
-  private static InputStream getTestResourceStream( String name ) throws IOException {
-    URL url = getTestResourceUrl( name );
-    InputStream stream = url.openStream();
-    return stream;
-  }
-
-  private static Reader getTestResourceReader( String name, String charset ) throws IOException {
-    return new InputStreamReader( getTestResourceStream( name ), charset );
-  }
-
-  @Test
-  public void testLoadMissingFile() throws IOException {
-    try {
-      UrlRewriteRulesDescriptorFactory.load( "xml", getTestResourceReader( "missing.xml", "UTF-8" ) );
-      fail( "Should have thrown a FileNotFoundException." );
-    } catch ( FileNotFoundException e ) {
-      assertThat( e.getMessage(), containsString( "missing.xml" ) );
-    }
-  }
-
-  @Test
-  public void testLoadEmptyFile() throws IOException {
-    Logger logger = org.apache.log4j.LogManager.getLogger( "org.apache.commons.digester3.Digester" );
-    Level level = logger.getLevel();
-    try {
-      logger.setLevel( org.apache.log4j.Level.OFF );
-      UrlRewriteRulesDescriptorFactory.load( "xml", getTestResourceReader( "empty.xml", "UTF-8" ) );
-      fail( "Should have thrown an IOException." );
-    } catch ( IOException e ) {
-      // Expected.
-    } catch ( Throwable t ) {
-      fail( "Should have thrown an IOException." );
-    } finally {
-      logger.setLevel( level );
-    }
-  }
-
-  @Test
-  public void testLoadInvalidFile() throws IOException {
-    Logger logger = org.apache.log4j.LogManager.getLogger( "org.apache.commons.digester3.Digester" );
-    Level level = logger.getLevel();
-    try {
-      logger.setLevel( org.apache.log4j.Level.OFF );
-      UrlRewriteRulesDescriptorFactory.load( "xml", getTestResourceReader( "invalid.xml", "UTF-8" ) );
-      fail( "Should have thrown an IOException." );
-    } catch ( IOException e ) {
-      // Expected.
-    } catch ( Throwable t ) {
-      fail( "Should have thrown an IOException." );
-    } finally {
-      logger.setLevel( level );
-    }
-  }
-
-  @Test
-  public void testLoadNoopFile() throws IOException {
-    UrlRewriteRulesDescriptor config =
-        UrlRewriteRulesDescriptorFactory.load( "xml", getTestResourceReader( "noop.xml", "UTF-8" ) );
-    assertThat( "Rules should be an empty list.", config.getRules().isEmpty(), Matchers.is( true ) );
-  }
-
-  @Test
-  public void testLoadSimpleFile() throws IOException {
-    UrlRewriteRulesDescriptor config =
-        UrlRewriteRulesDescriptorFactory.load( "xml", getTestResourceReader( "simple.xml", "UTF-8" ) );
-    assertThat( "Failed to load simple config file.", config, notNullValue() );
-  }
-
-  @Test
-  public void testLoadSimpleFilterFile() throws IOException {
-    UrlRewriteRulesDescriptor config =
-        UrlRewriteRulesDescriptorFactory.load( "xml", getTestResourceReader( "filter-simple.xml", "UTF-8" ) );
-    List<UrlRewriteFilterDescriptor> filters = config.getFilters();
-    assertThat( filters.size(), is( 1 ) );
-    UrlRewriteFilterDescriptor filter = config.getFilter( "test-filter-1" );
-    assertThat( filter, notNullValue() );
-    assertThat( config.getFilters().get(0), sameInstance( filter ) );
-  }
-
-  @Test
-  public void testLoadStoreCompleteFilterFile() throws IOException {
-    UrlRewriteRulesDescriptor config =
-        UrlRewriteRulesDescriptorFactory.load( "xml", getTestResourceReader( "filter-complete.xml", "UTF-8" ) );
-
-    List<UrlRewriteFilterDescriptor> filters = config.getFilters();
-    assertThat( filters.size(), is( 1 ) );
-
-    UrlRewriteFilterDescriptor filter = config.getFilter( "test-filter-name-1" );
-    assertThat( filter, notNullValue() );
-    assertThat( config.getFilters().get(0), sameInstance( filter ) );
-    assertThat( filter.name(), is( "test-filter-name-1" ) );
-
-    UrlRewriteFilterContentDescriptor content = filter.getContent( "test-content-type-1/test-content-subtype-1" );
-    assertThat( content, notNullValue() );
-    assertThat( content.type(), is( "test-content-type-1/test-content-subtype-1" ) );
-
-    List<UrlRewriteFilterPathDescriptor> selectors = content.getSelectors();
-    assertThat( selectors, notNullValue() );
-    assertThat( selectors.size(), is( 3 ) );
-
-    UrlRewriteFilterApplyDescriptor apply = (UrlRewriteFilterApplyDescriptor)selectors.get( 0 );
-    assertThat( apply, notNullValue() );
-    assertThat( apply.path(), is( "test-apply-path-1" ) );
-    assertThat( apply.rule(), is( "test-apply-rule-1" ) );
-    assertThat( apply.compiledPath(), nullValue() );
-
-    UrlRewriteFilterScopeDescriptor scope = (UrlRewriteFilterScopeDescriptor)selectors.get( 1 );
-    assertThat( scope, notNullValue() );
-    assertThat( scope.path(), is( "test-scope-path-1" ) );
-    assertThat( scope.compiledPath(), nullValue() );
-    List<UrlRewriteFilterPathDescriptor> scopeSelectors = scope.getSelectors();
-    assertThat( scopeSelectors, notNullValue() );
-    assertThat( scopeSelectors.size(), is( 1 ) );
-    UrlRewriteFilterApplyDescriptor scopeApply = (UrlRewriteFilterApplyDescriptor)scopeSelectors.get( 0 );
-    assertThat( scopeApply, notNullValue() );
-    assertThat( scopeApply.path(), is( "test-apply-path-2" ) );
-    assertThat( scopeApply.compiledPath(), nullValue() );
-    assertThat( scopeApply.rule(), is( "test-apply-rule-2" ) );
-
-    UrlRewriteFilterBufferDescriptor buffer = (UrlRewriteFilterBufferDescriptor)selectors.get( 2 );
-    assertThat( buffer, notNullValue() );
-    assertThat( buffer.path(), is( "test-buffer-path-1" ) );
-    assertThat( buffer.compiledPath(), nullValue() );
-    List<UrlRewriteFilterPathDescriptor> bufferSelectors = buffer.getSelectors();
-    assertThat( bufferSelectors, notNullValue() );
-    assertThat( bufferSelectors.size(), is( 2 ) );
-    UrlRewriteFilterApplyDescriptor bufferApply = (UrlRewriteFilterApplyDescriptor)bufferSelectors.get( 0 );
-    assertThat( bufferApply, notNullValue() );
-    assertThat( bufferApply.path(), is( "test-apply-path-3" ) );
-    assertThat( bufferApply.compiledPath(), nullValue() );
-    assertThat( bufferApply.rule(), is( "test-apply-rule-3" ) );
-    UrlRewriteFilterDetectDescriptor bufferDetect = (UrlRewriteFilterDetectDescriptor)bufferSelectors.get( 1 );
-    assertThat( bufferDetect, notNullValue() );
-    assertThat( bufferDetect.value(), is( "test-detect-value-1" ) );
-    assertThat( bufferDetect.compiledValue(), nullValue() );
-    List<UrlRewriteFilterPathDescriptor> detectSelectors = bufferDetect.getSelectors();
-    assertThat( detectSelectors, notNullValue() );
-    assertThat( detectSelectors.size(), is( 1 ) );
-    UrlRewriteFilterApplyDescriptor detectApply = (UrlRewriteFilterApplyDescriptor)detectSelectors.get( 0 );
-    assertThat( detectApply, notNullValue() );
-    assertThat( detectApply.path(), is( "test-apply-path-4" ) );
-    assertThat( detectApply.compiledPath(), nullValue() );
-    assertThat( detectApply.rule(), is( "test-apply-rule-4" ) );
-
-    StringWriter writer = new StringWriter();
-    UrlRewriteRulesDescriptorFactory.store( config, "xml", writer );
-    Source xml = XmlConverters.the( writer.toString() );
-
-    assertThat( xml, notNullValue() );
-    assertThat( xml, hasXPath( "/" ) );
-    assertThat( xml, hasXPath( "/rules" ) );
-    assertThat( xml, hasXPath( "/rules/filter" ) );
-    assertThat( xml, hasXPath( "/rules/filter/@name", equalTo( "test-filter-name-1" ) ) );
-    assertThat( xml, hasXPath( "/rules/filter/content" ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/@type", equalTo( "test-content-type-1/test-content-subtype-1" ) ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/apply" ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/apply/@path", equalTo( "test-apply-path-1" ) ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/apply/@rule", equalTo( "test-apply-rule-1" ) ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/scope" ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/scope/@path", equalTo( "test-scope-path-1" ) ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/scope/apply" ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/scope/apply/@path", equalTo( "test-apply-path-2" ) ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/scope/apply/@rule", equalTo( "test-apply-rule-2" ) ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/buffer" ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/buffer/@path", equalTo( "test-buffer-path-1" ) ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/buffer/apply" ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/buffer/apply/@path", equalTo( "test-apply-path-3" ) ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/buffer/apply/@rule", equalTo( "test-apply-rule-3" ) ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/buffer/detect" ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/buffer/detect/@path", equalTo( "test-detect-path-1" ) ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/buffer/detect/@value", equalTo( "test-detect-value-1" ) ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/buffer/detect/apply" ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/buffer/detect/apply/@path", equalTo( "test-apply-path-4" ) ) );
-    assertThat( xml, hasXPath( "/rules/filter/content/buffer/detect/apply/@rule", equalTo( "test-apply-rule-4" ) ) );
-
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest.java
deleted file mode 100644
index a7b8481..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest.java
+++ /dev/null
@@ -1,91 +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.hadoop.gateway.filter.rewrite.api;
-
-import org.apache.hadoop.test.mock.MockInteraction;
-import org.apache.hadoop.test.mock.MockServlet;
-import org.eclipse.jetty.servlet.FilterHolder;
-import org.eclipse.jetty.servlet.ServletHolder;
-import org.eclipse.jetty.http.HttpTester;
-import org.eclipse.jetty.servlet.ServletTester;
-import org.eclipse.jetty.util.ArrayQueue;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-
-import javax.servlet.DispatcherType;
-import java.net.URL;
-import java.util.EnumSet;
-
-import static org.junit.Assert.fail;
-
-public class UrlRewriteServletContextListenerTest {
-
-  private ServletTester server;
-  private HttpTester.Request request;
-  private HttpTester.Response response;
-  private ArrayQueue<MockInteraction> interactions;
-  private MockInteraction interaction;
-
-  private static URL getTestResource( String name ) {
-    name = UrlRewriteServletFilterTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
-    URL url = ClassLoader.getSystemResource( name );
-    return url;
-  }
-
-  @Before
-  public void setUp() throws Exception {
-    String descriptorUrl = getTestResource( "rewrite.xml" ).toExternalForm();
-
-    server = new ServletTester();
-    server.setContextPath( "/" );
-    server.getContext().addEventListener( new UrlRewriteServletContextListener() );
-    server.getContext().setInitParameter(
-        UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );
-
-    FilterHolder filter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
-    filter.setFilter( new UrlRewriteServletFilter() );
-
-    interactions = new ArrayQueue<MockInteraction>();
-
-    ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
-    servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );
-    servlet.setInitParameter(
-        UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME,
-        getTestResource( "rewrite.xml" ).toExternalForm() );
-
-    server.start();
-
-    interaction = new MockInteraction();
-    request = HttpTester.newRequest();
-    response = null;
-  }
-
-  @After
-  public void tearDown() throws Exception {
-    server.stop();
-  }
-
-//  @Test
-//  @Ignore("TODO")
-//  public void testProvider() throws Exception {
-//    fail( "TODO" );
-//  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletEnvironmentTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletEnvironmentTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletEnvironmentTest.java
deleted file mode 100644
index 4900805..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletEnvironmentTest.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.hadoop.gateway.filter.rewrite.api;
-
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-import javax.servlet.ServletContext;
-
-import java.net.URL;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
-
-public class UrlRewriteServletEnvironmentTest {
-
-  @Test
-  public void testGetResource() throws Exception {
-    ServletContext context = EasyMock.createNiceMock( ServletContext.class );
-    EasyMock.expect( context.getResource( "test-resource-name" ) ).andReturn( new URL( "http:/test-resource-value" ) ).anyTimes();
-    EasyMock.replay( context );
-    UrlRewriteServletEnvironment env = new UrlRewriteServletEnvironment( context );
-    assertThat( env.getResource( "test-resource-name" ), is( new URL( "http:/test-resource-value" ) ) );
-  }
-
-  @Test
-  public void testGetAttribute() throws Exception {
-    ServletContext context = EasyMock.createNiceMock( ServletContext.class );
-    EasyMock.expect(  context.getAttribute( "test-attribute-name" ) ).andReturn( "test-attribute-value" ).anyTimes();
-    EasyMock.replay( context );
-    UrlRewriteServletEnvironment env = new UrlRewriteServletEnvironment( context );
-    assertThat( (String)env.getAttribute( "test-attribute-name" ), is( "test-attribute-value" ) );
-  }
-
-  @Test
-  public void testResolve() throws Exception {
-    ServletContext context = EasyMock.createNiceMock( ServletContext.class );
-    EasyMock.expect( context.getInitParameter( "test-parameter-name" ) ).andReturn( "test-parameter-value" );
-    EasyMock.replay( context );
-    UrlRewriteServletEnvironment env = new UrlRewriteServletEnvironment( context );
-    assertThat( env.resolve( "test-parameter-name" ), contains( "test-parameter-value" ) );
-  }
-
-}


[29/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessor.java
deleted file mode 100644
index be1eca5..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessor.java
+++ /dev/null
@@ -1,125 +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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.FrontendFunctionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteResources;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteResolver;
-import org.apache.hadoop.gateway.i18n.resources.ResourcesFactory;
-import org.apache.hadoop.gateway.services.GatewayServices;
-
-import java.net.URI;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class FrontendFunctionProcessor implements UrlRewriteFunctionProcessor<FrontendFunctionDescriptor> {
-
-  private static UrlRewriteResources RES = ResourcesFactory.get( UrlRewriteResources.class );
-
-  private Map<String,UrlRewriteResolver> resolvers;
-
-  @Override
-  public String name() {
-    return FrontendFunctionDescriptor.FUNCTION_NAME;
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, FrontendFunctionDescriptor descriptor ) throws Exception {
-    if( environment == null ) {
-      throw new IllegalArgumentException( "environment==null" );
-    }
-    URI frontend = environment.getAttribute( FrontendFunctionDescriptor.FRONTEND_URI_ATTRIBUTE );
-    resolvers = new HashMap<>();
-    if( frontend == null ) {
-      resolvers.put( "url", new ParamResolver( "gateway.url" ) );
-      resolvers.put( "addr", new ParamResolver( "gateway.addr" ) );
-      resolvers.put( "scheme", new ParamResolver( "gateway.scheme" ) );
-      resolvers.put( "host", new ParamResolver( "gateway.host" ) );
-      resolvers.put( "port", new ParamResolver( "gateway.port" ) );
-      resolvers.put( "path", new ParamResolver( "gateway.path" ) );
-    } else {
-      resolvers.put( "url", new FixedResolver( frontend.toString() ) );
-      resolvers.put( "addr", new FixedResolver( frontend.getHost() + ":" + frontend.getPort() ) );
-      resolvers.put( "scheme", new FixedResolver( frontend.getScheme() ) );
-      resolvers.put( "host", new FixedResolver( frontend.getHost() ) );
-      resolvers.put( "port", new FixedResolver( Integer.toString( frontend.getPort() ) ) );
-      resolvers.put( "path", new FixedResolver( frontend.getPath() ) );
-    }
-    resolvers.put( "topology", new FixedResolver( (String)environment.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE) ) );
-    resolvers.put( "address", resolvers.get( "addr" ) );
-  }
-
-  @Override
-  public void destroy() throws Exception {
-    resolvers.clear();
-  }
-
-  @Override
-  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
-    String parameter = "url";
-    if( parameters != null && parameters.size() > 0 ) {
-      String first = parameters.get( 0 );
-      if( first != null ) {
-        parameter = first;
-      }
-    }
-    parameter = parameter.trim().toLowerCase();
-    UrlRewriteResolver resolver = resolvers.get( parameter );
-    if( resolver == null ) {
-      throw new IllegalArgumentException( RES.invalidFrontendFunctionParameter( parameter ) );
-    }
-    List<String> results = resolver.resolve( context, parameters );
-    return results;
-  }
-
-  private static class ParamResolver implements UrlRewriteResolver {
-
-    private String paramName;
-
-    private ParamResolver( String paramName ) {
-      this.paramName = paramName;
-    }
-
-    @Override
-    public List<String> resolve( UrlRewriteContext context, List<String> parameter ) throws Exception {
-      return context.getParameters().resolve( paramName );
-    }
-
-  }
-
-  private static class FixedResolver implements UrlRewriteResolver {
-
-    private List<String> fixedValues;
-
-    private FixedResolver( String... fixedValues ) {
-      this.fixedValues = Arrays.asList( fixedValues );
-    }
-
-    @Override
-    public List<String> resolve( UrlRewriteContext context, List<String> parameter ) throws Exception {
-      return fixedValues;
-    }
-
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteContextImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteContextImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteContextImpl.java
deleted file mode 100644
index 4a153d0..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteContextImpl.java
+++ /dev/null
@@ -1,152 +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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.util.urltemplate.Evaluator;
-import org.apache.hadoop.gateway.util.urltemplate.Params;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-public class UrlRewriteContextImpl implements UrlRewriteContext {
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-
-  private UrlRewriteEnvironment environment;
-  private Resolver resolver;
-  private Evaluator evaluator;
-  private Map<String,UrlRewriteFunctionProcessor> functions;
-  private ContextParameters params;
-  private UrlRewriter.Direction direction;
-  private Template originalUrl;
-  private Template currentUrl;
-
-  public UrlRewriteContextImpl(
-      UrlRewriteEnvironment environment,
-      Resolver resolver,
-      Map<String,UrlRewriteFunctionProcessor> functions,
-      UrlRewriter.Direction direction,
-      Template url ) {
-    this.environment = environment;
-    this.resolver = resolver;
-    this.functions = functions;
-    this.params = new ContextParameters();
-    this.evaluator = new ContextEvaluator();
-    this.direction = direction;
-    this.originalUrl = url;
-    this.currentUrl = url;
-  }
-
-  @Override
-  public UrlRewriter.Direction getDirection() {
-    return direction;
-  }
-
-  @Override
-  public Template getOriginalUrl() {
-    return originalUrl;
-  }
-
-  @Override
-  public Template getCurrentUrl() {
-    return currentUrl;
-  }
-
-  @Override
-  public void setCurrentUrl( Template url ) {
-    currentUrl = url;
-  }
-
-  @Override
-  public void addParameters( Params parameters ) {
-    params.add( parameters );
-  }
-
-  @Override
-  public Params getParameters() {
-    return params;
-  }
-
-  @Override
-  public Evaluator getEvaluator() {
-    return evaluator;
-  }
-
-  private class ContextParameters implements Params {
-
-    Map<String,List<String>> map = new HashMap<>();
-
-    @Override
-    public Set<String> getNames() {
-      return map.keySet();
-    }
-
-    @Override
-    public List<String> resolve( String name ) {
-      List<String> values = map.get( name ); // Try to find the name in the context map.
-      if( values == null ) {
-        try {
-          values = resolver.resolve( name );
-          if( values == null ) {
-            values = environment.resolve( name ); // Try to find the name in the environment.
-          }
-        } catch( Exception e ) {
-          LOG.failedToFindValuesByParameter( name, e );
-          // Ignore it and return null.
-        }
-      }
-      return values;
-    }
-
-    public void add( Params params ) {
-      for( String name : params.getNames() ) {
-        map.put( name, params.resolve( name ) );
-      }
-    }
-
-  }
-
-  private class ContextEvaluator implements Evaluator {
-
-    @Override
-    public List<String> evaluate( String function, List<String> parameters ) {
-      List<String> results = null;
-      UrlRewriteFunctionProcessor processor = functions.get( function );
-      if( processor != null ) {
-        try {
-          results = processor.resolve( UrlRewriteContextImpl.this, parameters );
-        } catch( Exception e ) {
-          LOG.failedToInvokeRewriteFunction( function, e );
-          results = null;
-        }
-      }
-      return results;
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteDeploymentContributor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteDeploymentContributor.java
deleted file mode 100644
index d48468c..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteDeploymentContributor.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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterDescriptor;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletFilter;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-import org.jboss.shrinkwrap.api.asset.StringAsset;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.List;
-
-public class UrlRewriteDeploymentContributor extends ProviderDeploymentContributorBase {
-
-  private static final String PROVIDER_ROLE_NAME = "rewrite";
-  private static final String PROVIDER_IMPL_NAME = "url-rewrite";
-  private static final String PARAM_SERVICE_ROLE = "service.role";
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-
-  @Override
-  public String getRole() {
-    return PROVIDER_ROLE_NAME;
-  }
-
-  @Override
-  public String getName() {
-    return PROVIDER_IMPL_NAME;
-  }
-
-  public void initializeContribution( DeploymentContext context ) {
-    context.addDescriptor( getRole(), UrlRewriteRulesDescriptorFactory.create() );
-  }
-
-  public void contributeProvider( DeploymentContext context, Provider provider ) {
-  }
-
-  public void finalizeContribution( DeploymentContext context ) {
-    // Write the descriptor into the archive.
-    UrlRewriteRulesDescriptor descriptor = context.getDescriptor( getRole() );
-    StringWriter writer = new StringWriter();
-    try {
-      UrlRewriteRulesDescriptorFactory.store( descriptor, "xml", writer );
-    } catch( IOException e ) {
-      LOG.failedToWriteRulesDescriptor( e );
-    }
-    String asset = writer.toString();
-    context.getWebArchive().addAsWebInfResource(
-        new StringAsset( asset ),
-        UrlRewriteServletContextListener.DESCRIPTOR_DEFAULT_FILE_NAME );
-
-    // Tell the provider the location of the descriptor.
-    context.getWebAppDescriptor().createListener().listenerClass( UrlRewriteServletContextListener.class.getName() );
-    context.getWebAppDescriptor().createContextParam()
-        .paramName( UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME )
-        .paramValue( UrlRewriteServletContextListener.DESCRIPTOR_DEFAULT_LOCATION );
-//    ServletType<WebAppDescriptor> servlet = findServlet( context, context.getTopology().getName() );
-//    servlet.createInitParam()
-//        .paramName( UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME )
-//        .paramValue( DESCRIPTOR_FILE_NAME );
-  }
-
-  @Override
-  public void contributeFilter(
-      DeploymentContext context,
-      Provider provider,
-      Service service,
-      ResourceDescriptor resource,
-      List<FilterParamDescriptor> params ) {
-    FilterDescriptor filterDescriptor = resource.addFilter();
-    filterDescriptor.role( getRole() ).name( getName() ).impl( UrlRewriteServletFilter.class ).params( params );
-    filterDescriptor.param().name(PARAM_SERVICE_ROLE).value(service.getRole());
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterApplyDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterApplyDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterApplyDescriptorImpl.java
deleted file mode 100644
index ff3c4d5..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterApplyDescriptorImpl.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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
-
-public class UrlRewriteFilterApplyDescriptorImpl
-    extends UrlRewriteFilterSelectorDescriptorBase<UrlRewriteFilterApplyDescriptor>
-    implements UrlRewriteFilterApplyDescriptor {
-
-  private String rule;
-
-  @Override
-  public String rule() {
-    return rule;
-  }
-
-  @Override
-  public UrlRewriteFilterApplyDescriptor rule( String rule ) {
-    this.rule = rule;
-    return this;
-  }
-
-  public void setRule( String rule ) {
-    this.rule = rule;
-  }
-
-  public String getRule() {
-    return rule;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterBufferDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterBufferDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterBufferDescriptorImpl.java
deleted file mode 100644
index d8ac83d..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterBufferDescriptorImpl.java
+++ /dev/null
@@ -1,37 +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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterBufferDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterDetectDescriptor;
-
-public class UrlRewriteFilterBufferDescriptorImpl
-    extends UrlRewriteFilterGroupDescriptorBase
-    implements UrlRewriteFilterBufferDescriptor {
-
-  @Override
-  public UrlRewriteFilterDetectDescriptor addDetect( String path, String value ) {
-    UrlRewriteFilterDetectDescriptor detect = new UrlRewriteFilterDetectDescriptorImpl();
-    detect.path( path );
-    detect.value( value );
-    addSelector( detect );
-    return detect;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterContentDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterContentDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterContentDescriptorImpl.java
deleted file mode 100644
index 3d42537..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterContentDescriptorImpl.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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterBufferDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-
-public class UrlRewriteFilterContentDescriptorImpl
-    extends UrlRewriteFilterGroupDescriptorBase
-    implements UrlRewriteFilterContentDescriptor {
-
-  private String type;
-
-  private String asType;
-
-  public UrlRewriteFilterContentDescriptorImpl() {
-  }
-
-  @Override
-  public String type() {
-    return this.type;
-  }
-
-  @Override
-  public String asType() {
-    return asType;
-  }
-
-  @Override
-  public UrlRewriteFilterContentDescriptor type( String type ) {
-    this.type = type;
-    return this;
-  }
-
-  @Override
-  public UrlRewriteFilterContentDescriptor asType( String type ) {
-    asType = type;
-    return this;
-  }
-
-  public void setType(String type ) {
-    type( type );
-  }
-
-  public String getType() {
-    return type;
-  }
-
-  public String getAsType() {
-    return asType;
-  }
-
-  public void setAsType(String asType) {
-    this.asType = asType;
-  }
-
-  @Override
-  public UrlRewriteFilterBufferDescriptor addBuffer( String path ) {
-    UrlRewriteFilterBufferDescriptor descriptor = new UrlRewriteFilterBufferDescriptorImpl();
-    descriptor.path( path );
-    addSelector( descriptor );
-    return descriptor;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterDescriptorImpl.java
deleted file mode 100644
index 5a72547..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterDescriptorImpl.java
+++ /dev/null
@@ -1,87 +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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterDescriptor;
-import org.apache.hadoop.gateway.util.MimeTypeMap;
-
-import javax.activation.MimeType;
-import javax.activation.MimeTypeParseException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class UrlRewriteFilterDescriptorImpl implements UrlRewriteFilterDescriptor {
-
-  private String name;
-  private List<UrlRewriteFilterContentDescriptor> contentList = new ArrayList<UrlRewriteFilterContentDescriptor>();
-  private MimeTypeMap<UrlRewriteFilterContentDescriptor> contentMap = new MimeTypeMap<UrlRewriteFilterContentDescriptor>();
-
-  public UrlRewriteFilterDescriptorImpl() {
-  }
-
-  @Override
-  public String name() {
-    return this.name;
-  }
-
-  public String getName() {
-    return name;
-  }
-
-  @Override
-  public UrlRewriteFilterDescriptor name( String name ) {
-    this.name = name;
-    return this;
-  }
-
-  public void setName( String name ) {
-    this.name = name;
-  }
-
-  @Override
-  public List<UrlRewriteFilterContentDescriptor> getContents() {
-    return contentList;
-  }
-
-  @Override
-  public UrlRewriteFilterContentDescriptor getContent( String type ) {
-    return contentMap.get( type );
-  }
-
-  @Override
-  public UrlRewriteFilterContentDescriptor getContent( MimeType type ) {
-    return contentMap.get( type );
-  }
-
-  @Override
-  public UrlRewriteFilterContentDescriptor addContent( String type ) {
-    UrlRewriteFilterContentDescriptorImpl impl = new UrlRewriteFilterContentDescriptorImpl();
-    impl.type( type );
-    contentList.add( impl );
-    try {
-      contentMap.put( new MimeType( type ), impl );
-    } catch( MimeTypeParseException e ) {
-      throw new IllegalArgumentException( type, e );
-    }
-    return impl;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterDetectDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterDetectDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterDetectDescriptorImpl.java
deleted file mode 100644
index b4b14a6..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterDetectDescriptorImpl.java
+++ /dev/null
@@ -1,65 +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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterDetectDescriptor;
-
-public class UrlRewriteFilterDetectDescriptorImpl
-    extends UrlRewriteFilterGroupDescriptorBase
-    implements UrlRewriteFilterDetectDescriptor {
-
-  private String value;
-  private Object compiledValue;
-
-  @Override
-  public String value() {
-    return value;
-  }
-
-  @Override
-  public UrlRewriteFilterDetectDescriptor value( String value ) {
-    this.value = value;
-    return this;
-  }
-
-  public void setValue( String value ) {
-    this.value = value;
-  }
-
-  public String getValue() {
-    return value;
-  }
-
-  @Override
-  public <C> C compiledValue() {
-    return (C)compiledValue;
-  }
-
-  @Override
-  public UrlRewriteFilterDetectDescriptor compiledValue( String compiledValue ) {
-    this.compiledValue = compiledValue;
-    return this;
-  }
-
-  @Override
-  public <C> C compiledValue( Compiler<C> compiler ) {
-    compiledValue = compiler.compile( value, (C)compiledValue );
-    return (C)compiledValue;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterGroupDescriptorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterGroupDescriptorBase.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterGroupDescriptorBase.java
deleted file mode 100644
index 228cfa4..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterGroupDescriptorBase.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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterGroupDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class UrlRewriteFilterGroupDescriptorBase
-    extends UrlRewriteFilterSelectorDescriptorBase
-    implements UrlRewriteFilterGroupDescriptor {
-
-  private List<UrlRewriteFilterPathDescriptor> selectors = new ArrayList<UrlRewriteFilterPathDescriptor>();
-
-  @Override
-  public List<UrlRewriteFilterPathDescriptor> getSelectors() {
-    return selectors;
-  }
-
-  @Override
-  public void addSelector( UrlRewriteFilterPathDescriptor selector ) {
-    this.selectors.add( selector );
-  }
-
-  @Override
-  public UrlRewriteFilterApplyDescriptor addApply( String path, String rule ) {
-    UrlRewriteFilterApplyDescriptor apply = new UrlRewriteFilterApplyDescriptorImpl();
-    apply.path( path );
-    apply.rule( rule );
-    addSelector( apply );
-    return apply;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterReader.java
deleted file mode 100644
index c291468..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterReader.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.hadoop.gateway.filter.rewrite.impl;
-
-import java.util.regex.Pattern;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
-
-
-public interface UrlRewriteFilterReader {
-
-  public String filterValueString( String name, String value, String rule );
-
-  public static class RegexCompiler implements UrlRewriteFilterPathDescriptor.Compiler<Pattern> {
-    @Override
-    public Pattern compile( String expression, Pattern compiled ) {
-      if( compiled != null ) {
-        return compiled;
-      } else {
-        return Pattern.compile( expression );
-      }
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterScopeDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterScopeDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterScopeDescriptorImpl.java
deleted file mode 100644
index bdebe69..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterScopeDescriptorImpl.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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterScopeDescriptor;
-
-public class UrlRewriteFilterScopeDescriptorImpl
-    extends UrlRewriteFilterGroupDescriptorBase
-    implements UrlRewriteFilterScopeDescriptor {
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterSelectorDescriptorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterSelectorDescriptorBase.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterSelectorDescriptorBase.java
deleted file mode 100644
index ff4ab22..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFilterSelectorDescriptorBase.java
+++ /dev/null
@@ -1,64 +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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
-
-public class UrlRewriteFilterSelectorDescriptorBase<T> implements UrlRewriteFilterPathDescriptor<T> {
-
-  private String path;
-  private Object compiledPath;
-
-  @Override
-  public String path() {
-    return path;
-  }
-
-  @Override
-  public T path( String path ) {
-    this.path = path;
-    return (T)this;
-  }
-
-  public void setPath( String path ) {
-    this.path = path;
-  }
-
-  public String getPath()  {
-    return path;
-  }
-
-  @Override
-  public <C> C compiledPath() {
-    return (C)compiledPath;
-  }
-
-  @Override
-  @SuppressWarnings("unchecked")
-  public T compiledPath( Object compiledPath ) {
-    this.compiledPath = compiledPath;
-    return (T)this;
-  }
-
-  @Override
-  public <C> C compiledPath( Compiler<C> compiler ) {
-    compiledPath = compiler.compile( path, (C)compiledPath );
-    return (C)compiledPath;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFunctionProcessorFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFunctionProcessorFactory.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFunctionProcessorFactory.java
deleted file mode 100644
index 2676cfc..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteFunctionProcessorFactory.java
+++ /dev/null
@@ -1,113 +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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.ServiceLoader;
-
-public abstract class UrlRewriteFunctionProcessorFactory {
-
-  private static final Map<Class<? extends UrlRewriteFunctionDescriptor>,Map<String,Class<? extends UrlRewriteFunctionProcessor>>> MAP
-      = loadProcessors();
-
-  private UrlRewriteFunctionProcessorFactory() {
-  }
-
-  public static UrlRewriteFunctionProcessor create( String name, UrlRewriteFunctionDescriptor descriptor )
-      throws IllegalAccessException, InstantiationException {
-    UrlRewriteFunctionProcessor processor;
-    if( descriptor == null ) {
-      descriptor = UrlRewriteFunctionDescriptorFactory.create( name );
-    }
-    Map<String,Class<? extends UrlRewriteFunctionProcessor>> typeMap;
-    typeMap = MAP.get( descriptor.getClass() );
-    if( typeMap == null ) {
-      Class<? extends UrlRewriteFunctionDescriptor> descriptorInterface = getDescriptorInterface( descriptor );
-      typeMap = MAP.get( descriptorInterface );
-    }
-    if( typeMap == null ) {
-      throw new IllegalArgumentException( descriptor.getClass().getName() );
-    } else {
-      Class<? extends UrlRewriteFunctionProcessor> processorClass = typeMap.get( name );
-      if( processorClass == null ) {
-        throw new IllegalArgumentException( name );
-      } else {
-        processor = processorClass.newInstance();
-      }
-    }
-    return processor;
-  }
-
-  private static Map<Class<? extends UrlRewriteFunctionDescriptor>,Map<String,Class<? extends UrlRewriteFunctionProcessor>>> loadProcessors() {
-    Map<Class<? extends UrlRewriteFunctionDescriptor>,Map<String,Class<? extends UrlRewriteFunctionProcessor>>> descriptorMap
-        = new HashMap<>();
-    ServiceLoader<UrlRewriteFunctionProcessor> processors = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    for( UrlRewriteFunctionProcessor processor : processors ) {
-      Class<? extends UrlRewriteFunctionDescriptor> descriptorInterface = getDescriptorInterface( processor );
-      Map<String,Class<? extends UrlRewriteFunctionProcessor>> typeMap = descriptorMap.get( descriptorInterface );
-      if( typeMap == null ) {
-        typeMap = new HashMap<>();
-        descriptorMap.put( descriptorInterface, typeMap );
-      }
-      String functionName = processor.name();
-      typeMap.put( functionName, processor.getClass() );
-    }
-    return descriptorMap;
-  }
-
-  private static Class<? extends UrlRewriteFunctionDescriptor> getDescriptorInterface(
-      UrlRewriteFunctionDescriptor descriptor ) {
-    Class<? extends UrlRewriteFunctionDescriptor> descriptorClass = null;
-    for( Type interfaceType : descriptor.getClass().getGenericInterfaces() ) {
-      Class genericClass = (Class)interfaceType;
-      if( UrlRewriteFunctionDescriptor.class.isAssignableFrom( genericClass ) ) {
-        descriptorClass = uncheckedDescriptorClassCast( genericClass );
-        break;
-      }
-    }
-    return descriptorClass;
-  }
-
-  private static Class<? extends UrlRewriteFunctionDescriptor> getDescriptorInterface(
-      UrlRewriteFunctionProcessor processor ) {
-    Class<? extends UrlRewriteFunctionDescriptor> descriptorClass = null;
-    Class<? extends UrlRewriteFunctionProcessor> processorClass = processor.getClass();
-    for( Type interfaceType : processorClass.getGenericInterfaces() ) {
-      if( UrlRewriteFunctionProcessor.class.isAssignableFrom(
-          (Class)((ParameterizedType)interfaceType).getRawType() ) ) {
-        ParameterizedType interfaceClass = (ParameterizedType)interfaceType;
-        descriptorClass = uncheckedDescriptorClassCast( interfaceClass.getActualTypeArguments()[ 0 ] );
-        break;
-      }
-    }
-    return descriptorClass;
-  }
-
-  @SuppressWarnings("unchecked")
-  private static Class<? extends UrlRewriteFunctionDescriptor> uncheckedDescriptorClassCast( Type type ) {
-    return (Class<? extends UrlRewriteFunctionDescriptor>)type;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRequest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRequest.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRequest.java
deleted file mode 100644
index de9331b..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRequest.java
+++ /dev/null
@@ -1,265 +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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.filter.GatewayRequestWrapper;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletFilter;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStreamFilterFactory;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.util.MimeTypes;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import javax.activation.MimeType;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletInputStream;
-import javax.servlet.http.HttpServletRequest;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.UnsupportedEncodingException;
-import java.net.URISyntaxException;
-import java.net.URLDecoder;
-import java.util.Arrays;
-import java.util.Enumeration;
-import java.util.List;
-
-import static org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteUtil.pickFirstRuleWithEqualsIgnoreCasePathMatch;
-
-public class UrlRewriteRequest extends GatewayRequestWrapper implements Resolver {
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-  private static final String[] EMPTY_STRING_ARRAY = new String[]{};
-
-  private FilterConfig config;
-  private UrlRewriter rewriter;
-  private String urlRuleName;
-  private String bodyFilterName;
-  private String headersFilterName;
-  private UrlRewriteFilterContentDescriptor headersFilterConfig;
-  private String cookiesFilterName;
-
-  /**
-   * Constructs a request object wrapping the given request.
-   *
-   * @throws IllegalArgumentException if the request is null
-   */
-  public UrlRewriteRequest( FilterConfig config, HttpServletRequest request ) throws IOException {
-    super( request );
-    this.config = config;
-    this.rewriter = UrlRewriteServletContextListener.getUrlRewriter( config.getServletContext() );
-    this.urlRuleName = config.getInitParameter( UrlRewriteServletFilter.REQUEST_URL_RULE_PARAM );
-    this.bodyFilterName = config.getInitParameter( UrlRewriteServletFilter.REQUEST_BODY_FILTER_PARAM );
-    this.headersFilterName = config.getInitParameter( UrlRewriteServletFilter.REQUEST_HEADERS_FILTER_PARAM );
-    this.headersFilterConfig = getRewriteFilterConfig( headersFilterName, UrlRewriteServletFilter.HEADERS_MIME_TYPE );
-    this.cookiesFilterName = config.getInitParameter( UrlRewriteServletFilter.REQUEST_COOKIES_FILTER_PARAM );
-  }
-
-  private Template getSourceUrl() {
-    Template urlTemplate;
-    //KNOX-439[
-    //StringBuffer urlString = super.getRequestURL();
-    StringBuffer urlString = new StringBuffer( 128 );
-    urlString.append( getScheme() );
-    urlString.append( "://" );
-    urlString.append( getServerName() );
-    urlString.append( ":" );
-    urlString.append( getServerPort() );
-    urlString.append( super.getRequestURI() );
-    //]
-    String queryString = super.getQueryString();
-    if( queryString != null ) {
-      urlString.append( '?' );
-      urlString.append( queryString );
-    }
-    try {
-      urlTemplate = Parser.parseLiteral( urlString.toString() );
-    } catch( URISyntaxException e ) {
-      LOG.failedToParseValueForUrlRewrite( urlString.toString() );
-      // Shouldn't be possible given that the URL is constructed from parts of an existing URL.
-      urlTemplate = null;
-    }
-    return urlTemplate;
-  }
-
-  // Note: Source url was added to the request attributes by the GatewayFilter doFilter method.
-  private Template getTargetUrl() {
-    boolean rewriteRequestUrl = true;
-    Template targetUrl;
-    if( rewriteRequestUrl ) {
-      targetUrl = (Template)getAttribute( AbstractGatewayFilter.TARGET_REQUEST_URL_ATTRIBUTE_NAME );
-      if( targetUrl == null ) {
-        Template sourceUrl = getSourceUrl();
-        targetUrl = rewriter.rewrite( this, sourceUrl, UrlRewriter.Direction.IN, urlRuleName );
-        setAttribute( AbstractGatewayFilter.TARGET_REQUEST_URL_ATTRIBUTE_NAME, targetUrl );
-      }
-    } else {
-      targetUrl = (Template)getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_URL_ATTRIBUTE_NAME );
-    }
-    return targetUrl;
-  }
-
-  private String[] splitTargetUrl( Template url ) {
-    if( url == null ) {
-      return EMPTY_STRING_ARRAY;
-    } else {
-      String s = url.toString();
-      return s.split( "\\?" );
-    }
-  }
-
-  @Override
-  public StringBuffer getRequestURL() {
-    return new StringBuffer( getRequestURI() );
-  }
-
-  //TODO: I think this method is implemented wrong based on the HttpServletRequest.getRequestURI docs.
-  // It should not include the scheme or authority parts.
-  @Override
-  public String getRequestURI() {
-    String[] split = splitTargetUrl( getTargetUrl() );
-    if( split.length > 0 ) {
-      return split[0];
-    } else {
-      return "";
-    }
-  }
-
-  @Override
-  public String getQueryString() {
-    String[] split = splitTargetUrl( getTargetUrl() );
-    if( split.length > 1 ) {
-      try {
-        return URLDecoder.decode(split[1], "UTF-8");
-      } catch ( UnsupportedEncodingException e ) {
-        LOG.failedToDecodeQueryString(split[1], e);
-        return split[1];
-      }
-    } else {
-      return null;
-    }
-  }
-
-  private String rewriteValue( UrlRewriter rewriter, String value, String rule ) {
-    try {
-      Template input = Parser.parseLiteral( value );
-      Template output = rewriter.rewrite( this, input, UrlRewriter.Direction.IN, rule );
-      value = output.getPattern();
-    } catch( URISyntaxException e ) {
-      LOG.failedToParseValueForUrlRewrite( value );
-    }
-    return value;
-  }
-
-  @Override
-  public String getHeader( String name ) {
-    String value = super.getHeader( name );
-    if( value != null ) {
-      value = rewriteValue( rewriter, super.getHeader( name ), pickFirstRuleWithEqualsIgnoreCasePathMatch( headersFilterConfig, name ) );
-    }
-    return value;
-  }
-
-  @SuppressWarnings("unchecked")
-  public Enumeration getHeaders( String name ) {
-    return new EnumerationRewriter( rewriter, super.getHeaders( name ), pickFirstRuleWithEqualsIgnoreCasePathMatch( headersFilterConfig, name ) );
-  }
-
-  @Override
-  public List<String> resolve( String name ) {
-    return Arrays.asList( config.getInitParameter( name ) );
-  }
-
-  private class EnumerationRewriter implements Enumeration<String> {
-
-    private UrlRewriter rewriter;
-    private Enumeration<String> delegate;
-    private String rule;
-
-    private EnumerationRewriter( UrlRewriter rewriter, Enumeration<String> delegate, String rule ) {
-      this.rewriter = rewriter;
-      this.delegate = delegate;
-      this.rule = rule;
-    }
-
-    @Override
-    public boolean hasMoreElements() {
-      return delegate.hasMoreElements();
-    }
-
-    @Override
-    public String nextElement() {
-      return rewriteValue( rewriter, delegate.nextElement(), rule );
-    }
-  }
-
-  @Override
-  public ServletInputStream getInputStream() throws IOException {
-    ServletInputStream input = super.getInputStream();
-    if( getContentLength() != 0 ) {
-      MimeType mimeType = getMimeType();
-      UrlRewriteFilterContentDescriptor filterContentConfig = getRewriteFilterConfig( bodyFilterName, mimeType );
-      if (filterContentConfig != null) {
-        String asType = filterContentConfig.asType();
-        if ( asType != null && asType.trim().length() > 0 ) {
-          mimeType = MimeTypes.create(asType, getCharacterEncoding());
-        }
-      }
-      InputStream stream = UrlRewriteStreamFilterFactory.create( mimeType, null, input, rewriter, this, UrlRewriter.Direction.IN, filterContentConfig );
-      input = new UrlRewriteRequestStream( stream );
-    }
-    return input;
-  }
-
-  @Override
-  public BufferedReader getReader() throws IOException {
-    return new BufferedReader( new InputStreamReader( getInputStream(), getCharacterEncoding() ) );
-  }
-
-  @Override
-  public int getContentLength() {
-    // The rewrite might change the content length so return the default of -1 to indicate the length is unknown.
-    int contentLength = super.getContentLength();
-    if( contentLength > 0 ) {
-      contentLength = -1;
-    }
-    return contentLength;
-  }
-
-  private UrlRewriteFilterContentDescriptor getRewriteFilterConfig( String filterName, MimeType mimeType ) {
-    UrlRewriteFilterContentDescriptor filterContentConfig = null;
-    UrlRewriteRulesDescriptor rewriteConfig = rewriter.getConfig();
-    if( rewriteConfig != null ) {
-      UrlRewriteFilterDescriptor filterConfig = rewriteConfig.getFilter( filterName );
-      if( filterConfig != null ) {
-        filterContentConfig = filterConfig.getContent( mimeType );
-      }
-    }
-    return filterContentConfig;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRequestStream.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRequestStream.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRequestStream.java
deleted file mode 100644
index 1904d15..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRequestStream.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.hadoop.gateway.filter.rewrite.impl;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.hadoop.gateway.servlet.SynchronousServletInputStreamAdapter;
-
-//TODO: This needs to be coded much more efficiently!
-public class UrlRewriteRequestStream extends SynchronousServletInputStreamAdapter {
-
-  private InputStream stream;
-
-  public UrlRewriteRequestStream( InputStream stream ) {
-    this.stream = stream;
-  }
-
-  @Override
-  public int read() throws IOException {
-    return stream.read();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteResponse.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteResponse.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteResponse.java
deleted file mode 100644
index d4e31e3..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteResponse.java
+++ /dev/null
@@ -1,330 +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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.GatewayResponseWrapper;
-import org.apache.hadoop.gateway.filter.ResponseStreamer;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletFilter;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStreamFilterFactory;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.util.MimeTypes;
-import org.apache.hadoop.gateway.util.Urls;
-import org.apache.hadoop.gateway.util.urltemplate.Params;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-import org.apache.commons.io.IOUtils;
-
-import javax.activation.MimeType;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletOutputStream;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import java.io.BufferedInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.InetAddress;
-import java.net.URISyntaxException;
-import java.net.UnknownHostException;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.zip.GZIPInputStream;
-import java.util.zip.GZIPOutputStream;
-import java.util.zip.ZipException;
-
-import static org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteUtil.getRewriteFilterConfig;
-import static org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteUtil.pickFirstRuleWithEqualsIgnoreCasePathMatch;
-
-/**
- *
- */
-public class UrlRewriteResponse extends GatewayResponseWrapper implements Params, ResponseStreamer {
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-
-  // An 8K buffer better matches the underlying buffer sizes.
-  // Testing with 16K made no appreciable difference.
-  private static final int STREAM_BUFFER_SIZE = 8 * 1024;
-
-  private static final Set<String> IGNORE_HEADER_NAMES = new HashSet<>();
-  static {
-    IGNORE_HEADER_NAMES.add( "Content-Length" );
-  }
-
-  private static final String REQUEST_PARAM_PREFIX = "request.";
-  private static final String CLUSTER_PARAM_PREFIX = "cluster.";
-  private static final String GATEWAY_PARAM_PREFIX = "gateway.";
-  public  static final String INBOUND_QUERY_PARAM_PREFIX   = "query.param.";
-
-  private UrlRewriter rewriter;
-  private FilterConfig config;
-  private HttpServletRequest request;
-  private HttpServletResponse response;
-  private ServletOutputStream output;
-  private String bodyFilterName;
-  private String headersFilterName;
-  private UrlRewriteFilterContentDescriptor headersFilterConfig;
-  private String cookiesFilterName;
-  private String xForwardedHostname;
-  private String xForwardedPort;
-  private String xForwardedScheme;
-
-  public UrlRewriteResponse( FilterConfig config, HttpServletRequest request, HttpServletResponse response )
-      throws IOException {
-    super( response );
-    this.rewriter = UrlRewriteServletContextListener.getUrlRewriter( config.getServletContext() );
-    this.config = config;
-    this.request = request;
-    this.response = response;
-    this.output = null;
-    getXForwardedHeaders();
-    this.bodyFilterName = config.getInitParameter( UrlRewriteServletFilter.RESPONSE_BODY_FILTER_PARAM );
-    this.headersFilterName = config.getInitParameter( UrlRewriteServletFilter.RESPONSE_HEADERS_FILTER_PARAM );
-    this.headersFilterConfig = getRewriteFilterConfig( rewriter.getConfig(), headersFilterName, UrlRewriteServletFilter.HEADERS_MIME_TYPE );
-    this.cookiesFilterName = config.getInitParameter( UrlRewriteServletFilter.RESPONSE_COOKIES_FILTER_PARAM );
-  }
-
-  protected boolean ignoreHeader( String name ) {
-    return IGNORE_HEADER_NAMES.contains( name );
-  }
-
-  private String rewriteValue( String value, String rule ) {
-    try {
-      Template input = Parser.parseLiteral( value );
-      Template output = rewriter.rewrite( this, input, UrlRewriter.Direction.OUT, rule );
-      if( output != null ) {
-        value = output.toString();
-      }
-    } catch( URISyntaxException e ) {
-      LOG.failedToParseValueForUrlRewrite( value );
-    }
-    return value;
-  }
-
-  // Ignore the Content-Length from the dispatch respond since the respond body may be rewritten.
-  @Override
-  public void setHeader( String name, String value ) {
-    if( !ignoreHeader( name) ) {
-      value = rewriteValue( value, pickFirstRuleWithEqualsIgnoreCasePathMatch( headersFilterConfig, name ) );
-      super.setHeader( name, value );
-    }
-  }
-
-  // Ignore the Content-Length from the dispatch respond since the respond body may be rewritten.
-  @Override
-  public void addHeader( String name, String value ) {
-    if( !ignoreHeader( name ) ) {
-      String rule = pickFirstRuleWithEqualsIgnoreCasePathMatch( headersFilterConfig, name );
-      value = rewriteValue( value, rule );
-      super.addHeader( name, value );
-    }
-  }
-
-  @Override
-  public OutputStream getRawOutputStream() throws IOException {
-    return response.getOutputStream();
-  }
-
-  @Override
-  public void streamResponse( InputStream input, OutputStream output ) throws IOException {
-    InputStream inStream;
-    OutputStream outStream;
-    boolean isGzip = false;
-    BufferedInputStream inBuffer = new BufferedInputStream(input);
-    try {
-      // Use this way to check whether the input stream is gzip compressed, in case
-      // the content encoding header is unknown, as it could be unset in inbound response
-      inBuffer.mark(STREAM_BUFFER_SIZE);
-      inStream = new GZIPInputStream(inBuffer);
-      isGzip = true;
-    } catch (ZipException e) {
-      inBuffer.reset();
-      inStream = inBuffer;
-    } catch (IOException e) {
-      inBuffer.reset();
-      inStream = inBuffer;
-    }
-
-    MimeType mimeType = getMimeType();
-    UrlRewriteFilterContentDescriptor filterContentConfig =
-        getRewriteFilterConfig( rewriter.getConfig(), bodyFilterName, mimeType );
-    if (filterContentConfig != null) {
-      String asType = filterContentConfig.asType();
-      if ( asType != null && asType.trim().length() > 0 ) {
-        mimeType = MimeTypes.create(asType, getCharacterEncoding());
-      }
-    }
-    InputStream filteredInput = UrlRewriteStreamFilterFactory.create(
-        mimeType, null, inStream, rewriter, this, UrlRewriter.Direction.OUT, filterContentConfig );
-    outStream = (isGzip) ? new GZIPOutputStream(output) : output;
-    IOUtils.copyLarge( filteredInput, outStream, new byte[STREAM_BUFFER_SIZE] );
-    //KNOX-685: outStream.flush();
-    outStream.close();
-  }
-
-  //TODO: Need to buffer the output here and when it is closed, rewrite it and then write the result to the stream.
-  // This should only happen if the caller isn't using the streaming model.
-  @Override
-  public ServletOutputStream getOutputStream() throws IOException {
-    if( output == null ) {
-      output = new UrlRewriteResponseStream( this );
-    }
-    return output;
-  }
-
-  @Override
-  public Set<String> getNames() {
-    return Collections.emptySet();
-  }
-
-  @Override
-  @SuppressWarnings( "unchecked" )
-  public List<String> resolve( String name ) {
-    if( name.startsWith( REQUEST_PARAM_PREFIX ) ) {
-      return Arrays.asList( getRequestParam( name.substring( REQUEST_PARAM_PREFIX.length() ) ) );
-    } else if ( name.startsWith( GATEWAY_PARAM_PREFIX ) ) {
-      return Arrays.asList( getGatewayParam( name.substring( GATEWAY_PARAM_PREFIX.length() ) ) );
-    } else if ( name.startsWith( CLUSTER_PARAM_PREFIX ) ) {
-      return Arrays.asList( getClusterParam( name.substring( GATEWAY_PARAM_PREFIX.length() ) ) );
-    } else if ( name.startsWith( INBOUND_QUERY_PARAM_PREFIX ) ) {
-      return getInboundQueryParam(name.substring(INBOUND_QUERY_PARAM_PREFIX.length()));
-    } else {
-      return Arrays.asList( config.getInitParameter( name ) );
-    }
-  }
-
-  // KNOX-464: Doing this because Jetty only returns the string version of the IP address for request.getLocalName().
-  // Hopefully the local hostname will be cached so this will not be a significant performance hit.
-  // Previously this was an inline request.getServerName() but this ended up mixing the hostname from the Host header
-  // and the local port which was making load balancer configuration difficult if not impossible.
-  private String getRequestLocalHostName() {
-    String hostName = request.getLocalName();
-    try {
-      hostName = InetAddress.getByName( hostName ).getHostName();
-    } catch( UnknownHostException e ) {
-      // Ignore it and use the original hostname.
-    }
-    return hostName;
-  }
-
-  private String getGatewayParam( String name ) {
-    if( "url".equals( name ) ) {
-      if( xForwardedPort == null ) {
-        return xForwardedScheme + "://" + xForwardedHostname + request.getContextPath();
-      } else {
-        return xForwardedScheme + "://" + xForwardedHostname + ":" + xForwardedPort + request.getContextPath();
-      }
-    } else if( "scheme".equals( name ) ) {
-      return xForwardedScheme;
-    } else if( "host".equals( name ) ) {
-      return xForwardedHostname;
-    } else if( "port".equals( name ) ) {
-        return xForwardedPort;
-    } else if( "addr".equals( name ) || "address".equals( name ) ) {
-      if( xForwardedPort == null ) {
-        return xForwardedHostname;
-      } else {
-        return xForwardedHostname + ":" + xForwardedPort;
-      }
-    } else if( "path".equals( name ) ) {
-      return request.getContextPath();
-    } else {
-      return null;
-    }
-  }
-
-  private String getClusterParam( String name ) {
-    if( "name".equals( name ) ) {
-      return config.getServletContext().getServletContextName();
-    } else {
-      return null;
-    }
-  }
-
-  private List <String> getInboundQueryParam(String name ){
-     List <String> inboundHosts = null;
-     if( this.request!=null )
-       inboundHosts =
-         Arrays.asList( this.request.getParameterValues(name));
-     return inboundHosts;
-  }
-
-  private String getRequestParam( String name ) {
-    if( "host".equals( name ) ) {
-      return request.getServerName();
-    } else if ( "port".equals( name ) ) {
-      return Integer.toString( request.getLocalPort() );
-    } else if ( "scheme".equals( name ) ) {
-      return request.getScheme();
-    } else if ( "context-path".equals( name ) ) {
-      return Urls.stripLeadingSlash( request.getContextPath() );
-    } else {
-      config.getServletContext().getServletContextName();
-      return null;
-    }
-  }
-
-  @SuppressWarnings("deprecation")
-  public String encodeUrl( String url ) {
-    return this.encodeURL( url );
-  }
-
-  //TODO: Route these through the rewriter.
-  public String encodeURL( String url ) {
-    throw new UnsupportedOperationException();
-  }
-
-  @SuppressWarnings("deprecation")
-  public String encodeRedirectUrl( String url ) {
-    return this.encodeRedirectURL( url );
-  }
-
-  //TODO: Route these through the rewriter.
-  public String encodeRedirectURL( String url ) {
-    throw new UnsupportedOperationException();
-  }
-
-  private void getXForwardedHeaders() {
-    xForwardedHostname = request.getHeader( "X-Forwarded-Host" );
-    xForwardedPort = request.getHeader( "X-Forwarded-Port" );
-    xForwardedScheme = request.getHeader( "X-Forwarded-Proto" );
-    if ( xForwardedScheme == null ) {
-      xForwardedScheme = request.getScheme();
-    }
-    if ( xForwardedHostname != null ) {
-      int separator = xForwardedHostname.indexOf( ":" );
-      if ( separator > 0 ) {
-        //a specific port in the forwarded host wins
-        xForwardedPort = xForwardedHostname.substring(separator + 1, xForwardedHostname.length());
-        xForwardedHostname = xForwardedHostname.substring( 0, separator );
-      }
-    } else {
-      xForwardedHostname = getRequestLocalHostName();
-      xForwardedPort = Integer.toString( request.getLocalPort() );
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteResponseStream.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteResponseStream.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteResponseStream.java
deleted file mode 100644
index 41117bd..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteResponseStream.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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.GatewayResponse;
-import org.apache.hadoop.gateway.servlet.SynchronousServletOutputStreamAdapter;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-//TODO: This needs to be coded much more efficiently!
-public class UrlRewriteResponseStream extends SynchronousServletOutputStreamAdapter {
-
-  private static final int DEFAULT_BUFFER_SIZE = 1024;
-
-  private GatewayResponse response;
-  private ByteArrayOutputStream buffer;
-
-  public UrlRewriteResponseStream( GatewayResponse response ) {
-    this.response = response;
-    this.buffer = new ByteArrayOutputStream( DEFAULT_BUFFER_SIZE );
-  }
-
-  @Override
-  public void write( int b ) throws IOException {
-    buffer.write( b );
-  }
-
-  @Override
-  public void close() throws IOException {
-    InputStream stream = new ByteArrayInputStream( buffer.toByteArray() );
-    response.streamResponse( stream ) ;
-    stream.close();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRuleDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRuleDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRuleDescriptorImpl.java
deleted file mode 100644
index c0396a2..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRuleDescriptorImpl.java
+++ /dev/null
@@ -1,194 +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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFlowDescriptorBase;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.net.URISyntaxException;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-public class UrlRewriteRuleDescriptorImpl extends UrlRewriteFlowDescriptorBase<UrlRewriteRuleDescriptor> implements UrlRewriteRuleDescriptor {
-
-  private String name;
-  private String scope;
-  private String pattern;
-  private Template template;
-  private EnumSet<UrlRewriter.Direction> directions;
-
-  public UrlRewriteRuleDescriptorImpl() {
-    super( "rule" );
-  }
-
-  @Override
-  public String name() {
-    return this.name;
-  }
-
-  @Override
-  public UrlRewriteRuleDescriptor name( String name ) {
-    this.name = name;
-    return this;
-  }
-
-  public void setName( String name ) {
-    name( name );
-  }
-
-  public String getName() {
-    return name;
-  }
-
-  public String getScope() {
-    return scope;
-  }
-
-  public void setScope(String scope) {
-    scope( scope );
-  }
-
-  @Override
-  public String scope() {
-    return scope;
-  }
-
-  @Override
-  public UrlRewriteStepDescriptor scope( String scope ) {
-    this.scope = scope;
-    return this;
-  }
-
-  @Override
-  public EnumSet<UrlRewriter.Direction> directions() {
-    return directions;
-  }
-
-  @Override
-  public UrlRewriteRuleDescriptor directions( String directions ) {
-    this.directions = parseDirections( directions );
-    return this;
-  }
-
-  public void setDirections( String directions ) {
-    directions( directions );
-  }
-
-  public void setDirection( String directions ) {
-    directions( directions );
-  }
-
-  public void setDir( String directions ) {
-    directions( directions );
-  }
-
-  public String getDir() {
-    String s = null;
-    if( directions != null ) {
-      StringBuilder sb = new StringBuilder();
-      for( UrlRewriter.Direction direction: directions ) {
-        if( sb.length() > 0 ) {
-          sb.append( ',' );
-        }
-        sb.append( direction.toString() );
-      }
-      s = sb.toString();
-    }
-    return s;
-  }
-
-  @Override
-  public UrlRewriteRuleDescriptor directions( UrlRewriter.Direction... directions ) {
-    return this;
-  }
-
-  @Override
-  public String pattern() {
-    return pattern;
-  }
-
-  @Override
-  public UrlRewriteRuleDescriptor pattern( String pattern ) throws URISyntaxException {
-    this.pattern = pattern;
-    this.template = Parser.parseTemplate( pattern );
-    return this;
-  }
-
-  public void setPattern( String pattern ) throws URISyntaxException {
-    pattern( pattern );
-  }
-
-  public void setUrl( String pattern ) throws URISyntaxException {
-    pattern( pattern );
-  }
-
-  public String getPattern() {
-    return pattern();
-  }
-
-  @Override
-  public Template template() {
-    return template;
-  }
-
-  @Override
-  public UrlRewriteRuleDescriptor template( Template template ) {
-    this.template = template;
-    this.pattern = template.toString();
-    return this;
-  }
-
-  private static EnumSet<UrlRewriter.Direction> parseDirections( String directions ) {
-    EnumSet<UrlRewriter.Direction> set = EnumSet.noneOf( UrlRewriter.Direction.class );
-    StringTokenizer parser = new StringTokenizer( directions, " ,;:/|+" );
-    while( parser.hasMoreTokens() ) {
-      UrlRewriter.Direction direction = parseDirection( parser.nextToken() );
-      if( direction != null ) {
-        set.add( direction );
-      }
-    }
-    return set;
-  }
-
-  private static UrlRewriter.Direction parseDirection( String direction ) {
-    direction = direction.trim().toLowerCase();
-    return directionNameMap.get( direction );
-  }
-
-  private static Map<String,UrlRewriter.Direction> directionNameMap = new HashMap<>();
-  static {
-    directionNameMap.put( "inbound", UrlRewriter.Direction.IN );
-    directionNameMap.put( "in", UrlRewriter.Direction.IN );
-    directionNameMap.put( "i", UrlRewriter.Direction.IN );
-    directionNameMap.put( "request", UrlRewriter.Direction.IN );
-    directionNameMap.put( "req", UrlRewriter.Direction.IN );
-
-    directionNameMap.put( "outbound", UrlRewriter.Direction.OUT );
-    directionNameMap.put( "out", UrlRewriter.Direction.OUT );
-    directionNameMap.put( "o", UrlRewriter.Direction.OUT );
-    directionNameMap.put( "response", UrlRewriter.Direction.OUT );
-    directionNameMap.put( "res", UrlRewriter.Direction.OUT );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorHolder.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorHolder.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorHolder.java
deleted file mode 100644
index 708fd8c..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorHolder.java
+++ /dev/null
@@ -1,65 +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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.ext.ScopedMatcher;
-
-import java.util.List;
-
-public class UrlRewriteRuleProcessorHolder extends UrlRewriteStepProcessorHolder {
-
-  private String ruleName;
-
-  private String scope;
-
-  public void initialize( UrlRewriteEnvironment environment, UrlRewriteRuleDescriptor descriptor ) throws Exception {
-    super.initialize( environment, descriptor );
-    ruleName = descriptor.name();
-    //if a scope is set in the rewrite file, use that
-    if (descriptor.scope() != null) {
-      scope = descriptor.scope();
-    } else {
-      //by convention the name of the rules start with ROLENAME/servicename/direction
-      //use the first part of the name to determine the scope, therefore setting the scope of a rule to
-      //be local to that service
-      int slashIndex = ruleName.indexOf('/');
-      if (slashIndex > 0) {
-        scope = ruleName.substring( 0, slashIndex );
-      }
-      //check config to see if the is an override configuration for a given service to have all its rules set to global
-      GatewayConfig gatewayConfig = environment.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
-      if (gatewayConfig != null) {
-        List<String> globalRulesServices = gatewayConfig.getGlobalRulesServices();
-        if ( globalRulesServices.contains(scope) ) {
-          scope = ScopedMatcher.GLOBAL_SCOPE;
-        }
-      }
-    }
-  }
-
-  public String getRuleName() {
-    return ruleName;
-  }
-
-  public String getScope() {
-    return scope;
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorImpl.java
deleted file mode 100644
index a07a9f0..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorImpl.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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptorExt;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteMatchProcessorExt;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-
-public class UrlRewriteRuleProcessorImpl implements UrlRewriteStepProcessor<UrlRewriteRuleDescriptor> {
-
-  private UrlRewriteMatchProcessorExt matchProcessor;
-
-  @Override
-  public String getType() {
-    return "rule";
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, UrlRewriteRuleDescriptor descriptor ) throws Exception {
-    UrlRewriteMatchDescriptor matchDescriptor = new UrlRewriteMatchDescriptorExt();
-    matchDescriptor.operation( "matches" );
-    matchDescriptor.flow( descriptor.flow() );
-    matchDescriptor.template( descriptor.template() );
-    matchProcessor = new UrlRewriteMatchProcessorExt();
-    matchProcessor.initialize( environment, matchDescriptor );
-  }
-
-  @Override
-  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
-    return matchProcessor.process( context );
-  }
-
-  @Override
-  public void destroy() {
-    matchProcessor.destroy();
-  }
-
-}


[10/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/SSOCookieProviderTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/SSOCookieProviderTest.java b/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/SSOCookieProviderTest.java
deleted file mode 100644
index 396aec9..0000000
--- a/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/SSOCookieProviderTest.java
+++ /dev/null
@@ -1,205 +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.hadoop.gateway.provider.federation;
-
-import static org.junit.Assert.fail;
-
-import java.security.NoSuchAlgorithmException;
-import java.security.Principal;
-import java.util.Properties;
-import java.util.Date;
-import java.util.Set;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.hadoop.gateway.provider.federation.jwt.filter.SSOCookieFederationFilter;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.apache.hadoop.gateway.services.security.token.JWTokenAuthority;
-import org.easymock.EasyMock;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import com.nimbusds.jwt.SignedJWT;
-
-public class SSOCookieProviderTest extends AbstractJWTFilterTest {
-  private static final String SERVICE_URL = "https://localhost:8888/resource";
-  private static final String REDIRECT_LOCATION =
-      "https://localhost:8443/authserver?originalUrl=" + SERVICE_URL;
-  
-  @Before
-  public void setup() throws Exception, NoSuchAlgorithmException {
-    super.setup();
-    handler = new TestSSOCookieFederationProvider();
-    ((TestSSOCookieFederationProvider) handler).setTokenService(new TestJWTokenAuthority());
-  }
-  
-  protected void setTokenOnRequest(HttpServletRequest request, SignedJWT jwt) {
-    Cookie cookie = new Cookie("hadoop-jwt", jwt.serialize());
-    EasyMock.expect(request.getCookies()).andReturn(new Cookie[] { cookie });
-  }
-  
-  protected void setGarbledTokenOnRequest(HttpServletRequest request, SignedJWT jwt) {
-    Cookie cookie = new Cookie("hadoop-jwt", "ljm" + jwt.serialize());
-    EasyMock.expect(request.getCookies()).andReturn(new Cookie[] { cookie });
-  }
-
-  protected String getAudienceProperty() {
-    return TestSSOCookieFederationProvider.SSO_EXPECTED_AUDIENCES;
-  }
-  
-  @Test
-  public void testCustomCookieNameJWT() throws Exception {
-    try {
-      Properties props = getProperties();
-      props.put("sso.cookie.name", "jowt");
-      handler.init(new TestFilterConfig(props));
-
-      SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 5000),
-          privateKey, props);
-
-      Cookie cookie = new Cookie("jowt", jwt.serialize());
-      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
-      EasyMock.expect(request.getCookies()).andReturn(new Cookie[] { cookie });
-      EasyMock.expect(request.getRequestURL()).andReturn(
-          new StringBuffer(SERVICE_URL)).anyTimes();
-      EasyMock.expect(request.getQueryString()).andReturn(null);
-      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
-      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
-          SERVICE_URL);
-      EasyMock.replay(request);
-
-      TestFilterChain chain = new TestFilterChain();
-      handler.doFilter(request, response, chain);
-      Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == true);
-      Set<PrimaryPrincipal> principals = chain.subject.getPrincipals(PrimaryPrincipal.class);
-      Assert.assertTrue("No PrimaryPrincipal returned.", principals.size() > 0);
-      Assert.assertEquals("Not the expected principal", "alice", ((Principal)principals.toArray()[0]).getName());
-    } catch (ServletException se) {
-      fail("Should NOT have thrown a ServletException.");
-    }
-  }
-
-  @Test
-  public void testNoProviderURLJWT() throws Exception {
-    try {
-      Properties props = getProperties();
-      props.remove("sso.authentication.provider.url");
-      handler.init(new TestFilterConfig(props));
-
-      fail("Servlet exception should have been thrown.");
-
-    } catch (ServletException se) {
-      // expected - let's ensure it mentions the missing authentication provider URL
-      se.getMessage().contains("authentication provider URL is missing");
-    }
-  }
-  
-/*
-  @Test
-  public void testFailedSignatureValidationJWT() throws Exception {
-    try {
-
-      // Create a public key that doesn't match the one needed to
-      // verify the signature - in order to make it fail verification...
-      KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
-      kpg.initialize(2048);
-
-      KeyPair kp = kpg.genKeyPair();
-      RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();
-
-      handler.setPublicKey(publicKey);
-
-      Properties props = getProperties();
-      handler.init(props);
-
-      SignedJWT jwt = getJWT("bob", new Date(new Date().getTime() + 5000),
-          privateKey);
-
-      Cookie cookie = new Cookie("hadoop-jwt", jwt.serialize());
-      HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
-      Mockito.when(request.getCookies()).thenReturn(new Cookie[] { cookie });
-      Mockito.when(request.getRequestURL()).thenReturn(
-          new StringBuffer(SERVICE_URL)).anyTimes();
-      HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
-      Mockito.when(response.encodeRedirectURL(SERVICE_URL)).thenReturn(
-          SERVICE_URL);
-
-      AuthenticationToken token = handler.alternateAuthenticate(request,
-          response);
-      Mockito.verify(response).sendRedirect(REDIRECT_LOCATION);
-    } catch (ServletException se) {
-      fail("alternateAuthentication should NOT have thrown a ServletException");
-    } catch (AuthenticationException ae) {
-      fail("alternateAuthentication should NOT have thrown a AuthenticationException");
-    }
-  }
-*/
-
-  @Test
-  public void testOrigURLWithQueryString() throws Exception {
-    Properties props = getProperties();
-    handler.init(new TestFilterConfig(props));
-
-    HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
-    EasyMock.expect(request.getRequestURL()).andReturn(
-        new StringBuffer(SERVICE_URL)).anyTimes();
-    EasyMock.expect(request.getQueryString()).andReturn("name=value");
-    EasyMock.replay(request);
-
-    String loginURL = ((TestSSOCookieFederationProvider)handler).testConstructLoginURL(request);
-    Assert.assertNotNull("loginURL should not be null.", loginURL);
-    Assert.assertEquals("https://localhost:8443/authserver?originalUrl=" + SERVICE_URL + "?name=value", loginURL);
-  }
-
-  @Test
-  public void testOrigURLNoQueryString() throws Exception {
-    Properties props = getProperties();
-    handler.init(new TestFilterConfig(props));
-
-    HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
-    EasyMock.expect(request.getRequestURL()).andReturn(
-        new StringBuffer(SERVICE_URL)).anyTimes();
-    EasyMock.expect(request.getQueryString()).andReturn(null);
-    EasyMock.replay(request);
-
-    String loginURL = ((TestSSOCookieFederationProvider)handler).testConstructLoginURL(request);
-    Assert.assertNotNull("LoginURL should not be null.", loginURL);
-    Assert.assertEquals("https://localhost:8443/authserver?originalUrl=" + SERVICE_URL, loginURL);
-  }
-  
-
-  @Override
-  protected String getVerificationPemProperty() {
-    return SSOCookieFederationFilter.SSO_VERIFICATION_PEM;
-  };
-
-  private static class TestSSOCookieFederationProvider extends SSOCookieFederationFilter {
-    public String testConstructLoginURL(HttpServletRequest req) {
-      return constructLoginURL(req);
-    }
-    
-    public void setTokenService(JWTokenAuthority ts) {
-      authority = ts;
-    }
-  };
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/AbstractJWTFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/AbstractJWTFilterTest.java b/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/AbstractJWTFilterTest.java
new file mode 100644
index 0000000..503f323
--- /dev/null
+++ b/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/AbstractJWTFilterTest.java
@@ -0,0 +1,490 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.provider.federation;
+
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.security.AccessController;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.NoSuchAlgorithmException;
+import java.security.Principal;
+import java.security.cert.Certificate;
+import java.security.interfaces.RSAPrivateKey;
+import java.security.interfaces.RSAPublicKey;
+import java.text.MessageFormat;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Properties;
+import java.util.Date;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.knox.gateway.provider.federation.jwt.filter.AbstractJWTFilter;
+import org.apache.knox.gateway.provider.federation.jwt.filter.SSOCookieFederationFilter;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.apache.knox.gateway.services.security.impl.X509CertificateUtil;
+import org.apache.knox.gateway.services.security.token.JWTokenAuthority;
+import org.apache.knox.gateway.services.security.token.TokenServiceException;
+import org.apache.knox.gateway.services.security.token.impl.JWT;
+import org.apache.knox.gateway.services.security.token.impl.JWTToken;
+import org.easymock.EasyMock;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.nimbusds.jose.*;
+import com.nimbusds.jwt.JWTClaimsSet;
+import com.nimbusds.jwt.SignedJWT;
+import com.nimbusds.jose.crypto.RSASSASigner;
+import com.nimbusds.jose.util.Base64URL;
+
+public abstract class AbstractJWTFilterTest  {
+  private static final String SERVICE_URL = "https://localhost:8888/resource";
+  private static final String dnTemplate = "CN={0},OU=Test,O=Hadoop,L=Test,ST=Test,C=US";
+
+  protected AbstractJWTFilter handler = null;
+  protected RSAPublicKey publicKey = null;
+  protected RSAPrivateKey privateKey = null;
+  protected String pem = null;
+
+  protected abstract void setTokenOnRequest(HttpServletRequest request, SignedJWT jwt);
+  protected abstract void setGarbledTokenOnRequest(HttpServletRequest request, SignedJWT jwt);
+  protected abstract String getAudienceProperty();
+  protected abstract String getVerificationPemProperty();
+
+  private String buildDistinguishedName(String hostname) {
+    MessageFormat headerFormatter = new MessageFormat(dnTemplate);
+    String[] paramArray = new String[1];
+    paramArray[0] = hostname;
+    String dn = headerFormatter.format(paramArray);
+    return dn;
+  }
+
+  @Before
+  public void setup() throws Exception, NoSuchAlgorithmException {
+    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
+    kpg.initialize(2048);
+    KeyPair KPair = kpg.generateKeyPair();
+    String dn = buildDistinguishedName(InetAddress.getLocalHost().getHostName());
+    Certificate cert = X509CertificateUtil.generateCertificate(dn, KPair, 365, "SHA1withRSA");
+    byte[] data = cert.getEncoded();
+    Base64 encoder = new Base64( 76, "\n".getBytes( "ASCII" ) );
+    pem = new String(encoder.encodeToString( data ).getBytes( "ASCII" )).trim();
+
+    publicKey = (RSAPublicKey) KPair.getPublic();
+    privateKey = (RSAPrivateKey) KPair.getPrivate();
+  }
+
+  @After
+  public void teardown() throws Exception {
+    handler.destroy();
+  }
+  
+  @Test
+  public void testValidJWT() throws Exception {
+    try {
+      Properties props = getProperties();
+      handler.init(new TestFilterConfig(props));
+
+      SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 5000), privateKey, props);
+
+      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
+      setTokenOnRequest(request, jwt);
+      
+      EasyMock.expect(request.getRequestURL()).andReturn(
+          new StringBuffer(SERVICE_URL)).anyTimes();
+      EasyMock.expect(request.getQueryString()).andReturn(null);
+      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
+      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
+          SERVICE_URL);
+      EasyMock.replay(request);
+
+      TestFilterChain chain = new TestFilterChain();
+      handler.doFilter(request, response, chain);
+      Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == true);
+      Set<PrimaryPrincipal> principals = chain.subject.getPrincipals(PrimaryPrincipal.class);
+      Assert.assertTrue("No PrimaryPrincipal", principals.size() > 0);
+      Assert.assertEquals("Not the expected principal", "alice", ((Principal)principals.toArray()[0]).getName());
+    } catch (ServletException se) {
+      fail("Should NOT have thrown a ServletException.");
+    }
+  }
+  
+  @Test
+  public void testValidAudienceJWT() throws Exception {
+    try {
+      Properties props = getProperties();
+      props.put(getAudienceProperty(), "bar");
+      handler.init(new TestFilterConfig(props));
+
+      SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 5000), privateKey, props);
+
+      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
+      setTokenOnRequest(request, jwt);
+      
+      EasyMock.expect(request.getRequestURL()).andReturn(
+          new StringBuffer(SERVICE_URL)).anyTimes();
+      EasyMock.expect(request.getQueryString()).andReturn(null);
+      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
+      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
+          SERVICE_URL);
+      EasyMock.replay(request);
+
+      TestFilterChain chain = new TestFilterChain();
+      handler.doFilter(request, response, chain);
+      Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == true);
+      Set<PrimaryPrincipal> principals = chain.subject.getPrincipals(PrimaryPrincipal.class);
+      Assert.assertTrue("No PrimaryPrincipal", principals.size() > 0);
+      Assert.assertEquals("Not the expected principal", "alice", ((Principal)principals.toArray()[0]).getName());
+    } catch (ServletException se) {
+      fail("Should NOT have thrown a ServletException.");
+    }
+  }
+
+  @Test
+  public void testInvalidAudienceJWT() throws Exception {
+    try {
+      Properties props = getProperties();
+      props.put(getAudienceProperty(), "foo");
+      props.put("sso.authentication.provider.url", "https://localhost:8443/gateway/knoxsso/api/v1/websso");
+
+      handler.init(new TestFilterConfig(props));
+
+      SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 5000), privateKey, props);
+
+      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
+      setTokenOnRequest(request, jwt);
+      
+      EasyMock.expect(request.getRequestURL()).andReturn(
+          new StringBuffer(SERVICE_URL)).anyTimes();
+      EasyMock.expect(request.getQueryString()).andReturn(null);
+      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
+      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
+          SERVICE_URL);
+      EasyMock.replay(request);
+
+      TestFilterChain chain = new TestFilterChain();
+      handler.doFilter(request, response, chain);
+      Assert.assertTrue("doFilterCalled should not be true.", chain.doFilterCalled == false);
+      Assert.assertTrue("No Subject should be returned.", chain.subject == null);
+    } catch (ServletException se) {
+      fail("Should NOT have thrown a ServletException.");
+    }
+  }
+
+  @Test
+  public void testValidVerificationPEM() throws Exception {
+    try {
+      Properties props = getProperties();
+      
+//      System.out.println("+" + pem + "+");
+
+      props.put(getAudienceProperty(), "bar");
+      props.put("sso.authentication.provider.url", "https://localhost:8443/gateway/knoxsso/api/v1/websso");
+      props.put(getVerificationPemProperty(), pem);
+      handler.init(new TestFilterConfig(props));
+
+      SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 50000), privateKey, props);
+
+      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
+      setTokenOnRequest(request, jwt);
+
+      EasyMock.expect(request.getRequestURL()).andReturn(
+          new StringBuffer(SERVICE_URL)).anyTimes();
+      EasyMock.expect(request.getQueryString()).andReturn(null);
+      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
+      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
+          SERVICE_URL);
+      EasyMock.replay(request);
+
+      TestFilterChain chain = new TestFilterChain();
+      handler.doFilter(request, response, chain);
+      Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == true);
+      Set<PrimaryPrincipal> principals = chain.subject.getPrincipals(PrimaryPrincipal.class);
+      Assert.assertTrue("No PrimaryPrincipal", principals.size() > 0);
+      Assert.assertEquals("Not the expected principal", "alice", ((Principal)principals.toArray()[0]).getName());
+    } catch (ServletException se) {
+      fail("Should NOT have thrown a ServletException.");
+    }
+  }
+
+  @Test
+  public void testExpiredJWT() throws Exception {
+    try {
+      Properties props = getProperties();
+      handler.init(new TestFilterConfig(props));
+
+      SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() - 1000), privateKey, props);
+
+      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
+      setTokenOnRequest(request, jwt);
+      
+      EasyMock.expect(request.getRequestURL()).andReturn(
+          new StringBuffer(SERVICE_URL)).anyTimes();
+      EasyMock.expect(request.getQueryString()).andReturn(null);
+      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
+      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
+          SERVICE_URL);
+      EasyMock.replay(request);
+
+      TestFilterChain chain = new TestFilterChain();
+      handler.doFilter(request, response, chain);
+      Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == false);
+      Assert.assertTrue("No Subject should be returned.", chain.subject == null);
+    } catch (ServletException se) {
+      fail("Should NOT have thrown a ServletException.");
+    }
+  }
+  
+  @Test
+  public void testValidJWTNoExpiration() throws Exception {
+    try {
+      Properties props = getProperties();
+      handler.init(new TestFilterConfig(props));
+
+      SignedJWT jwt = getJWT("alice", null, privateKey, props);
+
+      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
+      setTokenOnRequest(request, jwt);
+      
+      EasyMock.expect(request.getRequestURL()).andReturn(
+          new StringBuffer(SERVICE_URL)).anyTimes();
+      EasyMock.expect(request.getQueryString()).andReturn(null);
+      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
+      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
+          SERVICE_URL).anyTimes();
+      EasyMock.replay(request);
+
+      TestFilterChain chain = new TestFilterChain();
+      handler.doFilter(request, response, chain);
+      Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == true);
+      Set<PrimaryPrincipal> principals = chain.subject.getPrincipals(PrimaryPrincipal.class);
+      Assert.assertTrue("No PrimaryPrincipal", principals.size() > 0);
+      Assert.assertEquals("Not the expected principal", "alice", ((Principal)principals.toArray()[0]).getName());
+    } catch (ServletException se) {
+      fail("Should NOT have thrown a ServletException.");
+    }
+  }
+  
+  @Test
+  public void testUnableToParseJWT() throws Exception {
+    try {
+      Properties props = getProperties();
+      handler.init(new TestFilterConfig(props));
+
+      SignedJWT jwt = getJWT("bob",new Date(new Date().getTime() + 5000), privateKey, props);
+
+      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
+      setGarbledTokenOnRequest(request, jwt);
+
+      EasyMock.expect(request.getRequestURL()).andReturn(
+          new StringBuffer(SERVICE_URL)).anyTimes();
+      EasyMock.expect(request.getQueryString()).andReturn(null);
+      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
+      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
+          SERVICE_URL).anyTimes();
+      EasyMock.replay(request);
+
+      TestFilterChain chain = new TestFilterChain();
+      handler.doFilter(request, response, chain);
+      Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == false);
+      Assert.assertTrue("No Subject should be returned.", chain.subject == null);
+    } catch (ServletException se) {
+      fail("Should NOT have thrown a ServletException.");
+    }
+  }
+
+  protected Properties getProperties() {
+    Properties props = new Properties();
+    props.setProperty(
+        SSOCookieFederationFilter.SSO_AUTHENTICATION_PROVIDER_URL,
+        "https://localhost:8443/authserver");
+    return props;
+  }
+
+  protected SignedJWT getJWT(String sub, Date expires, RSAPrivateKey privateKey,
+      Properties props) throws Exception {
+    List<String> aud = new ArrayList<String>();
+    aud.add("bar");
+
+    JWTClaimsSet claims = new JWTClaimsSet.Builder()
+    .issuer("KNOXSSO")
+    .subject(sub)
+    .audience(aud)
+    .expirationTime(expires)
+    .claim("scope", "openid")
+    .build();
+
+    JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).build();
+
+    SignedJWT signedJWT = new SignedJWT(header, claims);
+    Base64URL sigInput = Base64URL.encode(signedJWT.getSigningInput());
+    JWSSigner signer = new RSASSASigner(privateKey);
+
+    signedJWT.sign(signer);
+
+    return signedJWT;
+  }
+
+  protected static class TestFilterConfig implements FilterConfig {
+    Properties props = null;
+
+    public TestFilterConfig(Properties props) {
+      this.props = props;
+    }
+
+    @Override
+    public String getFilterName() {
+      return null;
+    }
+
+    /* (non-Javadoc)
+     * @see javax.servlet.FilterConfig#getServletContext()
+     */
+    @Override
+    public ServletContext getServletContext() {
+//      JWTokenAuthority authority = EasyMock.createNiceMock(JWTokenAuthority.class);
+//      GatewayServices services = EasyMock.createNiceMock(GatewayServices.class);
+//      EasyMock.expect(services.getService("TokenService").andReturn(authority));
+//      ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+//      EasyMock.expect(context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE).andReturn(new DefaultGatewayServices()));
+      return null;
+    }
+
+    /* (non-Javadoc)
+     * @see javax.servlet.FilterConfig#getInitParameter(java.lang.String)
+     */
+    @Override
+    public String getInitParameter(String name) {
+      return props.getProperty(name, null);
+    }
+
+    /* (non-Javadoc)
+     * @see javax.servlet.FilterConfig#getInitParameterNames()
+     */
+    @Override
+    public Enumeration<String> getInitParameterNames() {
+      return null;
+    }
+    
+  }
+  
+  protected static class TestJWTokenAuthority implements JWTokenAuthority {
+
+    /* (non-Javadoc)
+     * @see JWTokenAuthority#issueToken(javax.security.auth.Subject, java.lang.String)
+     */
+    @Override
+    public JWTToken issueToken(Subject subject, String algorithm)
+        throws TokenServiceException {
+      // TODO Auto-generated method stub
+      return null;
+    }
+
+    /* (non-Javadoc)
+     * @see JWTokenAuthority#issueToken(java.security.Principal, java.lang.String)
+     */
+    @Override
+    public JWTToken issueToken(Principal p, String algorithm)
+        throws TokenServiceException {
+      // TODO Auto-generated method stub
+      return null;
+    }
+
+    /* (non-Javadoc)
+     * @see JWTokenAuthority#issueToken(java.security.Principal, java.lang.String, java.lang.String)
+     */
+    @Override
+    public JWTToken issueToken(Principal p, String audience, String algorithm)
+        throws TokenServiceException {
+      return null;
+    }
+
+    /* (non-Javadoc)
+     * @see JWTokenAuthority#verifyToken(JWTToken)
+     */
+    @Override
+    public boolean verifyToken(JWTToken token) throws TokenServiceException {
+      return true;
+    }
+
+    /* (non-Javadoc)
+     * @see JWTokenAuthority#issueToken(java.security.Principal, java.lang.String, java.lang.String, long)
+     */
+    @Override
+    public JWTToken issueToken(Principal p, String audience, String algorithm,
+        long expires) throws TokenServiceException {
+      return null;
+    }
+
+    @Override
+    public JWTToken issueToken(Principal p, List<String> audiences, String algorithm,
+        long expires) throws TokenServiceException {
+      return null;
+    }
+
+    /* (non-Javadoc)
+     * @see JWTokenAuthority#issueToken(java.security.Principal, java.lang.String, long)
+     */
+    @Override
+    public JWT issueToken(Principal p, String audience, long l)
+        throws TokenServiceException {
+      // TODO Auto-generated method stub
+      return null;
+    }
+
+    @Override
+    public boolean verifyToken(JWTToken token, RSAPublicKey publicKey) throws TokenServiceException {
+      // TODO Auto-generated method stub
+      return true;
+    }
+    
+  }
+  
+  protected static class TestFilterChain implements FilterChain {
+    boolean doFilterCalled = false;
+    Subject subject = null;
+
+    /* (non-Javadoc)
+     * @see javax.servlet.FilterChain#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
+     */
+    @Override
+    public void doFilter(ServletRequest request, ServletResponse response)
+        throws IOException, ServletException {
+      doFilterCalled = true;
+      
+      subject = Subject.getSubject( AccessController.getContext() );
+    }
+    
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/JWTFederationFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/JWTFederationFilterTest.java b/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/JWTFederationFilterTest.java
new file mode 100644
index 0000000..14b704a
--- /dev/null
+++ b/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/JWTFederationFilterTest.java
@@ -0,0 +1,67 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.provider.federation;
+
+import java.security.NoSuchAlgorithmException;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.knox.gateway.provider.federation.jwt.filter.JWTFederationFilter;
+import org.apache.knox.gateway.services.security.token.JWTokenAuthority;
+import org.easymock.EasyMock;
+import org.junit.Before;
+
+import com.nimbusds.jwt.SignedJWT;
+
+public class JWTFederationFilterTest extends AbstractJWTFilterTest {
+    
+    @Before
+    public void setup() throws Exception, NoSuchAlgorithmException {
+      super.setup();
+      handler = new TestJWTFederationFilter();
+      ((TestJWTFederationFilter) handler).setTokenService(new TestJWTokenAuthority());
+    }
+    
+    protected void setTokenOnRequest(HttpServletRequest request, SignedJWT jwt) {
+      String token = "Bearer " + jwt.serialize();
+      EasyMock.expect(request.getHeader("Authorization")).andReturn(token);
+    }
+    
+    protected void setGarbledTokenOnRequest(HttpServletRequest request, SignedJWT jwt) {
+      String token = "Bearer " + "ljm" + jwt.serialize();
+      EasyMock.expect(request.getHeader("Authorization")).andReturn(token);
+    }
+
+    protected String getAudienceProperty() {
+      return TestJWTFederationFilter.KNOX_TOKEN_AUDIENCES;
+    }
+    
+    private static class TestJWTFederationFilter extends JWTFederationFilter {
+
+      public void setTokenService(JWTokenAuthority ts) {
+        authority = ts;
+      }
+        
+    }
+
+    @Override
+    protected String getVerificationPemProperty() {
+      return TestJWTFederationFilter.TOKEN_VERIFICATION_PEM;
+    };
+    
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/JWTTokenTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/JWTTokenTest.java b/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/JWTTokenTest.java
new file mode 100644
index 0000000..1f1973e
--- /dev/null
+++ b/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/JWTTokenTest.java
@@ -0,0 +1,133 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.provider.federation;
+
+import java.util.ArrayList;
+import junit.framework.TestCase;
+
+import org.apache.knox.gateway.services.security.token.impl.JWTToken;
+import org.junit.Test;
+
+public class JWTTokenTest extends TestCase {
+  private static final String JWT_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0MTY5MjkxMDksImp0aSI6ImFhN2Y4ZDBhOTVjIiwic2NvcGVzIjpbInJlcG8iLCJwdWJsaWNfcmVwbyJdfQ.XCEwpBGvOLma4TCoh36FU7XhUbcskygS81HE1uHLf0E";
+  private static final String HEADER = "{\"alg\":\"RS256\", \"type\":\"JWT\"}";
+  private static final String CLAIMS = "{\"iss\": \"gateway\", \"prn\": \"john.doe@example.com\", \"aud\": \"https://login.example.com\", \"exp\": \"1363360913\"}";
+  
+//  public void testTokenParsing() throws Exception {
+//    try {
+//      JWTToken token = JWTToken.parseToken(JWT_TOKEN);
+//      assertEquals(token.getHeader(), HEADER);
+//      assertEquals(token.getClaims(), CLAIMS);
+//      
+//      assertEquals(token.getIssuer(), "gateway");
+//      assertEquals(token.getPrincipal(), "john.doe@example.com");
+//      assertEquals(token.getAudience(), "https://login.example.com");
+//      assertEquals(token.getExpires(), "1363360913");
+//    }
+//    catch (ParseException pe) {
+//      fail("ParseException encountered.");
+//    }
+//  }
+  
+  @Test
+  public void testTokenCreation() throws Exception {
+    String[] claims = new String[4];
+    claims[0] = "KNOXSSO";
+    claims[1] = "john.doe@example.com";
+    claims[2] = "https://login.example.com";
+    claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
+    JWTToken token = new JWTToken("RS256", claims);
+
+    assertEquals("KNOXSSO", token.getIssuer());
+    assertEquals("john.doe@example.com", token.getSubject());
+    assertEquals("https://login.example.com", token.getAudience());
+  }
+
+  @Test
+  public void testTokenCreationWithAudienceListSingle() throws Exception {
+    String[] claims = new String[4];
+    claims[0] = "KNOXSSO";
+    claims[1] = "john.doe@example.com";
+    claims[2] = null;
+    claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
+    ArrayList<String> audiences = new ArrayList<String>();
+    audiences.add("https://login.example.com");
+
+    JWTToken token = new JWTToken("RS256", claims, audiences);
+
+    assertEquals("KNOXSSO", token.getIssuer());
+    assertEquals("john.doe@example.com", token.getSubject());
+    assertEquals("https://login.example.com", token.getAudience());
+    assertEquals(1, token.getAudienceClaims().length);
+  }
+
+  @Test
+  public void testTokenCreationWithAudienceListMultiple() throws Exception {
+    String[] claims = new String[4];
+    claims[0] = "KNOXSSO";
+    claims[1] = "john.doe@example.com";
+    claims[2] = null;
+    claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
+    ArrayList<String> audiences = new ArrayList<String>();
+    audiences.add("https://login.example.com");
+    audiences.add("KNOXSSO");
+
+    JWTToken token = new JWTToken("RS256", claims, audiences);
+
+    assertEquals("KNOXSSO", token.getIssuer());
+    assertEquals("john.doe@example.com", token.getSubject());
+    assertEquals("https://login.example.com", token.getAudience());
+    assertEquals(2, token.getAudienceClaims().length);
+  }
+
+  @Test
+  public void testTokenCreationWithAudienceListCombined() throws Exception {
+    String[] claims = new String[4];
+    claims[0] = "KNOXSSO";
+    claims[1] = "john.doe@example.com";
+    claims[2] = "LJM";
+    claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
+    ArrayList<String> audiences = new ArrayList<String>();
+    audiences.add("https://login.example.com");
+    audiences.add("KNOXSSO");
+
+    JWTToken token = new JWTToken("RS256", claims, audiences);
+
+    assertEquals("KNOXSSO", token.getIssuer());
+    assertEquals("john.doe@example.com", token.getSubject());
+    assertEquals("https://login.example.com", token.getAudience());
+    assertEquals(3, token.getAudienceClaims().length);
+  }
+
+  @Test
+  public void testTokenCreationWithNullAudienceList() throws Exception {
+    String[] claims = new String[4];
+    claims[0] = "KNOXSSO";
+    claims[1] = "john.doe@example.com";
+    claims[2] = null;
+    claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
+    ArrayList<String> audiences = null;
+
+    JWTToken token = new JWTToken("RS256", claims, audiences);
+
+    assertEquals("KNOXSSO", token.getIssuer());
+    assertEquals("john.doe@example.com", token.getSubject());
+    assertEquals(null, token.getAudience());
+    assertEquals(null, token.getAudienceClaims());
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/SSOCookieProviderTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/SSOCookieProviderTest.java b/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/SSOCookieProviderTest.java
new file mode 100644
index 0000000..fa0e785
--- /dev/null
+++ b/gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/SSOCookieProviderTest.java
@@ -0,0 +1,205 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.provider.federation;
+
+import static org.junit.Assert.fail;
+
+import java.security.NoSuchAlgorithmException;
+import java.security.Principal;
+import java.util.Properties;
+import java.util.Date;
+import java.util.Set;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.provider.federation.jwt.filter.SSOCookieFederationFilter;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.apache.knox.gateway.services.security.token.JWTokenAuthority;
+import org.easymock.EasyMock;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.nimbusds.jwt.SignedJWT;
+
+public class SSOCookieProviderTest extends AbstractJWTFilterTest {
+  private static final String SERVICE_URL = "https://localhost:8888/resource";
+  private static final String REDIRECT_LOCATION =
+      "https://localhost:8443/authserver?originalUrl=" + SERVICE_URL;
+  
+  @Before
+  public void setup() throws Exception, NoSuchAlgorithmException {
+    super.setup();
+    handler = new TestSSOCookieFederationProvider();
+    ((TestSSOCookieFederationProvider) handler).setTokenService(new TestJWTokenAuthority());
+  }
+  
+  protected void setTokenOnRequest(HttpServletRequest request, SignedJWT jwt) {
+    Cookie cookie = new Cookie("hadoop-jwt", jwt.serialize());
+    EasyMock.expect(request.getCookies()).andReturn(new Cookie[] { cookie });
+  }
+  
+  protected void setGarbledTokenOnRequest(HttpServletRequest request, SignedJWT jwt) {
+    Cookie cookie = new Cookie("hadoop-jwt", "ljm" + jwt.serialize());
+    EasyMock.expect(request.getCookies()).andReturn(new Cookie[] { cookie });
+  }
+
+  protected String getAudienceProperty() {
+    return TestSSOCookieFederationProvider.SSO_EXPECTED_AUDIENCES;
+  }
+  
+  @Test
+  public void testCustomCookieNameJWT() throws Exception {
+    try {
+      Properties props = getProperties();
+      props.put("sso.cookie.name", "jowt");
+      handler.init(new TestFilterConfig(props));
+
+      SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 5000),
+          privateKey, props);
+
+      Cookie cookie = new Cookie("jowt", jwt.serialize());
+      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
+      EasyMock.expect(request.getCookies()).andReturn(new Cookie[] { cookie });
+      EasyMock.expect(request.getRequestURL()).andReturn(
+          new StringBuffer(SERVICE_URL)).anyTimes();
+      EasyMock.expect(request.getQueryString()).andReturn(null);
+      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
+      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
+          SERVICE_URL);
+      EasyMock.replay(request);
+
+      TestFilterChain chain = new TestFilterChain();
+      handler.doFilter(request, response, chain);
+      Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == true);
+      Set<PrimaryPrincipal> principals = chain.subject.getPrincipals(PrimaryPrincipal.class);
+      Assert.assertTrue("No PrimaryPrincipal returned.", principals.size() > 0);
+      Assert.assertEquals("Not the expected principal", "alice", ((Principal)principals.toArray()[0]).getName());
+    } catch (ServletException se) {
+      fail("Should NOT have thrown a ServletException.");
+    }
+  }
+
+  @Test
+  public void testNoProviderURLJWT() throws Exception {
+    try {
+      Properties props = getProperties();
+      props.remove("sso.authentication.provider.url");
+      handler.init(new TestFilterConfig(props));
+
+      fail("Servlet exception should have been thrown.");
+
+    } catch (ServletException se) {
+      // expected - let's ensure it mentions the missing authentication provider URL
+      se.getMessage().contains("authentication provider URL is missing");
+    }
+  }
+  
+/*
+  @Test
+  public void testFailedSignatureValidationJWT() throws Exception {
+    try {
+
+      // Create a public key that doesn't match the one needed to
+      // verify the signature - in order to make it fail verification...
+      KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
+      kpg.initialize(2048);
+
+      KeyPair kp = kpg.genKeyPair();
+      RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();
+
+      handler.setPublicKey(publicKey);
+
+      Properties props = getProperties();
+      handler.init(props);
+
+      SignedJWT jwt = getJWT("bob", new Date(new Date().getTime() + 5000),
+          privateKey);
+
+      Cookie cookie = new Cookie("hadoop-jwt", jwt.serialize());
+      HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
+      Mockito.when(request.getCookies()).thenReturn(new Cookie[] { cookie });
+      Mockito.when(request.getRequestURL()).thenReturn(
+          new StringBuffer(SERVICE_URL)).anyTimes();
+      HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
+      Mockito.when(response.encodeRedirectURL(SERVICE_URL)).thenReturn(
+          SERVICE_URL);
+
+      AuthenticationToken token = handler.alternateAuthenticate(request,
+          response);
+      Mockito.verify(response).sendRedirect(REDIRECT_LOCATION);
+    } catch (ServletException se) {
+      fail("alternateAuthentication should NOT have thrown a ServletException");
+    } catch (AuthenticationException ae) {
+      fail("alternateAuthentication should NOT have thrown a AuthenticationException");
+    }
+  }
+*/
+
+  @Test
+  public void testOrigURLWithQueryString() throws Exception {
+    Properties props = getProperties();
+    handler.init(new TestFilterConfig(props));
+
+    HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
+    EasyMock.expect(request.getRequestURL()).andReturn(
+        new StringBuffer(SERVICE_URL)).anyTimes();
+    EasyMock.expect(request.getQueryString()).andReturn("name=value");
+    EasyMock.replay(request);
+
+    String loginURL = ((TestSSOCookieFederationProvider)handler).testConstructLoginURL(request);
+    Assert.assertNotNull("loginURL should not be null.", loginURL);
+    Assert.assertEquals("https://localhost:8443/authserver?originalUrl=" + SERVICE_URL + "?name=value", loginURL);
+  }
+
+  @Test
+  public void testOrigURLNoQueryString() throws Exception {
+    Properties props = getProperties();
+    handler.init(new TestFilterConfig(props));
+
+    HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
+    EasyMock.expect(request.getRequestURL()).andReturn(
+        new StringBuffer(SERVICE_URL)).anyTimes();
+    EasyMock.expect(request.getQueryString()).andReturn(null);
+    EasyMock.replay(request);
+
+    String loginURL = ((TestSSOCookieFederationProvider)handler).testConstructLoginURL(request);
+    Assert.assertNotNull("LoginURL should not be null.", loginURL);
+    Assert.assertEquals("https://localhost:8443/authserver?originalUrl=" + SERVICE_URL, loginURL);
+  }
+  
+
+  @Override
+  protected String getVerificationPemProperty() {
+    return SSOCookieFederationFilter.SSO_VERIFICATION_PEM;
+  };
+
+  private static class TestSSOCookieFederationProvider extends SSOCookieFederationFilter {
+    public String testConstructLoginURL(HttpServletRequest req) {
+      return constructLoginURL(req);
+    }
+    
+    public void setTokenService(JWTokenAuthority ts) {
+      authority = ts;
+    }
+  };
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/Pac4jMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/Pac4jMessages.java b/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/Pac4jMessages.java
deleted file mode 100644
index 931e494..0000000
--- a/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/Pac4jMessages.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.hadoop.gateway.pac4j;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-
-/**
- * Logging messages for the pac4j provider.
- *
- * @since 0.8.0
- */
-@Messages(logger="org.apache.hadoop.gateway.pac4j")
-public interface Pac4jMessages {
-
-  @Message( level = MessageLevel.ERROR, text = "pac4j callback URL required")
-  public void ssoAuthenticationProviderUrlRequired();
-
-  @Message( level = MessageLevel.ERROR, text = "pac4j clientName parameter required")
-  public void clientNameParameterRequired();
-
-  @Message( level = MessageLevel.ERROR, text = "At least one pac4j client must be defined")
-  public void atLeastOnePac4jClientMustBeDefined();
-
-  @Message( level = MessageLevel.ERROR, text = "Crypto service, alias service and cluster name required")
-  public void cryptoServiceAndAliasServiceAndClusterNameRequired();
-
-  @Message( level = MessageLevel.ERROR, text = "Unable to generate a password for encryption")
-  public void unableToGenerateAPasswordForEncryption(Exception e);
-
-  @Message( level = MessageLevel.INFO, text = 
-      "No private key passphrase alias found. Defaulting to master. Exception encountered: {0}")
-  public void noPrivateKeyPasshraseProvisioned(Exception e);
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/deploy/Pac4jFederationProviderContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/deploy/Pac4jFederationProviderContributor.java b/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/deploy/Pac4jFederationProviderContributor.java
deleted file mode 100644
index c673ed5..0000000
--- a/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/deploy/Pac4jFederationProviderContributor.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.hadoop.gateway.pac4j.deploy;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-/**
- * Descriptor of the pac4j provider. This module must be deployed for the KnoxSSO service.
- *
- * @since 0.8.0
- */
-public class Pac4jFederationProviderContributor extends ProviderDeploymentContributorBase {
-
-  private static final String ROLE = "federation";
-  private static final String NAME = "pac4j";
-  private static final String DISPATCHER_FILTER_CLASSNAME = "org.apache.hadoop.gateway.pac4j.filter.Pac4jDispatcherFilter";
-  private static final String IDENTITY_ADAPTER_CLASSNAME = "org.apache.hadoop.gateway.pac4j.filter.Pac4jIdentityAdapter";
-
-  @Override
-  public String getRole() {
-    return ROLE;
-  }
-
-  @Override
-  public String getName() {
-    return NAME;
-  }
-  
-  @Override
-  public void initializeContribution(DeploymentContext context) {
-    super.initializeContribution(context);
-  }
-
-  @Override
-  public void contributeProvider(DeploymentContext context, Provider provider) {
-  }
-
-  @Override
-  public void contributeFilter(DeploymentContext context, Provider provider, Service service, 
-      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
-    // blindly add all the provider params as filter init params
-    if (params == null) {
-      params = new ArrayList<FilterParamDescriptor>();
-    }
-    Map<String, String> providerParams = provider.getParams();
-    for(Entry<String, String> entry : providerParams.entrySet()) {
-      params.add( resource.createFilterParam().name( entry.getKey() ).value( entry.getValue() ) );
-    }
-    resource.addFilter().name( getName() ).role( getRole() ).impl( DISPATCHER_FILTER_CLASSNAME ).params( params );
-    resource.addFilter().name( getName() ).role( getRole() ).impl( IDENTITY_ADAPTER_CLASSNAME ).params( params );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/filter/Pac4jDispatcherFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/filter/Pac4jDispatcherFilter.java b/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/filter/Pac4jDispatcherFilter.java
deleted file mode 100644
index 574dea5..0000000
--- a/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/filter/Pac4jDispatcherFilter.java
+++ /dev/null
@@ -1,215 +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.hadoop.gateway.pac4j.filter;
-
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.pac4j.Pac4jMessages;
-import org.apache.hadoop.gateway.pac4j.session.KnoxSessionStore;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.security.KeystoreService;
-import org.apache.hadoop.gateway.services.security.MasterService;
-import org.apache.hadoop.gateway.services.security.AliasService;
-import org.apache.hadoop.gateway.services.security.AliasServiceException;
-import org.apache.hadoop.gateway.services.security.CryptoService;
-import org.pac4j.config.client.PropertiesConfigFactory;
-import org.pac4j.core.client.Client;
-import org.pac4j.core.config.Config;
-import org.pac4j.core.config.ConfigSingleton;
-import org.pac4j.core.context.J2EContext;
-import org.pac4j.core.context.Pac4jConstants;
-import org.pac4j.core.util.CommonHelper;
-import org.pac4j.http.client.indirect.IndirectBasicAuthClient;
-import org.pac4j.http.credentials.authenticator.test.SimpleTestUsernamePasswordAuthenticator;
-import org.pac4j.j2e.filter.CallbackFilter;
-import org.pac4j.j2e.filter.RequiresAuthenticationFilter;
-
-import javax.servlet.*;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * <p>This is the main filter for the pac4j provider. The pac4j provider module heavily relies on the j2e-pac4j library (https://github.com/pac4j/j2e-pac4j).</p>
- * <p>This filter dispatches the HTTP calls between the j2e-pac4j filters:</p>
- * <ul>
- *     <li>to the {@link CallbackFilter} if the <code>client_name</code> parameter exists: it finishes the authentication process</li>
- *     <li>to the {@link RequiresAuthenticationFilter} otherwise: it starts the authentication process (redirection to the identity provider) if the user is not authenticated</li>
- * </ul>
- * <p>It uses the {@link KnoxSessionStore} to manage session data. The generated cookies are defined on a domain name
- * which can be configured via the domain suffix parameter: <code>pac4j.cookie.domain.suffix</code>.</p>
- * <p>The callback url must be defined to the current protected url (KnoxSSO service for example) via the parameter: <code>pac4j.callbackUrl</code>.</p>
- *
- * @since 0.8.0
- */
-public class Pac4jDispatcherFilter implements Filter {
-
-  private static Pac4jMessages log = MessagesFactory.get(Pac4jMessages.class);
-
-  public static final String TEST_BASIC_AUTH = "testBasicAuth";
-
-  public static final String PAC4J_CALLBACK_URL = "pac4j.callbackUrl";
-
-  public static final String PAC4J_CALLBACK_PARAMETER = "pac4jCallback";
-
-  private static final String PAC4J_COOKIE_DOMAIN_SUFFIX_PARAM = "pac4j.cookie.domain.suffix";
-
-  private CallbackFilter callbackFilter;
-
-  private RequiresAuthenticationFilter requiresAuthenticationFilter;
-  private MasterService masterService = null;
-  private KeystoreService keystoreService = null;
-  private AliasService aliasService = null;
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-    // JWT service
-    final ServletContext context = filterConfig.getServletContext();
-    CryptoService cryptoService = null;
-    String clusterName = null;
-    if (context != null) {
-      GatewayServices services = (GatewayServices) context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
-      clusterName = (String) context.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE);
-      if (services != null) {
-        keystoreService = (KeystoreService) services.getService(GatewayServices.KEYSTORE_SERVICE);
-        cryptoService = (CryptoService) services.getService(GatewayServices.CRYPTO_SERVICE);
-        aliasService = (AliasService) services.getService(GatewayServices.ALIAS_SERVICE);
-        masterService = (MasterService) services.getService("MasterService");
-      }
-    }
-    // crypto service, alias service and cluster name are mandatory
-    if (cryptoService == null || aliasService == null || clusterName == null) {
-      log.cryptoServiceAndAliasServiceAndClusterNameRequired();
-      throw new ServletException("The crypto service, alias service and cluster name are required.");
-    }
-    try {
-      aliasService.getPasswordFromAliasForCluster(clusterName, KnoxSessionStore.PAC4J_PASSWORD, true);
-    } catch (AliasServiceException e) {
-      log.unableToGenerateAPasswordForEncryption(e);
-      throw new ServletException("Unable to generate a password for encryption.");
-    }
-
-    // url to SSO authentication provider
-    String pac4jCallbackUrl = filterConfig.getInitParameter(PAC4J_CALLBACK_URL);
-    if (pac4jCallbackUrl == null) {
-      log.ssoAuthenticationProviderUrlRequired();
-      throw new ServletException("Required pac4j callback URL is missing.");
-    }
-    // add the callback parameter to know it's a callback
-    pac4jCallbackUrl = CommonHelper.addParameter(pac4jCallbackUrl, PAC4J_CALLBACK_PARAMETER, "true");
-
-    final Config config;
-    final String clientName;
-    // client name from servlet parameter (mandatory)
-    final String clientNameParameter = filterConfig.getInitParameter(Pac4jConstants.CLIENT_NAME);
-    if (clientNameParameter == null) {
-      log.clientNameParameterRequired();
-      throw new ServletException("Required pac4j clientName parameter is missing.");
-    }
-    if (TEST_BASIC_AUTH.equalsIgnoreCase(clientNameParameter)) {
-      // test configuration
-      final IndirectBasicAuthClient indirectBasicAuthClient = new IndirectBasicAuthClient(new SimpleTestUsernamePasswordAuthenticator());
-      indirectBasicAuthClient.setRealmName("Knox TEST");
-      config = new Config(pac4jCallbackUrl, indirectBasicAuthClient);
-      clientName = "IndirectBasicAuthClient";
-    } else {
-      // get clients from the init parameters
-      final Map<String, String> properties = new HashMap<>();
-      final Enumeration<String> names = filterConfig.getInitParameterNames();
-      addDefaultConfig(clientNameParameter, properties);
-      while (names.hasMoreElements()) {
-        final String key = names.nextElement();
-        properties.put(key, filterConfig.getInitParameter(key));
-      }
-      final PropertiesConfigFactory propertiesConfigFactory = new PropertiesConfigFactory(pac4jCallbackUrl, properties);
-      config = propertiesConfigFactory.build();
-      final List<Client> clients = config.getClients().getClients();
-      if (clients == null || clients.size() == 0) {
-        log.atLeastOnePac4jClientMustBeDefined();
-        throw new ServletException("At least one pac4j client must be defined.");
-      }
-      if (CommonHelper.isBlank(clientNameParameter)) {
-        clientName = clients.get(0).getName();
-      } else {
-        clientName = clientNameParameter;
-      }
-    }
-
-    callbackFilter = new CallbackFilter();
-    requiresAuthenticationFilter = new RequiresAuthenticationFilter();
-    requiresAuthenticationFilter.setClientName(clientName);
-    requiresAuthenticationFilter.setConfig(config);
-
-    final String domainSuffix = filterConfig.getInitParameter(PAC4J_COOKIE_DOMAIN_SUFFIX_PARAM);
-    config.setSessionStore(new KnoxSessionStore(cryptoService, clusterName, domainSuffix));
-    ConfigSingleton.setConfig(config);
-  }
-
-  private void addDefaultConfig(String clientNameParameter, Map<String, String> properties) {
-    // add default saml params
-    if (clientNameParameter.contains("SAML2Client")) {
-      properties.put(PropertiesConfigFactory.SAML_KEYSTORE_PATH,
-          keystoreService.getKeystorePath());
-
-      properties.put(PropertiesConfigFactory.SAML_KEYSTORE_PASSWORD,
-          new String(masterService.getMasterSecret()));
-
-      // check for provisioned alias for private key
-      char[] gip = null;
-      try {
-        gip = aliasService.getGatewayIdentityPassphrase();
-      }
-      catch(AliasServiceException ase) {
-        log.noPrivateKeyPasshraseProvisioned(ase);
-      }
-      if (gip != null) {
-        properties.put(PropertiesConfigFactory.SAML_PRIVATE_KEY_PASSWORD,
-            new String(gip));
-      }
-      else {
-        // no alias provisioned then use the master
-        properties.put(PropertiesConfigFactory.SAML_PRIVATE_KEY_PASSWORD,
-            new String(masterService.getMasterSecret()));
-      }
-    }
-  }
-
-  @Override
-  public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
-
-    final HttpServletRequest request = (HttpServletRequest) servletRequest;
-    final HttpServletResponse response = (HttpServletResponse) servletResponse;
-    final J2EContext context = new J2EContext(request, response, ConfigSingleton.getConfig().getSessionStore());
-
-    // it's a callback from an identity provider
-    if (request.getParameter(PAC4J_CALLBACK_PARAMETER) != null) {
-      // apply CallbackFilter
-      callbackFilter.doFilter(servletRequest, servletResponse, filterChain);
-    } else {
-      // otherwise just apply security and requires authentication
-      // apply RequiresAuthenticationFilter
-      requiresAuthenticationFilter.doFilter(servletRequest, servletResponse, filterChain);
-    }
-  }
-
-  @Override
-  public void destroy() { }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/filter/Pac4jIdentityAdapter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/filter/Pac4jIdentityAdapter.java b/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/filter/Pac4jIdentityAdapter.java
deleted file mode 100644
index ec5c368..0000000
--- a/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/filter/Pac4jIdentityAdapter.java
+++ /dev/null
@@ -1,132 +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.hadoop.gateway.pac4j.filter;
-
-import org.apache.hadoop.gateway.audit.api.*;
-import org.apache.hadoop.gateway.audit.log4j.audit.AuditConstants;
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.pac4j.core.config.ConfigSingleton;
-import org.pac4j.core.context.J2EContext;
-import org.pac4j.core.profile.ProfileManager;
-import org.pac4j.core.profile.UserProfile;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.security.auth.Subject;
-import javax.servlet.*;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-
-/**
- * <p>This filter retrieves the authenticated user saved by the pac4j provider and injects it into the J2E HTTP request.</p>
- *
- * @since 0.8.0
- */
-public class Pac4jIdentityAdapter implements Filter {
-
-  private static final Logger logger = LoggerFactory.getLogger(Pac4jIdentityAdapter.class);
-
-  private static AuditService auditService = AuditServiceFactory.getAuditService();
-  private static Auditor auditor = auditService.getAuditor(
-      AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
-      AuditConstants.KNOX_COMPONENT_NAME );
-
-  private String testIdentifier;
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-  }
-
-  public void destroy() {
-  }
-
-  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
-      throws IOException, ServletException {
-
-    final HttpServletRequest request = (HttpServletRequest) servletRequest;
-    final HttpServletResponse response = (HttpServletResponse) servletResponse;
-    final J2EContext context = new J2EContext(request, response, ConfigSingleton.getConfig().getSessionStore());
-    final ProfileManager manager = new ProfileManager(context);
-    final UserProfile profile = manager.get(true);
-    logger.debug("User authenticated as: {}", profile);
-    manager.remove(true);
-    final String id = profile.getId();
-    testIdentifier = id;
-    PrimaryPrincipal pp = new PrimaryPrincipal(id);
-    Subject subject = new Subject();
-    subject.getPrincipals().add(pp);
-    auditService.getContext().setUsername(id);
-    String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
-    auditor.audit(Action.AUTHENTICATION, sourceUri, ResourceType.URI, ActionOutcome.SUCCESS);
-    
-    doAs(request, response, chain, subject);
-  }
-  
-  private void doAs(final ServletRequest request,
-      final ServletResponse response, final FilterChain chain, Subject subject)
-      throws IOException, ServletException {
-    try {
-      Subject.doAs(
-          subject,
-          new PrivilegedExceptionAction<Object>() {
-            public Object run() throws Exception {
-              chain.doFilter(request, response);
-              return null;
-            }
-          }
-          );
-    }
-    catch (PrivilegedActionException e) {
-      Throwable t = e.getCause();
-      if (t instanceof IOException) {
-        throw (IOException) t;
-      }
-      else if (t instanceof ServletException) {
-        throw (ServletException) t;
-      }
-      else {
-        throw new ServletException(t);
-      }
-    }
-  }
-
-  /**
-   * For tests only.
-   */
-  public static void setAuditService(AuditService auditService) {
-    Pac4jIdentityAdapter.auditService = auditService;
-  }
-
-  /**
-   * For tests only.
-   */
-  public static void setAuditor(Auditor auditor) {
-    Pac4jIdentityAdapter.auditor = auditor;
-  }
-
-  /**
-   * For tests only.
-     */
-  public String getTestIdentifier() {
-    return testIdentifier;
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/session/KnoxSessionStore.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/session/KnoxSessionStore.java b/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/session/KnoxSessionStore.java
deleted file mode 100644
index 1d7c567..0000000
--- a/gateway-provider-security-pac4j/src/main/java/org/apache/hadoop/gateway/pac4j/session/KnoxSessionStore.java
+++ /dev/null
@@ -1,120 +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.hadoop.gateway.pac4j.session;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.hadoop.gateway.services.security.CryptoService;
-import org.apache.hadoop.gateway.services.security.EncryptionResult;
-import org.apache.hadoop.gateway.util.Urls;
-import org.pac4j.core.context.ContextHelper;
-import org.pac4j.core.context.Cookie;
-import org.pac4j.core.context.WebContext;
-import org.pac4j.core.context.session.SessionStore;
-import org.pac4j.core.exception.TechnicalException;
-import org.pac4j.core.util.JavaSerializationHelper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.Serializable;
-
-/**
- * Specific session store where data are saved into cookies (and not in memory).
- * Each data is encrypted and base64 encoded before being saved as a cookie (for security reasons).
- *
- * @since 0.8.0
- */
-public class KnoxSessionStore implements SessionStore {
-
-    private static final Logger logger = LoggerFactory.getLogger(KnoxSessionStore.class);
-
-    public static final String PAC4J_PASSWORD = "pac4j.password";
-
-    public static final String PAC4J_SESSION_PREFIX = "pac4j.session.";
-
-    private final JavaSerializationHelper javaSerializationHelper;
-
-    private final CryptoService cryptoService;
-
-    private final String clusterName;
-
-    private final String domainSuffix;
-
-    public KnoxSessionStore(final CryptoService cryptoService, final String clusterName, final String domainSuffix) {
-        javaSerializationHelper = new JavaSerializationHelper();
-        this.cryptoService = cryptoService;
-        this.clusterName = clusterName;
-        this.domainSuffix = domainSuffix;
-    }
-
-    public String getOrCreateSessionId(WebContext context) {
-        return null;
-    }
-
-    private Serializable decryptBase64(final String v) {
-        if (v != null && v.length() > 0) {
-            byte[] bytes = Base64.decodeBase64(v);
-            EncryptionResult result = EncryptionResult.fromByteArray(bytes);
-            byte[] clear = cryptoService.decryptForCluster(this.clusterName,
-                    PAC4J_PASSWORD,
-                    result.cipher,
-                    result.iv,
-                    result.salt);
-            if (clear != null) {
-                return javaSerializationHelper.unserializeFromBytes(clear);
-            }
-        }
-        return null;
-    }
-
-    public Object get(WebContext context, String key) {
-        final Cookie cookie = ContextHelper.getCookie(context, PAC4J_SESSION_PREFIX + key);
-        Object value = null;
-        if (cookie != null) {
-            value = decryptBase64(cookie.getValue());
-        }
-        logger.debug("Get from session: {} = {}", key, value);
-        return value;
-    }
-
-    private String encryptBase64(final Object o) {
-        if (o == null || o.equals("")) {
-            return null;
-        } else {
-            final byte[] bytes = javaSerializationHelper.serializeToBytes((Serializable) o);
-            EncryptionResult result = cryptoService.encryptForCluster(this.clusterName, PAC4J_PASSWORD, bytes);
-            return Base64.encodeBase64String(result.toByteAray());
-        }
-    }
-
-    public void set(WebContext context, String key, Object value) {
-        logger.debug("Save in session: {} = {}", key, value);
-        final Cookie cookie = new Cookie(PAC4J_SESSION_PREFIX + key, encryptBase64(value));
-        try {
-            String domain = Urls.getDomainName(context.getFullRequestURL(), this.domainSuffix);
-            if (domain == null) {
-                domain = context.getServerName();
-            }
-            cookie.setDomain(domain);
-        } catch (final Exception e) {
-            throw new TechnicalException(e);
-        }
-        cookie.setHttpOnly(true);
-        cookie.setSecure(ContextHelper.isHttpsOrSecure(context));
-        context.addResponseCookie(cookie);
-    }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/Pac4jMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/Pac4jMessages.java b/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/Pac4jMessages.java
new file mode 100644
index 0000000..32e07e6
--- /dev/null
+++ b/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/Pac4jMessages.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.knox.gateway.pac4j;
+
+import org.apache.knox.gateway.i18n.messages.Message;
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.Messages;
+
+/**
+ * Logging messages for the pac4j provider.
+ *
+ * @since 0.8.0
+ */
+@Messages(logger="org.apache.hadoop.gateway.pac4j")
+public interface Pac4jMessages {
+
+  @Message( level = MessageLevel.ERROR, text = "pac4j callback URL required")
+  public void ssoAuthenticationProviderUrlRequired();
+
+  @Message( level = MessageLevel.ERROR, text = "pac4j clientName parameter required")
+  public void clientNameParameterRequired();
+
+  @Message( level = MessageLevel.ERROR, text = "At least one pac4j client must be defined")
+  public void atLeastOnePac4jClientMustBeDefined();
+
+  @Message( level = MessageLevel.ERROR, text = "Crypto service, alias service and cluster name required")
+  public void cryptoServiceAndAliasServiceAndClusterNameRequired();
+
+  @Message( level = MessageLevel.ERROR, text = "Unable to generate a password for encryption")
+  public void unableToGenerateAPasswordForEncryption(Exception e);
+
+  @Message( level = MessageLevel.INFO, text = 
+      "No private key passphrase alias found. Defaulting to master. Exception encountered: {0}")
+  public void noPrivateKeyPasshraseProvisioned(Exception e);
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/deploy/Pac4jFederationProviderContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/deploy/Pac4jFederationProviderContributor.java b/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/deploy/Pac4jFederationProviderContributor.java
new file mode 100644
index 0000000..f027dd3
--- /dev/null
+++ b/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/deploy/Pac4jFederationProviderContributor.java
@@ -0,0 +1,78 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.pac4j.deploy;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+/**
+ * Descriptor of the pac4j provider. This module must be deployed for the KnoxSSO service.
+ *
+ * @since 0.8.0
+ */
+public class Pac4jFederationProviderContributor extends
+    ProviderDeploymentContributorBase {
+
+  private static final String ROLE = "federation";
+  private static final String NAME = "pac4j";
+  private static final String DISPATCHER_FILTER_CLASSNAME = "Pac4jDispatcherFilter";
+  private static final String IDENTITY_ADAPTER_CLASSNAME = "Pac4jIdentityAdapter";
+
+  @Override
+  public String getRole() {
+    return ROLE;
+  }
+
+  @Override
+  public String getName() {
+    return NAME;
+  }
+  
+  @Override
+  public void initializeContribution(DeploymentContext context) {
+    super.initializeContribution(context);
+  }
+
+  @Override
+  public void contributeProvider(DeploymentContext context, Provider provider) {
+  }
+
+  @Override
+  public void contributeFilter(DeploymentContext context, Provider provider, Service service,
+      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
+    // blindly add all the provider params as filter init params
+    if (params == null) {
+      params = new ArrayList<FilterParamDescriptor>();
+    }
+    Map<String, String> providerParams = provider.getParams();
+    for(Entry<String, String> entry : providerParams.entrySet()) {
+      params.add( resource.createFilterParam().name( entry.getKey() ).value( entry.getValue() ) );
+    }
+    resource.addFilter().name( getName() ).role( getRole() ).impl( DISPATCHER_FILTER_CLASSNAME ).params( params );
+    resource.addFilter().name( getName() ).role( getRole() ).impl( IDENTITY_ADAPTER_CLASSNAME ).params( params );
+  }
+}


[52/64] knox git commit: KNOX-1003 - Fix the rewrite rules for Zeppelin 0.7.2 UI

Posted by mo...@apache.org.
KNOX-1003 - Fix the rewrite rules for Zeppelin 0.7.2 UI


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

Branch: refs/heads/KNOX-998-Package_Restructuring
Commit: bea3974a89bbe2dd83be26f3e94e2c9cea0bba31
Parents: 1159135
Author: Sandeep More <mo...@apache.org>
Authored: Thu Aug 24 16:43:27 2017 -0400
Committer: Sandeep More <mo...@apache.org>
Committed: Thu Aug 24 16:43:27 2017 -0400

----------------------------------------------------------------------
 .../src/main/resources/services/zeppelinui/0.6.0/rewrite.xml     | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/knox/blob/bea3974a/gateway-service-definitions/src/main/resources/services/zeppelinui/0.6.0/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/zeppelinui/0.6.0/rewrite.xml b/gateway-service-definitions/src/main/resources/services/zeppelinui/0.6.0/rewrite.xml
index 7259aba..db251ad 100644
--- a/gateway-service-definitions/src/main/resources/services/zeppelinui/0.6.0/rewrite.xml
+++ b/gateway-service-definitions/src/main/resources/services/zeppelinui/0.6.0/rewrite.xml
@@ -119,7 +119,8 @@
   <rule dir="OUT" name="ZEPPELINUI/zeppelin/outbound/javascript" pattern="{path=app**}">
     <rewrite template="{$frontend[path]}/zeppelin/{path=app**}"/>
   </rule>
-  
+
+  <!--
   <rule dir="OUT" name="ZEPPELINUI/zeppelin/outbound/javascript/component/tick" pattern="'components/{**}">
     <rewrite template="{$prefix[&#39;,url]}/zeppelin/components/{**}"/>
   </rule>
@@ -127,6 +128,7 @@
   <rule dir="OUT" name="ZEPPELINUI/zeppelin/outbound/javascript/component/tick" pattern="'app/{**}">
     <rewrite template="{$prefix[&#39;,url]}/zeppelin/app/{**}"/>
   </rule>
+  -->
 
   <!-- Filters -->
   <rule dir="OUT" name="ZEPPELINUI/zeppelin/outbound/javascript/filter/app/home" >


[18/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest.java
deleted file mode 100644
index 82948a3..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest.java
+++ /dev/null
@@ -1,1003 +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.hadoop.gateway.filter.rewrite.impl.xml;
-
-import org.apache.commons.digester3.Digester;
-import org.apache.commons.digester3.ExtendedBaseRules;
-import org.apache.commons.digester3.binder.DigesterLoader;
-import org.apache.commons.io.IOUtils;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterBufferDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterDetectDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepFlow;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteCheckDescriptorExt;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteControlDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptorExt;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
-import org.apache.hadoop.test.TestUtils;
-import org.hamcrest.Matchers;
-import org.junit.Before;
-import org.junit.Test;
-import org.xml.sax.SAXException;
-import org.xmlmatchers.namespace.SimpleNamespaceContext;
-
-import javax.xml.namespace.QName;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.stream.XMLStreamException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Reader;
-import java.io.StringReader;
-import java.nio.charset.Charset;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import static org.apache.commons.digester3.binder.DigesterLoader.newLoader;
-import static org.hamcrest.CoreMatchers.hasItem;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.*;
-import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.equalTo;
-import static org.junit.Assert.fail;
-import static org.xmlmatchers.XmlMatchers.hasXPath;
-import static org.xmlmatchers.transform.XmlConverters.the;
-
-public class XmlFilterReaderTest {
-
-  public static class NoopXmlFilterReader extends XmlFilterReader {
-    public NoopXmlFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException, ParserConfigurationException, XMLStreamException {
-      super( reader, config );
-    }
-
-    @Override
-    protected String filterText( QName elementName, String text, String ruleName ) {
-      return text;
-    }
-
-    @Override
-    protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
-      return attributeValue;
-    }
-  }
-
-  public static class MapXmlFilterReader extends XmlFilterReader {
-    private Map<String,String> map;
-
-    public MapXmlFilterReader( Reader reader, Map<String,String> map ) throws IOException, ParserConfigurationException, XMLStreamException {
-      super( reader, null );
-      this.map = map;
-    }
-
-    @Override
-    protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
-      return map.get( attributeValue.trim() );
-    }
-
-    @Override
-    protected String filterText( QName elementName, String text, String ruleName ) {
-      return map.get( text.trim() );
-    }
-  }
-
-  @Test
-  public void testSimple() throws IOException, ParserConfigurationException, XMLStreamException {
-    String inputXml = "<root/>";
-    StringReader inputReader = new StringReader( inputXml );
-    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
-    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-    assertThat( the( outputHtml ), hasXPath( "/root" ) );
-  }
-
-  @Test
-  public void testSimpleStreaming() throws IOException, ParserConfigurationException, XMLStreamException {
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
-
-    String inputXml = "<root/>";
-    StringReader inputReader = new StringReader( inputXml );
-    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, contentConfig );
-    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-    assertThat( the( outputHtml ), hasXPath( "/root" ) );
-  }
-
-//  @Test
-//  public void testSimpleScoped() throws IOException, ParserConfigurationException, XMLStreamException {
-//    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-//    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-//    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
-//
-//    String inputXml = "<root/>";
-//    StringReader inputReader = new StringReader( inputXml );
-//    XmlStaxFilterReader filterReader = new NoopXmlFilterReader( inputReader );
-//    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-//    assertThat( the( outputHtml ), hasXPath( "/root" ) );
-//  }
-
-  @Test
-  public void testSimpleBuffered() throws IOException, ParserConfigurationException, XMLStreamException {
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
-    UrlRewriteFilterBufferDescriptor scopeConfig = contentConfig.addBuffer( "/root" );
-
-    String input = "<root/>";
-    //System.out.println( "INPUT=" + input );
-    StringReader inputReader = new StringReader( input );
-    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, contentConfig );
-    String output = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( "OUTPUT=" + output );
-    assertThat( the( output ), hasXPath( "/root" ) );
-  }
-
-  @Test
-  public void testSimpleNested() throws IOException, ParserConfigurationException, XMLStreamException {
-    String inputXml = "<root><child1><child11/><child12/></child1><child2><child21/><child22/></child2></root>";
-    StringReader inputReader = new StringReader( inputXml );
-    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
-    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-    assertThat( the( outputHtml ), hasXPath( "/root" ) );
-    assertThat( the( outputHtml ), hasXPath( "/root/child1" ) );
-    assertThat( the( outputHtml ), hasXPath( "/root/child1/child11" ) );
-    assertThat( the( outputHtml ), hasXPath( "/root/child1/child12" ) );
-    assertThat( the( outputHtml ), hasXPath( "/root/child2" ) );
-    assertThat( the( outputHtml ), hasXPath( "/root/child2/child21" ) );
-    assertThat( the( outputHtml ), hasXPath( "/root/child2/child22" ) );
-  }
-
-  @Test
-  public void testSimpleWithNamespace() throws IOException, ParserConfigurationException, XMLStreamException {
-    String inputXml = "<ns:root xmlns:ns='http://hortonworks.com/xml/ns'></ns:root>";
-    StringReader inputReader = new StringReader( inputXml );
-    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
-    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-
-    //System.out.println( outputHtml );
-    SimpleNamespaceContext ns = new SimpleNamespaceContext();
-    ns.bind( "ns", "http://hortonworks.com/xml/ns" );
-    assertThat( the( outputHtml ), hasXPath( "/ns:root", ns ) );
-  }
-
-  @Test
-  public void testSimpleTextNode() throws IOException, ParserConfigurationException, XMLStreamException {
-    String inputXml = "<root>text</root>";
-    StringReader inputReader = new StringReader( inputXml );
-    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
-    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( "OUTPUT=" + outputXml );
-    assertThat( the( outputXml ), hasXPath( "/root/text()", equalTo( "text" ) ) );
-  }
-
-  @Test
-  public void testSimpleAttribute() throws IOException, ParserConfigurationException, XMLStreamException {
-    String inputXml = "<root name='value'/>";
-    StringReader inputReader = new StringReader( inputXml );
-    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
-    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( outputHtml );
-    assertThat( the( outputXml ), hasXPath( "/root/@name", equalTo( "value" ) ) );
-  }
-
-  @Test
-  public void testSimpleTextNodeBuffered() throws IOException, ParserConfigurationException, XMLStreamException {
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
-    UrlRewriteFilterBufferDescriptor scopeConfig = contentConfig.addBuffer( "/root" );
-
-    String inputXml = "<root>text</root>";
-    StringReader inputReader = new StringReader( inputXml );
-    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, contentConfig );
-    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( outputHtml );
-    assertThat( the( outputHtml ), hasXPath( "/root/text()", equalTo( "text" ) ) );
-  }
-
-  @Test
-  public void testSimpleAttributeBuffered() throws IOException, ParserConfigurationException, XMLStreamException {
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
-    UrlRewriteFilterBufferDescriptor scopeConfig = contentConfig.addBuffer( "/root" );
-
-    String inputXml = "<root name='value'/>";
-    StringReader inputReader = new StringReader( inputXml );
-    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, contentConfig );
-    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( outputHtml );
-    assertThat( the( outputHtml ), hasXPath( "/root/@name", equalTo( "value" ) ) );
-  }
-
-  @Test
-  public void testMappedText() throws IOException, ParserConfigurationException, XMLStreamException {
-    Map<String,String> map = new HashMap<>();
-    map.put( "input-text", "output-text" );
-    String inputXml = "<root>input-text</root>";
-    StringReader inputReader = new StringReader( inputXml );
-    XmlFilterReader filterReader = new MapXmlFilterReader( inputReader, map );
-    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( outputHtml );
-    assertThat( the( outputHtml ), hasXPath( "/root/text()", equalTo( "output-text" ) ) );
-  }
-
-  @Test
-  public void testMappedAttribute() throws IOException, ParserConfigurationException, XMLStreamException {
-    Map<String,String> map = new HashMap<>();
-    map.put( "input-text", "output-text" );
-    String inputXml = "<root attribute='input-text'/>";
-    StringReader inputReader = new StringReader( inputXml );
-    XmlFilterReader filterReader = new MapXmlFilterReader( inputReader, map );
-    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( outputHtml );
-    assertThat( the( outputHtml ), hasXPath( "/root/@attribute", equalTo( "output-text" ) ) );
-  }
-
-  @Test
-  public void testCombined() throws IOException, ParserConfigurationException, XMLStreamException {
-    Map<String,String> map = new HashMap<>();
-    map.put( "attr1-input", "attr1-output" );
-    map.put( "attr2-input", "attr2-output" );
-    map.put( "attr3-input", "attr3-output" );
-    map.put( "attr4-input", "attr4-output" );
-    map.put( "attr5-input", "attr5-output" );
-    map.put( "attr6-input", "attr6-output" );
-    map.put( "attr7-input", "attr7-output" );
-    map.put( "root-input1", "root-output1" );
-    map.put( "root-input2", "root-output2" );
-    map.put( "root-input3", "root-output3" );
-    map.put( "child1-input", "child1-output" );
-    map.put( "child2-input", "child2-output" );
-
-    String inputXml =
-          "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
-            "<!-- Comment -->\n" +
-            "<ns1:root xmlns:ns1='http://hortonworks.com/xml/ns1' attr1='attr1-input' ns1:attr2='attr2-input'>\n" +
-            "  root-input1\n" +
-            "  <child1 attr3='attr3-input' ns1:attr4='attr4-input'>\n" +
-            "    child1-input\n" +
-            "  </child1>\n" +
-            "  root-input2\n" +
-            "  <ns2:child2 xmlns:ns2='http://hortonworks.com/xml/ns2' attr5='attr5-input' ns1:attr6='attr6-input' ns2:attr7='attr7-input'>\n" +
-            "    child2-input\n" +
-            "  </ns2:child2>\n" +
-            "  root-input3\n" +
-            "</ns1:root>";
-    //System.out.println( inputXml );
-
-    StringReader inputReader = new StringReader( inputXml );
-    XmlFilterReader filterReader = new MapXmlFilterReader( inputReader, map );
-    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( outputXml );
-    //System.out.flush();
-
-    SimpleNamespaceContext ns = new SimpleNamespaceContext();
-    ns.bind( "n1", "http://hortonworks.com/xml/ns1" );
-    ns.bind( "n2", "http://hortonworks.com/xml/ns2" );
-
-    assertThat( the( outputXml ), hasXPath( "/n1:root", ns ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/@attr1", ns, equalTo( "attr1-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/@n1:attr2", ns, equalTo( "attr2-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/text()[1]", ns, equalTo( "root-output1" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/text()[2]", ns, equalTo( "root-output2" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/text()[3]", ns, equalTo( "root-output3" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/child1", ns ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/child1/@attr3", ns, equalTo( "attr3-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/child1/@n1:attr4", ns, equalTo( "attr4-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/child1/text()", ns, equalTo( "child1-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2", ns ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/@attr5", ns, equalTo( "attr5-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/@n1:attr6", ns, equalTo( "attr6-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/@n2:attr7", ns, equalTo( "attr7-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/text()", ns, equalTo( "child2-output" ) ) );
-  }
-
-  public static class XmlRewriteRulesDescriptorDigesterTest {
-
-    private static DigesterLoader loader = newLoader( new XmlRewriteRulesDigester() );
-    private static Digester digester = loader.newDigester( new ExtendedBaseRules() );
-
-    @Before
-    public void setupTest() {
-      digester.setValidating( false );
-    }
-
-    @Test
-    public void testRuleParsing() throws IOException, SAXException {
-      Reader reader = new StringReader( "<rules/>" );
-      UrlRewriteRulesDescriptor config = digester.parse( reader );
-      assertThat( config.getRules().isEmpty(), is( true ) );
-
-      reader = new StringReader( "<rules><rule></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().size(), is( 1 ) );
-      UrlRewriteRuleDescriptor rule = config.getRules().get( 0 );
-      assertThat( rule, notNullValue() );
-      assertThat( rule.name(), nullValue() );
-      assertThat( rule.pattern(), nullValue() );
-      assertThat( rule.directions(), nullValue() );
-      assertThat( rule.flow(), nullValue() );
-
-      reader = new StringReader( "<rules><rule name=\"test-name\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule, notNullValue() );
-      assertThat( rule.name(), is( "test-name" ) );
-      assertThat( rule.pattern(), nullValue() );
-      assertThat( rule.directions(), nullValue() );
-      assertThat( rule.flow(), nullValue() );
-
-      reader = new StringReader( "<rules><rule scope=\"test-scope\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule, notNullValue() );
-      assertThat( rule.name(), nullValue() );
-      assertThat( rule.scope(), is( "test-scope" ) );
-      assertThat( rule.pattern(), nullValue() );
-      assertThat( rule.directions(), nullValue() );
-      assertThat( rule.flow(), nullValue() );
-
-      reader = new StringReader( "<rules><rule name=\"test-name\" scope=\"test-scope\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule, notNullValue() );
-      assertThat( rule.name(), is( "test-name" ) );
-      assertThat( rule.scope(), is( "test-scope" ) );
-      assertThat( rule.pattern(), nullValue() );
-      assertThat( rule.directions(), nullValue() );
-      assertThat( rule.flow(), nullValue() );
-
-      reader = new StringReader( "<rules><rule pattern=\"test-pattern\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule, notNullValue() );
-      assertThat( rule.name(), nullValue() );
-      assertThat( rule.pattern(), is( "test-pattern" ) );
-      assertThat( rule.directions(), nullValue() );
-      assertThat( rule.flow(), nullValue() );
-
-      reader = new StringReader( "<rules><rule dir=\"request\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule, notNullValue() );
-      assertThat( rule.name(), nullValue() );
-      assertThat( rule.pattern(), nullValue() );
-      assertThat( rule.directions().size(), is( 1 ) );
-      assertThat( rule.directions(), contains( UrlRewriter.Direction.IN ) );
-      assertThat( rule.flow(), nullValue() );
-
-      reader = new StringReader( "<rules><rule flow=\"all\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule, notNullValue() );
-      assertThat( rule.name(), nullValue() );
-      assertThat( rule.pattern(), nullValue() );
-      assertThat( rule.directions(), nullValue() );
-      assertThat( rule.flow(), Matchers.is( UrlRewriteStepFlow.ALL ) );
-    }
-
-    @Test
-    public void testDirectionParsing() throws IOException, SAXException {
-      Reader reader;
-      UrlRewriteRulesDescriptor config;
-
-      reader = new StringReader( "<rules><rule dir=\"request\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"Request\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"in\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"req\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"Req\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"REQ\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"inbound\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"Inbound\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"INBOUND\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"in\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"In\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"IN\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"i\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"I\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-
-      reader = new StringReader( "<rules><rule dir=\"response\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"Response\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"out\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"res\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"Res\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"RES\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"outbound\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"Outbound\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"OUTBOUND\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"out\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"Out\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"OUT\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"o\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"O\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-
-      reader = new StringReader( "<rules><rule dir=\"request,response\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), hasItem( UrlRewriter.Direction.IN ) );
-      assertThat( config.getRules().get( 0 ).directions(), hasItem( UrlRewriter.Direction.OUT ) );
-    }
-
-    @Test
-    public void testFlowParsing() throws IOException, SAXException {
-      Reader reader;
-      UrlRewriteRulesDescriptor config;
-
-      reader = new StringReader( "<rules><rule dir=\"request\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-    }
-
-    @Test
-    public void testMatchParsing() throws IOException, SAXException {
-      Reader reader;
-      UrlRewriteRulesDescriptor config;
-      UrlRewriteRuleDescriptor rule;
-      UrlRewriteMatchDescriptorExt match;
-      List<? extends UrlRewriteStepDescriptor> steps;
-
-      reader = new StringReader( "<rules><rule><match></match></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config, notNullValue() );
-      assertThat( config.getRules(), notNullValue() );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule.steps(), notNullValue() );
-      assertThat( rule.steps().size(), is( 1 ) );
-      match = (UrlRewriteMatchDescriptorExt)rule.steps().get( 0 );
-      assertThat( match, notNullValue() );
-      //assertThat( match.type(), nullValue() );
-      assertThat( match.operation(), nullValue() );
-      assertThat( match.pattern(), nullValue() );
-
-      reader = new StringReader( "<rules><rule><match type=\"test-type\" op=\"test-op\" pattern=\"test-pattern\"></match></rule></rules>" );
-      config = digester.parse( reader );
-      match = (UrlRewriteMatchDescriptorExt)config.getRules().get( 0 ).steps().get( 0 );
-      //assertThat( match.type(), is("test-type") );
-      assertThat( match.operation(), is( "test-op" ) );
-      assertThat( match.pattern(), is( "test-pattern" ) );
-
-      reader = new StringReader( "<rules><rule name=\"test\"><match><match pattern=\"test-pattern\"></match></match></rule></rules>" );
-      config = digester.parse( reader );
-      steps = ((UrlRewriteMatchDescriptor)config.getRule( "test" ).steps().get( 0 )).steps();
-      assertThat( steps, notNullValue() );
-      assertThat( steps.size(), is( 1 ) );
-      assertThat( steps.get( 0 ), notNullValue() );
-      match = (UrlRewriteMatchDescriptorExt)steps.get( 0 );
-      assertThat( match.pattern(), is( "test-pattern" ) );
-    }
-
-    @Test
-    public void testCheckParsing() throws IOException, SAXException {
-      Reader reader;
-      UrlRewriteRulesDescriptor config;
-      UrlRewriteRuleDescriptor rule;
-      List<UrlRewriteStepDescriptor> steps;
-      UrlRewriteCheckDescriptorExt step;
-
-      reader = new StringReader( "<rules><rule><check></check></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config, notNullValue() );
-      assertThat( config.getRules(), notNullValue() );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule.steps(), notNullValue() );
-      assertThat( rule.steps().size(), is( 1 ) );
-      step = (UrlRewriteCheckDescriptorExt)rule.steps().get( 0 );
-      assertThat( step, notNullValue() );
-      //assertThat( step.type(), nullValue() );
-      assertThat( step.operation(), nullValue() );
-      assertThat( step.input(), nullValue() );
-      assertThat( step.value(), nullValue() );
-
-      reader = new StringReader( "<rules><rule><check type=\"test-type\" op=\"test-op\" input=\"test-input\" value=\"test-value\"></check></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config, notNullValue() );
-      assertThat( config.getRules(), notNullValue() );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule.steps(), notNullValue() );
-      assertThat( rule.steps().size(), is( 1 ) );
-      step = (UrlRewriteCheckDescriptorExt)rule.steps().get( 0 );
-      assertThat( step, notNullValue() );
-      //assertThat( step.type(), is( "test-type" ) );
-      assertThat( step.operation(), is( "test-op" ) );
-      assertThat( step.input(), is( "test-input" ) );
-      assertThat( step.value(), is( "test-value" ) );
-    }
-
-    @Test
-    public void testActionParsing() throws IOException, SAXException {
-      Reader reader;
-      UrlRewriteRulesDescriptor config;
-      UrlRewriteRuleDescriptor rule;
-      UrlRewriteActionDescriptorBase step;
-
-      reader = new StringReader( "<rules><rule><action></action></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config, notNullValue() );
-      assertThat( config.getRules(), notNullValue() );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule.steps(), notNullValue() );
-      assertThat( rule.steps().size(), is( 1 ) );
-      step = (UrlRewriteActionDescriptorBase)rule.steps().get( 0 );
-      assertThat( step, notNullValue() );
-      //assertThat( step.type(), nullValue() );
-      assertThat( step.parameter(), nullValue() );
-
-      reader = new StringReader( "<rules><rule><action type=\"test-type\" param=\"test-param\"></action></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config, notNullValue() );
-      assertThat( config.getRules(), notNullValue() );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule.steps(), notNullValue() );
-      assertThat( rule.steps().size(), is( 1 ) );
-      step = (UrlRewriteActionDescriptorBase)rule.steps().get( 0 );
-      assertThat( step, notNullValue() );
-      //assertThat( step.type(), is( "test-type" ) );
-      assertThat( step.parameter(), is( "test-param" ) );
-    }
-
-    @Test
-    public void testControlParsing() throws IOException, SAXException {
-      Reader reader;
-      UrlRewriteRulesDescriptor config;
-      UrlRewriteRuleDescriptor rule;
-      List<UrlRewriteStepDescriptor> steps;
-
-      reader = new StringReader( "<rules><rule><control></control></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config, notNullValue() );
-      assertThat( config.getRules(), notNullValue() );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule.steps(), notNullValue() );
-      assertThat( rule.steps().size(), is( 1 ) );
-      UrlRewriteControlDescriptor step = (UrlRewriteControlDescriptor)rule.steps().get( 0 );
-      assertThat( step, notNullValue() );
-      assertThat(  step.flow(), nullValue() );
-
-      reader = new StringReader( "<rules><rule><control flow=\"or\"></control></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config, notNullValue() );
-      assertThat( config.getRules(), notNullValue() );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule.steps(), notNullValue() );
-      assertThat( rule.steps().size(), is( 1 ) );
-      step = (UrlRewriteControlDescriptor)rule.steps().get( 0 );
-      assertThat( step, notNullValue() );
-      assertThat( step.flow(), is( UrlRewriteStepFlow.OR ) );
-    }
-  }
-
-  @Test
-  public void testTagNameLetterCase() throws Exception {
-    String inputXml = "<Root/>";
-    StringReader inputReader = new StringReader( inputXml );
-
-    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
-    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
-    assertThat( the( outputXml ), hasXPath( "/Root" ) );
-  }
-
-  @Test
-  public void testXmlWithHtmlTagNames() throws Exception {
-    String inputXml = "<root><br><table name=\"table1\"/><table name=\"table2\"/></br></root>";
-    StringReader inputReader = new StringReader( inputXml );
-
-    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
-    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
-    assertThat( the( outputXml ), hasXPath( "/root/br/table[1]/@name", equalTo( "table1" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/root/br/table[2]/@name", equalTo( "table2" ) ) );
-  }
-
-  @Test
-  public void testStreamedApplyForElements() throws Exception {
-    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties-elements.xml" );
-    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
-
-    //System.out.println( "INPUT=" + input );
-
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
-    UrlRewriteFilterApplyDescriptor applyConfig = contentConfig.addApply( "/properties/property/value/text()", "test-rule-2" );
-
-    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
-
-    XmlFilterReader filter = new TestXmlFilterReader( new StringReader( input ), contentConfig );
-    String output = IOUtils.toString( filter );
-
-    //System.out.println( "OUTPUT=" + output );
-
-    assertThat( the( output ), hasXPath( "/properties/property[1]/name/text()", equalTo( "test-name-1" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[1]/value/text()", equalTo( "text:test-rule-2{test-value-1}" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[2]/name/text()", equalTo( "test-name-2" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[2]/value/text()", equalTo( "text:test-rule-2{test-value-2}" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[3]/name/text()", equalTo( "test-name-3" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[3]/value/text()", equalTo( "text:test-rule-2{test-value-3}" ) ) );
-  }
-
-  @Test
-  public void testStreamedApplyForElementsConfigShortcut() throws Exception {
-    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties-elements.xml" );
-    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
-
-    //System.out.println( "INPUT=" + input );
-
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
-    UrlRewriteFilterApplyDescriptor applyConfig = contentConfig.addApply( "/properties/property/value", "test-rule-2" );
-
-    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
-
-    XmlFilterReader filter = new TestXmlFilterReader( new StringReader( input ), contentConfig );
-    String output = IOUtils.toString( filter );
-
-    //System.out.println( "OUTPUT=" + output );
-
-    assertThat( the( output ), hasXPath( "/properties/property[1]/name/text()", equalTo( "test-name-1" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[1]/value/text()", equalTo( "text:test-rule-2{test-value-1}" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[2]/name/text()", equalTo( "test-name-2" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[2]/value/text()", equalTo( "text:test-rule-2{test-value-2}" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[3]/name/text()", equalTo( "test-name-3" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[3]/value/text()", equalTo( "text:test-rule-2{test-value-3}" ) ) );
-  }
-
-  @Test
-  public void testStreamedApplyForAttributes() throws Exception {
-    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties-attributes.xml" );
-    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
-
-    //System.out.println( "INPUT=" + input );
-
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
-    UrlRewriteFilterApplyDescriptor applyConfig = contentConfig.addApply( "/properties/property/@value", "test-rule-2" );
-
-    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
-
-    XmlFilterReader filter = new TestXmlFilterReader( new StringReader( input ), contentConfig );
-    String output = IOUtils.toString( filter );
-
-    //System.out.println( "OUTPUT=" + output );
-
-    assertThat( the( output ), hasXPath( "/properties/property[1]/@name", equalTo( "test-name-1" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[1]/@value", equalTo( "attr:test-rule-2{test-value-1}" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[2]/@name", equalTo( "test-name-2" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[2]/@value", equalTo( "attr:test-rule-2{test-value-2}" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[3]/@name", equalTo( "test-name-3" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[3]/@value", equalTo( "attr:test-rule-2{test-value-3}" ) ) );
-  }
-
-  @Test
-  public void testBufferedApplyForAttributes() throws Exception {
-    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties-attributes.xml" );
-    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
-
-    //System.out.println( "INPUT=" + input );
-
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
-    UrlRewriteFilterBufferDescriptor bufferconfig = contentConfig.addBuffer( "/properties/property" );
-    UrlRewriteFilterApplyDescriptor applyConfig = bufferconfig.addApply( "@value", "test-rule-2" );
-
-    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
-
-    XmlFilterReader filter = new TestXmlFilterReader( new StringReader( input ), contentConfig );
-    String output = IOUtils.toString( filter );
-
-    //System.out.println( "OUTPUT=" + output );
-
-    assertThat( the( output ), hasXPath( "/properties/property[1]/@name", equalTo( "test-name-1" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[1]/@value", equalTo( "attr:test-rule-2{test-value-1}" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[2]/@name", equalTo( "test-name-2" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[2]/@value", equalTo( "attr:test-rule-2{test-value-2}" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[3]/@name", equalTo( "test-name-3" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[3]/@value", equalTo( "attr:test-rule-2{test-value-3}" ) ) );
-  }
-
-  @Test
-  public void testBufferedDetectApplyForElements() throws Exception {
-    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties-elements.xml" );
-    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
-
-    //System.out.println( "INPUT=" + input );
-
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
-    UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "/properties/property" );
-    UrlRewriteFilterDetectDescriptor detectConfig = bufferConfig.addDetect( "name", "test-name-2" );
-    UrlRewriteFilterApplyDescriptor applyConfig = detectConfig.addApply( "value", "test-rule-2" );
-
-    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
-
-    XmlFilterReader filter = new TestXmlFilterReader( new StringReader( input ), contentConfig );
-    String output = IOUtils.toString( filter );
-
-    //System.out.println( "OUTPUT=" + output );
-
-    assertThat( the( output ), hasXPath( "/properties/property[1]/name/text()", equalTo( "test-name-1" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[1]/value/text()", equalTo( "test-value-1" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[2]/name/text()", equalTo( "test-name-2" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[2]/value/text()", equalTo( "text:test-rule-2{test-value-2}" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[3]/name/text()", equalTo( "test-name-3" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[3]/value/text()", equalTo( "test-value-3" ) ) );
-  }
-
-  @Test
-  public void testBufferedDetectApplyForAttributes() throws Exception {
-    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties-attributes.xml" );
-    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
-
-    //System.out.println( "INPUT=" + input );
-
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
-    UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "/properties/property" );
-    UrlRewriteFilterDetectDescriptor detectConfig = bufferConfig.addDetect( "@name", "test-name-2" );
-    UrlRewriteFilterApplyDescriptor applyConfig = detectConfig.addApply( "@value", "test-rule-2" );
-
-    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
-
-    XmlFilterReader filter = new TestXmlFilterReader( new StringReader( input ), contentConfig );
-    String output = IOUtils.toString( filter );
-
-    //System.out.println( "OUTPUT=" + output );
-
-    assertThat( the( output ), hasXPath( "/properties/property[1]/@name", equalTo( "test-name-1" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[1]/@value", equalTo( "test-value-1" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[2]/@name", equalTo( "test-name-2" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[2]/@value", equalTo( "attr:test-rule-2{test-value-2}" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[3]/@name", equalTo( "test-name-3" ) ) );
-    assertThat( the( output ), hasXPath( "/properties/property[3]/@value", equalTo( "test-value-3" ) ) );
-  }
-
-  @Test
-  public void testInvalidConfigShouldThrowException() throws Exception {
-    String input = "<root url='http://mock-host:42/test-input-path-1'><url>http://mock-host:42/test-input-path-2</url></root>";
-
-    //System.out.println( "INPUT=" + input );
-
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "*/xml" );
-    contentConfig.addApply( "$.url", "test-rule" );
-
-    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
-
-    try {
-      XmlFilterReader filter = new TestXmlFilterReader( new StringReader( input ), contentConfig );
-      IOUtils.toString( filter );
-      fail( "Should have thrown an IllegalArgumentException." );
-    } catch ( IOException e ) {
-      fail( "Should have thrown an IllegalArgumentException." );
-    } catch ( IllegalArgumentException e ) {
-      if(System.getProperty("java.vendor").contains("IBM")){
-        assertThat( e.getMessage(), containsString( "Extra illegal tokens: 'url'" ) );
-      }else {
-        assertThat( e.getMessage(), containsString( "$.url" ) );
-      }
-    }
-  }
-
-  @Test
-  public void testDefaultNamespace() throws IOException, ParserConfigurationException, XMLStreamException {
-    String input = "<root xmlns=\"ns\"><node attribute=\"attr\">nodevalue</node></root>";
-    StringReader inputReader = new StringReader( input );
-    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
-    String output = IOUtils.toString( filterReader );
-    //check default namespace URI
-    assertThat( the( output ), hasXPath( "/*/namespace::*[name()='']", equalTo( "ns" ) ) );
-    assertThat( the( output ), hasXPath( "/*[namespace-uri()='ns' and name()='root']/*[namespace-uri()='ns' and name()='node']", equalTo( "nodevalue" ) ) );
-    assertThat( the( output ), hasXPath( "/*[namespace-uri()='ns' and name()='root']/*[namespace-uri()='ns' and name()='node']/@attribute", equalTo( "attr" ) ) );
-  }
-
-  @Test
-  public void testEscapeCharactersBugKnox616() throws Exception {
-    String input, output;
-    StringReader reader;
-    XmlFilterReader filter;
-
-    input = "<tag/>";
-    reader = new StringReader( input );
-    filter = new NoopXmlFilterReader( reader, null );
-    output = IOUtils.toString( filter );
-    assertThat( output, containsString( "<tag/>" ) );
-
-    input = "<tag></tag>";
-    reader = new StringReader( input );
-    filter = new NoopXmlFilterReader( reader, null );
-    output = IOUtils.toString( filter );
-    assertThat( output, containsString( "<tag/>" ) );
-
-    input = "<tag>&lt;</tag>";
-    reader = new StringReader( input );
-    filter = new NoopXmlFilterReader( reader, null );
-    output = IOUtils.toString( filter );
-    assertThat( the( output ), hasXPath( "/tag" ) );
-    assertThat( output, containsString( "<tag>&lt;</tag>" ) );
-
-    input = "<tag>&amp;</tag>";
-    reader = new StringReader( input );
-    filter = new NoopXmlFilterReader( reader, null );
-    output = IOUtils.toString( filter );
-    assertThat( output, containsString( "<tag>&amp;</tag>" ) );
-
-    input = "<document><empty/><![CDATA[<xyz>wibble</xyz>]]></document>";
-    reader = new StringReader( input );
-    filter = new NoopXmlFilterReader( reader, null );
-    output = IOUtils.toString( filter );
-    assertThat( output, containsString( "<?xml version=\"1.0\" standalone=\"no\"?><document><empty/><![CDATA[<xyz>wibble</xyz>]]></document>" ));
-
-    input="<?xml version=\"1.0\" standalone=\"no\"?>"+
-"<document>" +
-"   <noempty test=\"a\"> </noempty>"+
-"  <!-- This is the first comment -->"+
-"   <empty/>"+
-"   <![CDATA[<xyz>wibble</xyz>]]>"+
-"   <here>"+
-"      <moreempty/>"+
-"       <!-- This is the second comment -->"+
-"      <![CDATA[<xyz>noop</xyz>]]>"+
-"   </here>"+
-"</document>";
-    reader = new StringReader( input );
-    filter = new NoopXmlFilterReader( reader, null );
-    output = IOUtils.toString( filter );
-    assertThat( output, containsString( "<?xml version=\"1.0\" standalone=\"no\"?><document>   <noempty test=\"a\"> </noempty>  <!-- This is the first comment -->   <empty/>   <![CDATA[<xyz>wibble</xyz>]]>   <here>      <moreempty/>       <!-- This is the second comment -->      <![CDATA[<xyz>noop</xyz>]]>   </here></document>"));
-  }
-
-  @Test
-  public void testSpecialTextNodeBugKnox394() throws IOException, ParserConfigurationException, XMLStreamException {
-    String inputXml = "<tag>${oozieTemplateMarkup}</tag>";
-    StringReader inputReader = new StringReader( inputXml );
-    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
-    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( "OUTPUT=" + outputXml );
-    assertThat( the( outputXml ), hasXPath( "/tag/text()", equalTo( "${oozieTemplateMarkup}" ) ) );
-  }
-
-
-  private class TestXmlFilterReader extends XmlFilterReader {
-
-    protected TestXmlFilterReader( Reader reader, UrlRewriteFilterContentDescriptor contentConfig ) throws IOException, ParserConfigurationException, XMLStreamException {
-      super( reader, contentConfig );
-    }
-
-    @Override
-    protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
-      return "attr:" + ruleName + "{" + attributeValue + "}";
-    }
-
-    @Override
-    protected String filterText( QName elementName, String text, String ruleName ) {
-      return "text:" + ruleName + "{" + text + "}";
-    }
-
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporterTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporterTest.java
deleted file mode 100644
index 9ae5bd0..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporterTest.java
+++ /dev/null
@@ -1,215 +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.hadoop.gateway.filter.rewrite.impl.xml;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteActionRewriteDescriptorExt;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteCheckDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteControlDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptor;
-import org.junit.Test;
-import org.xmlmatchers.XmlMatchers;
-import org.xmlmatchers.transform.XmlConverters;
-
-import javax.xml.transform.Source;
-import java.io.IOException;
-import java.io.StringWriter;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-public class XmlUrlRewriteRulesExporterTest {
-
-  @Test
-  public void testEmptyRules() throws IOException {
-    UrlRewriteRulesDescriptor rules = UrlRewriteRulesDescriptorFactory.create();
-    StringWriter writer = new StringWriter();
-    UrlRewriteRulesDescriptorFactory.store( rules, "xml", writer );
-
-    String xml = writer.toString();
-    assertThat( XmlConverters.the( xml ), XmlMatchers.hasXPath( "/rules" ) );
-  }
-
-  @Test
-  public void testSingleNamedRule() throws IOException {
-    UrlRewriteRulesDescriptor rules = UrlRewriteRulesDescriptorFactory.create();
-    rules.addRule( "first" ).scope( "test-scope" );
-
-    StringWriter writer = new StringWriter();
-    UrlRewriteRulesDescriptorFactory.store( rules, "xml", writer );
-
-    String str = writer.toString();
-    //System.out.println( str );
-    Source xml = XmlConverters.the( str );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule)", is( "1" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@name", is( "first" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@scope", is( "test-scope" ) ) );
-  }
-
-  @Test
-  public void testMatchStep() throws Exception {
-    UrlRewriteRulesDescriptor rules = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteRuleDescriptor rule = rules.addRule( "test-rule" ).pattern("test-pattern-rule");
-    UrlRewriteMatchDescriptor match = rule.addStep( "match" );
-    match.operation("test-operation").pattern( "test-pattern-step" ).flow( "all" );
-
-    StringWriter writer = new StringWriter();
-    UrlRewriteRulesDescriptorFactory.store( rules, "xml", writer );
-
-    String str = writer.toString();
-    //System.out.println( str );
-    Source xml = XmlConverters.the( str );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule)", is( "1" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@name", is( "test-rule" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@pattern", is( "test-pattern-rule" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule/match)", is( "1" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match/@flow", is( "ALL" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match/@oper", is( "test-operation" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match/@pattern", is( "test-pattern-step" ) ) );
-  }
-
-  @Test
-  public void testControlStep() throws Exception {
-    UrlRewriteRulesDescriptor rules = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteRuleDescriptor rule = rules.addRule( "test-rule" );
-    UrlRewriteControlDescriptor control = rule.addStep( "control" );
-    control.flow( "or" );
-
-    StringWriter writer = new StringWriter();
-    UrlRewriteRulesDescriptorFactory.store( rules, "xml", writer );
-
-    String str = writer.toString();
-    //System.out.println( str );
-    Source xml = XmlConverters.the( str );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule)", is( "1" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@name", is( "test-rule" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/control" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule/control)", is( "1" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/control/@flow", is( "OR" ) ) );
-  }
-
-  @Test
-  public void testCheckStep() throws Exception {
-    UrlRewriteRulesDescriptor rules = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteRuleDescriptor rule = rules.addRule( "test-rule" );
-    UrlRewriteCheckDescriptor step = rule.addStep( "check" );
-    step.operation("test-operation").input("test-input").value("test-value").flow( "all" );
-
-    StringWriter writer = new StringWriter();
-    UrlRewriteRulesDescriptorFactory.store( rules, "xml", writer );
-
-    String str = writer.toString();
-    //System.out.println( str );
-    Source xml = XmlConverters.the( str );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule)", is( "1" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@name", is( "test-rule" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/@oper", is("test-operation") ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/@input", is("test-input") ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/@value", is("test-value") ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/@flow", is("ALL") ) );
-  }
-
-  @Test
-  public void testRewriteStep() throws Exception {
-    UrlRewriteRulesDescriptor rules = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteRuleDescriptor rule = rules.addRule( "test-rule" );
-    UrlRewriteActionRewriteDescriptorExt step = rule.addStep( "rewrite" );
-    step.operation("test-operation").parameter( "test-param" );
-
-    StringWriter writer = new StringWriter();
-    UrlRewriteRulesDescriptorFactory.store( rules, "xml", writer );
-
-    String str = writer.toString();
-    //System.out.println( str );
-    Source xml = XmlConverters.the( str );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule)", is( "1" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@name", is( "test-rule" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/rewrite" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/rewrite/@oper", is("test-operation") ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/rewrite/@template", is("test-param") ) );
-  }
-
-  @Test
-  public void testNestedStep() throws Exception {
-    UrlRewriteRulesDescriptor rules = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteRuleDescriptor rule = rules.addRule( "test-rule" );
-
-    UrlRewriteMatchDescriptor match = rule.addStep( "match" );
-    UrlRewriteMatchDescriptor matchMatch = match.addStep( "match" );
-    UrlRewriteCheckDescriptor matchCheck = match.addStep( "check" );
-    UrlRewriteControlDescriptor matchControl = match.addStep( "control" );
-    UrlRewriteActionDescriptor matchRewrite = match.addStep( "rewrite" );
-
-    UrlRewriteCheckDescriptor check = rule.addStep( "check" );
-    UrlRewriteMatchDescriptor checkMatch = check.addStep( "match" );
-    UrlRewriteCheckDescriptor checkCheck = check.addStep( "check" );
-    UrlRewriteControlDescriptor checkControl = check.addStep( "control" );
-    UrlRewriteActionDescriptor checkRewrite = check.addStep( "rewrite" );
-
-    UrlRewriteControlDescriptor control = rule.addStep( "control" );
-    UrlRewriteMatchDescriptor controlMatch = control.addStep( "match" );
-    UrlRewriteCheckDescriptor controlCheck = control.addStep( "check" );
-    UrlRewriteControlDescriptor controlControl = control.addStep( "control" );
-    UrlRewriteActionDescriptor controlRewrite = control.addStep( "rewrite" );
-
-    UrlRewriteActionDescriptor rewrite = rule.addStep( "rewrite" );
-
-    StringWriter writer = new StringWriter();
-    UrlRewriteRulesDescriptorFactory.store( rules, "xml", writer );
-
-    String str = writer.toString();
-    //System.out.println( str );
-    Source xml = XmlConverters.the( str );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule)", is( "1" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@name", is( "test-rule" ) ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match/match" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match/check" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match/control" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match/rewrite" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/match" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/check" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/control" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/rewrite" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/control" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/control/match" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/control/check" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/control/control" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/control/rewrite" ) );
-    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/rewrite" ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/FrontendFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/FrontendFunctionDescriptorTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/FrontendFunctionDescriptorTest.java
new file mode 100644
index 0000000..fde25f2
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/FrontendFunctionDescriptorTest.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.knox.gateway.filter.rewrite.api;
+
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.fail;
+
+public class FrontendFunctionDescriptorTest {
+
+  @SuppressWarnings("rawtypes")
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof FrontendFunctionDescriptor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + FrontendFunctionDescriptor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    FrontendFunctionDescriptor descriptor = new FrontendFunctionDescriptor();
+    assertThat( descriptor.name(), is( "frontend" ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest.java
new file mode 100644
index 0000000..ff1093b
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest.java
@@ -0,0 +1,412 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.util.urltemplate.Expander;
+import org.apache.knox.gateway.util.urltemplate.Matcher;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Template;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+public class UrlRewriteProcessorTest {
+
+  private static URL getTestResourceUrl( String name ) throws FileNotFoundException {
+    name = UrlRewriteProcessorTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
+    URL url = ClassLoader.getSystemResource( name );
+    if( url == null ) {
+      throw new FileNotFoundException( name );
+    }
+    return url;
+  }
+
+  private static InputStream getTestResourceStream( String name ) throws IOException {
+    URL url = getTestResourceUrl( name );
+    InputStream stream = url.openStream();
+    return stream;
+  }
+
+  private static Reader getTestResourceReader( String name, String charset ) throws IOException {
+    return new InputStreamReader( getTestResourceStream( name ), charset );
+  }
+
+  @Test
+  public void testBasicPathRewrite() throws IOException, URISyntaxException {
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
+    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
+    EasyMock.replay( environment, request, response );
+
+    UrlRewriteProcessor processor = new UrlRewriteProcessor();
+    UrlRewriteRulesDescriptor config = UrlRewriteRulesDescriptorFactory.load(
+        "xml", getTestResourceReader( "rewrite.xml", "UTF-8" ) );
+    processor.initialize( environment, config );
+
+    Template inputUrl = Parser.parseLiteral( "test-scheme://test-host:1/test-input-path" );
+    Template outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.IN, null );
+
+    assertThat( "Expect rewrite to produce a new URL",
+        outputUrl, notNullValue() );
+    assertThat(
+        "Expect rewrite to contain the correct path.",
+        outputUrl.toString(), is( "test-scheme://test-host:1/test-output-path" ) );
+    processor.destroy();
+  }
+
+  @Test
+  public void testMultipleIdenticalRewriteOutputRules() throws IOException, URISyntaxException {
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
+    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
+    EasyMock.replay( environment, request, response );
+
+    UrlRewriteProcessor processor = new UrlRewriteProcessor();
+    UrlRewriteRulesDescriptor config = UrlRewriteRulesDescriptorFactory.load(
+        "xml", getTestResourceReader( "rewrite-with-same-rules.xml", "UTF-8" ) );
+    processor.initialize( environment, config );
+
+    Template inputUrl = Parser.parseLiteral( "scheme://input-mock-host:42/test-input-path" );
+    Template outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, null );
+
+    assertThat( "Expect rewrite to produce a new URL",
+        outputUrl, notNullValue() );
+    // Should always pick the first one.
+    assertThat(
+        "Expect rewrite to contain the correct path.",
+        outputUrl.toString(), is( "output-mock-scheme-1://output-mock-host-1:42/test-input-path" ) );
+
+    inputUrl = Parser.parseLiteral( "mock-scheme://input-mock-host:42/no-query" );
+    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, null );
+
+    assertThat(
+        "Expect rewrite to contain the correct path.",
+        outputUrl.toString(), is( "mock-scheme://output-mock-host-3:42/no-query" ) );
+
+    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, "test-rule-4" );
+
+    assertThat(
+        "Expect rewrite to contain the correct path.",
+        outputUrl.toString(), is( "mock-scheme://output-mock-host-4:42/no-query" ) );
+
+    processor.destroy();
+  }
+
+  @Test
+  public void testIdenticalRewriteOutputRulesWithScopes() throws IOException, URISyntaxException {
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
+    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
+    ArrayList<String> roles = new ArrayList<>();
+    roles.add("service-1");
+    EasyMock.expect(environment.resolve("service.role")).andReturn(roles).anyTimes();
+    EasyMock.replay( environment, request, response );
+
+    UrlRewriteProcessor processor = new UrlRewriteProcessor();
+    UrlRewriteRulesDescriptor config = UrlRewriteRulesDescriptorFactory.load(
+        "xml", getTestResourceReader( "rewrite-with-same-rules-different-scope.xml", "UTF-8" ) );
+    processor.initialize( environment, config );
+
+    Template inputUrl = Parser.parseLiteral( "scheme://input-mock-host:42/test-input-path" );
+    Template outputUrl = processor.rewrite( environment, inputUrl, UrlRewriter.Direction.OUT, null );
+
+    assertThat( "Expect rewrite to produce a new URL",
+        outputUrl, notNullValue() );
+    assertThat(
+        "Expect rewrite to contain the correct path.",
+        outputUrl.toString(), is( "output-mock-scheme-2://output-mock-host-2:42/test-input-path" ) );
+
+    inputUrl = Parser.parseLiteral( "mock-scheme://input-mock-host:42/no-query" );
+    outputUrl = processor.rewrite( environment, inputUrl, UrlRewriter.Direction.OUT, null );
+
+    roles.remove(0);
+    roles.add("service-2");
+
+    assertThat(
+        "Expect rewrite to contain the correct path.",
+        outputUrl.toString(), is( "mock-scheme://output-mock-host-5:42/no-query" ) );
+
+    outputUrl = processor.rewrite( environment, inputUrl, UrlRewriter.Direction.OUT, "service-2/test-rule-4" );
+
+    //no scope information should pick the first one
+    assertThat(
+        "Expect rewrite to contain the correct path.",
+        outputUrl.toString(), is( "mock-scheme://output-mock-host-4:42/no-query" ) );
+
+    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, "service-2/test-rule-4" );
+
+    assertThat(
+        "Expect rewrite to contain the correct path.",
+        outputUrl.toString(), is( "mock-scheme://output-mock-host-4:42/no-query" ) );
+
+    //Test the IN direction
+    inputUrl = Parser.parseLiteral( "scheme://input-mock-host:42/test-input-path" );
+    outputUrl = processor.rewrite( environment, inputUrl, UrlRewriter.Direction.IN, null );
+
+    assertThat( "Expect rewrite to produce a new URL",
+        outputUrl, notNullValue() );
+    assertThat(
+        "Expect rewrite to contain the correct path.",
+        outputUrl.toString(), is( "input-mock-scheme-2://input-mock-host-2:42/test-input-path" ) );
+
+    processor.destroy();
+  }
+
+  @Test
+  public void testRewriteViaRuleNameWithAmbiguousRules() throws IOException, URISyntaxException {
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
+    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
+    EasyMock.replay( environment, request, response );
+
+    UrlRewriteProcessor processor = new UrlRewriteProcessor();
+    UrlRewriteRulesDescriptor config = UrlRewriteRulesDescriptorFactory.load(
+        "xml", getTestResourceReader( "rewrite-with-same-rules.xml", "UTF-8" ) );
+    processor.initialize( environment, config );
+
+    Template inputUrl = Parser.parseLiteral( "input-mock-scheme-1://input-mock-host-1:42/test-input-path" );
+    Template outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, "test-rule-2" );
+
+    assertThat( "Expect rewrite to produce a new URL",
+        outputUrl, notNullValue() );
+    assertThat(
+        "Expect rewrite to contain the correct path.",
+        outputUrl.toString(), is( "output-mock-scheme-2://output-mock-host-2:42/test-input-path" ) );
+
+    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, "test-rule-1" );
+
+    assertThat( "Expect rewrite to produce a new URL",
+        outputUrl, notNullValue() );
+    assertThat(
+        "Expect rewrite to contain the correct path.",
+        outputUrl.toString(), is( "output-mock-scheme-1://output-mock-host-1:42/test-input-path" ) );
+
+    processor.destroy();
+  }
+
+  @Test
+  public void testRewriteViaRuleWithComplexFlow() throws Exception {
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
+    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
+    EasyMock.replay( environment, request, response );
+
+    UrlRewriteProcessor processor = new UrlRewriteProcessor();
+    UrlRewriteRulesDescriptor config = UrlRewriteRulesDescriptorFactory.load(
+        "xml", getTestResourceReader( "rewrite.xml", "UTF-8" ) );
+    processor.initialize( environment, config );
+
+    Template inputUrl;
+    Template outputUrl;
+
+    inputUrl = Parser.parseLiteral( "test-scheme://test-host:777/test-path" );
+    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.IN, "test-rule-with-complex-flow" );
+    assertThat(
+        "Expect rewrite to contain the correct path.",
+        outputUrl.toString(), is( "test-scheme-output://test-host-output:42/test-path-output/test-path" ) );
+
+    inputUrl = Parser.parseLiteral( "test-scheme://test-host:42/~/test-path" );
+    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.IN, "test-rule-with-complex-flow" );
+    assertThat(
+        "Expect rewrite to contain the correct path.",
+        outputUrl.toString(), is( "test-scheme-output://test-host-output:777/test-path-output/test-home/test-path" ) );
+
+    processor.destroy();
+  }
+
+  @Test
+  public void testRewriteViaRuleWithWildcardTemplateAndOptionalQuery() throws Exception {
+    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
+    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
+    EasyMock.replay( environment, request, response );
+
+    UrlRewriteProcessor processor = new UrlRewriteProcessor();
+    UrlRewriteRulesDescriptor config = UrlRewriteRulesDescriptorFactory.load(
+        "xml", getTestResourceReader( "rewrite.xml", "UTF-8" ) );
+    processor.initialize( environment, config );
+
+    Template inputUrl;
+    Template outputUrl;
+
+    inputUrl = Parser.parseLiteral( "test-scheme-input://test-host-input:42/test-path-input-one/test-path-input-two?test-query-name=test-query-value" );
+    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, "test-rule-2" );
+
+    assertThat(
+        "Expect rewrite to contain the correct path and query.",
+        outputUrl.toString(), is( "test-scheme-output://test-host-output:777/test-path-output/test-path-input-one/test-path-input-two?test-query-name=test-query-value" ) );
+
+    inputUrl = Parser.parseLiteral( "test-scheme-input://test-host-input:42/test-path-input-one/test-path-input-two" );
+    outputUrl = processor.rewrite( null, inputUrl, UrlRewriter.Direction.OUT, "test-rule-2" );
+
+    assertThat(
+        "Expect rewrite to contain the correct path.",
+        outputUrl.toString(), is( "test-scheme-output://test-host-output:777/test-path-output/test-path-input-one/test-path-input-two" ) );
+
+    processor.destroy();
+  }
+
+  /**
+   * Tests the rewrite pattern used for re-writing Solr urls passed through Knox.
+   * 
+   * @throws Exception
+   */
+  @Test
+  public void testSolrRewrite() throws Exception {
+    URI inputUri, outputUri;
+    Matcher<Void> matcher;
+    Matcher<Void>.Match match;
+    Template input, pattern, template;
+
+    inputUri = new URI(
+        "https://hortonworks.sandbox.hdp.24.test:8443/gateway/sandbox/solr/TestCollection/select?q=*.*&wt=json&indent=true");
+
+    input = Parser.parseLiteral(inputUri.toString());
+    pattern = Parser.parseTemplate("*://*:*/**/solr/{collection=**}/{query=**}?{**}");
+    template = Parser.parseTemplate("http://sandbox.hortonworks.com/solr/{collection=**}/{query=**}?{**}");
+
+    matcher = new Matcher<Void>();
+    matcher.add(pattern, null);
+    match = matcher.match(input);
+
+    outputUri = Expander.expand(template, match.getParams(), null);
+
+    final String reWrittenScheme = outputUri.getScheme();
+    assertEquals("http", reWrittenScheme);
+
+    final String reWrittenHost = outputUri.getHost();
+    assertEquals("sandbox.hortonworks.com", reWrittenHost);
+
+    final String reWrittenPath = outputUri.getPath();
+    assertEquals("/solr/TestCollection/select", reWrittenPath);
+
+    // Whole thing is (non-deterministicly ordered around the &s):
+    // "q=*.*&wt=json&indent=true"
+    final String reWrittenQuery = outputUri.getQuery();
+
+    // Check individual parameters are present, and have the right value.
+    final Map<String, String> reWrittenParams = mapUrlParameters(reWrittenQuery);
+    assertTrue(reWrittenParams.containsKey("q"));
+    assertEquals("*.*", reWrittenParams.get("q"));
+    assertTrue(reWrittenParams.containsKey("wt"));
+    assertEquals("json", reWrittenParams.get("wt"));
+    assertEquals("true", reWrittenParams.get("indent"));
+  }
+
+
+  @Test
+  public void testSolrRewriteDefaultPort() throws Exception {
+    URI inputUri, outputUri;
+    Matcher<Void> matcher;
+    Matcher<Void>.Match match;
+    Template input, pattern, template;
+
+    inputUri = new URI(
+                "https://hortonworks.sandbox.hdp.24.test/gateway/sandbox/solr/TestCollection/select?q=*.*&wt=json&indent=true");
+
+    input = Parser.parseLiteral(inputUri.toString());
+    pattern = Parser.parseTemplate("*://*:*/**/solr/{collection=**}/{query=**}?{**}");
+    template = Parser.parseTemplate("http://sandbox.hortonworks.com/solr/{collection=**}/{query=**}?{**}");
+
+    matcher = new Matcher<Void>();
+    matcher.add(pattern, null);
+    match = matcher.match(input);
+
+    outputUri = Expander.expand(template, match.getParams(), null);
+
+    final String reWrittenScheme = outputUri.getScheme();
+    assertEquals("http", reWrittenScheme);
+
+    final String reWrittenHost = outputUri.getHost();
+    assertEquals("sandbox.hortonworks.com", reWrittenHost);
+
+    final String reWrittenPath = outputUri.getPath();
+    assertEquals("/solr/TestCollection/select", reWrittenPath);
+
+    // Whole thing is (non-deterministicly ordered around the &s):
+    // "q=*.*&wt=json&indent=true"
+    final String reWrittenQuery = outputUri.getQuery();
+
+    // Check individual parameters are present, and have the right value.
+    final Map<String, String> reWrittenParams = mapUrlParameters(reWrittenQuery);
+    assertTrue(reWrittenParams.containsKey("q"));
+    assertEquals("*.*", reWrittenParams.get("q"));
+    assertTrue(reWrittenParams.containsKey("wt"));
+    assertEquals("json", reWrittenParams.get("wt"));
+    assertEquals("true", reWrittenParams.get("indent"));
+  }
+
+
+  /**
+   * Turn a string containing URL parameters, e.g.
+   * 
+   * <pre>
+   * a=b&c=d&e=f
+   * </pre>
+   * 
+   * into a map such as
+   * <table>
+   * <tr>
+   * <th>Key</th>
+   * <th>Value</th>
+   * </tr>
+   * <tr>
+   * <td>a</td>
+   * <td>b</td>
+   * </tr>
+   * <tr>
+   * <td>c</td>
+   * <td>d</td>
+   * </tr>
+   * </table>
+   * 
+   * @param urlParameters the URL parameter string. Expected to contain something of the form
+   *        "a=b&c=d" etc (i.e. Key=Value separated by &).
+   * @return a map, with the key-values pairs representing the URL parameters.
+   */
+  private Map<String, String> mapUrlParameters(String urlParameters) {
+    final Map<String, String> map = new HashMap<>();
+    for (String pair : urlParameters.split("&")) {
+      String[] kv = pair.split("=");
+      map.put(kv[0], kv[1]);
+    }
+    return map;
+  }
+
+  
+}


[60/64] knox git commit: Merge branch 'master' into KNOX-998-Package_Restructuring

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/912c5360/gateway-test/src/test/java/org/apache/knox/gateway/GatewayBasicFuncTest.java
----------------------------------------------------------------------
diff --cc gateway-test/src/test/java/org/apache/knox/gateway/GatewayBasicFuncTest.java
index e97b47b,0000000..0d2e99c
mode 100644,000000..100644
--- a/gateway-test/src/test/java/org/apache/knox/gateway/GatewayBasicFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/knox/gateway/GatewayBasicFuncTest.java
@@@ -1,4434 -1,0 +1,4470 @@@
 +/**
 + * Licensed to the Apache Software Foundation (ASF) under one
 + * or more contributor license agreements.  See the NOTICE file
 + * distributed with this work for additional information
 + * regarding copyright ownership.  The ASF licenses this file
 + * to you under the Apache License, Version 2.0 (the
 + * "License"); you may not use this file except in compliance
 + * with the License.  You may obtain a copy of the License at
 + *
 + *     http://www.apache.org/licenses/LICENSE-2.0
 + *
 + * Unless required by applicable law or agreed to in writing, software
 + * distributed under the License is distributed on an "AS IS" BASIS,
 + * WITHOUT 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.knox.gateway;
 +
 +import java.io.ByteArrayOutputStream;
 +import java.io.File;
 +import java.io.FileFilter;
 +import java.io.FileNotFoundException;
 +import java.io.IOException;
 +import java.io.PrintStream;
 +import java.io.StringWriter;
 +import java.net.InetAddress;
 +import java.net.InetSocketAddress;
 +import java.net.URI;
 +import java.net.URISyntaxException;
 +import java.net.URL;
 +import java.nio.charset.Charset;
 +import java.util.HashMap;
 +import java.util.Map;
 +import java.util.Map.Entry;
 +import javax.ws.rs.core.MediaType;
 +
 +import com.jayway.restassured.http.ContentType;
 +import com.jayway.restassured.path.json.JsonPath;
 +import com.jayway.restassured.response.Cookie;
 +import com.jayway.restassured.response.Header;
 +import com.jayway.restassured.response.Response;
 +import com.jayway.restassured.specification.ResponseSpecification;
 +import com.mycila.xmltool.XMLDoc;
 +import com.mycila.xmltool.XMLTag;
 +import org.apache.commons.io.filefilter.WildcardFileFilter;
 +import org.apache.commons.lang3.ArrayUtils;
 +import org.apache.knox.gateway.util.KnoxCLI;
 +import org.apache.hadoop.test.TestUtils;
 +import org.apache.hadoop.test.category.MediumTests;
 +import org.apache.hadoop.test.category.VerifyTest;
 +import org.apache.hadoop.test.mock.MockRequestMatcher;
 +import org.apache.http.HttpHost;
 +import org.apache.http.HttpResponse;
 +import org.apache.http.HttpStatus;
 +import org.apache.http.auth.AuthScope;
 +import org.apache.http.auth.UsernamePasswordCredentials;
 +import org.apache.http.client.AuthCache;
 +import org.apache.http.client.methods.HttpGet;
 +import org.apache.http.client.methods.HttpPost;
 +import org.apache.http.client.protocol.ClientContext;
 +import org.apache.http.entity.StringEntity;
 +import org.apache.http.impl.auth.BasicScheme;
 +import org.apache.http.impl.client.BasicAuthCache;
 +import org.apache.http.impl.client.DefaultHttpClient;
 +import org.apache.http.protocol.BasicHttpContext;
 +import org.apache.http.util.EntityUtils;
 +import org.apache.velocity.Template;
 +import org.apache.velocity.VelocityContext;
 +import org.apache.velocity.app.VelocityEngine;
 +import org.apache.velocity.runtime.RuntimeConstants;
 +import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
 +import org.hamcrest.CoreMatchers;
 +import org.hamcrest.Matcher;
 +import org.hamcrest.MatcherAssert;
 +import org.hamcrest.Matchers;
 +import org.junit.After;
 +import org.junit.AfterClass;
 +import org.junit.Assert;
 +import org.junit.BeforeClass;
 +import org.junit.Test;
 +import org.junit.experimental.categories.Category;
 +import org.slf4j.Logger;
 +import org.slf4j.LoggerFactory;
 +
 +import static com.jayway.restassured.RestAssured.given;
 +import static org.apache.hadoop.test.TestUtils.LOG_ENTER;
 +import static org.apache.hadoop.test.TestUtils.LOG_EXIT;
 +import static org.hamcrest.CoreMatchers.*;
 +import static org.hamcrest.Matchers.containsString;
 +import static org.hamcrest.Matchers.greaterThan;
 +import static org.hamcrest.text.IsEmptyString.isEmptyString;
 +import static org.junit.Assert.assertThat;
++import static org.junit.Assert.assertTrue;
 +import static org.xmlmatchers.XmlMatchers.isEquivalentTo;
 +import static org.xmlmatchers.transform.XmlConverters.the;
 +import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs;
 +
 +@Category( { VerifyTest.class, MediumTests.class } )
 +public class GatewayBasicFuncTest {
 +
 +  private static final Charset UTF8 = Charset.forName("UTF-8");
 +
 +  // Uncomment to cause the test to hang after the gateway instance is setup.
 +  // This will allow the gateway instance to be hit directly via some external client.
 +//  @Test
 +//  public void hang() throws IOException {
 +//    System.out.println( "Server on port " + driver.gateway.getAddresses()[0].getPort() );
 +//    System.out.println();
 +//    System.in.read();
 +//  }
 +
 +  private static Logger log = LoggerFactory.getLogger( GatewayBasicFuncTest.class );
 +
-   public static GatewayTestDriver driver = new GatewayTestDriver();
++  private static GatewayTestDriver driver = new GatewayTestDriver();
 +
 +  // Controls the host name to which the gateway dispatch requests.  This may be the name of a sandbox VM
 +  // or an EC2 instance.  Currently only a single host is supported.
 +  private static final String TEST_HOST = "vm.local";
 +
 +  // Specifies if the test requests should go through the gateway or directly to the services.
 +  // This is frequently used to verify the behavior of the test both with and without the gateway.
 +  private static final boolean USE_GATEWAY = true;
 +
 +  // Specifies if the test requests should be sent to mock services or the real services.
 +  // This is frequently used to verify the behavior of the test both with and without mock services.
 +  private static final boolean USE_MOCK_SERVICES = true;
 +
 +  // Specifies if the GATEWAY_HOME created for the test should be deleted when the test suite is complete.
 +  // This is frequently used during debugging to keep the GATEWAY_HOME around for inspection.
 +  private static final boolean CLEANUP_TEST = true;
 +
 +//  private static final boolean USE_GATEWAY = false;
 +//  private static final boolean USE_MOCK_SERVICES = false;
 +//  private static final boolean CLEANUP_TEST = false;
 +
 +  /**
 +   * Creates a deployment of a gateway instance that all test methods will share.  This method also creates a
 +   * registry of sorts for all of the services that will be used by the test methods.
 +   * The createTopology method is used to create the topology file that would normally be read from disk.
 +   * The driver.setupGateway invocation is where the creation of GATEWAY_HOME occurs.
 +   * @throws Exception Thrown if any failure occurs.
 +   */
 +  @BeforeClass
 +  public static void setupSuite() throws Exception {
 +    //Log.setLog( new NoOpLogger() );
 +    LOG_ENTER();
 +    GatewayTestConfig config = new GatewayTestConfig();
-     config.setGatewayPath( "gateway" );
 +    driver.setResourceBase(GatewayBasicFuncTest.class);
 +    driver.setupLdap(0);
 +    driver.setupService("WEBHDFS", "http://" + TEST_HOST + ":50070/webhdfs", "/cluster/webhdfs", USE_MOCK_SERVICES);
 +    driver.setupService( "DATANODE", "http://" + TEST_HOST + ":50075/webhdfs", "/cluster/webhdfs/data", USE_MOCK_SERVICES );
 +    driver.setupService( "WEBHCAT", "http://" + TEST_HOST + ":50111/templeton", "/cluster/templeton", USE_MOCK_SERVICES );
 +    driver.setupService( "OOZIE", "http://" + TEST_HOST + ":11000/oozie", "/cluster/oozie", USE_MOCK_SERVICES );
 +    driver.setupService( "HIVE", "http://" + TEST_HOST + ":10000", "/cluster/hive", USE_MOCK_SERVICES );
 +    driver.setupService( "WEBHBASE", "http://" + TEST_HOST + ":60080", "/cluster/hbase", USE_MOCK_SERVICES );
 +    driver.setupService( "NAMENODE", "hdfs://" + TEST_HOST + ":8020", null, USE_MOCK_SERVICES );
 +    driver.setupService( "JOBTRACKER", "thrift://" + TEST_HOST + ":8021", null, USE_MOCK_SERVICES );
 +    driver.setupService( "RESOURCEMANAGER", "http://" + TEST_HOST + ":8088/ws", "/cluster/resourcemanager", USE_MOCK_SERVICES );
 +    driver.setupService( "FALCON", "http://" + TEST_HOST + ":15000", "/cluster/falcon", USE_MOCK_SERVICES );
 +    driver.setupService( "STORM", "http://" + TEST_HOST + ":8477", "/cluster/storm", USE_MOCK_SERVICES );
 +    driver.setupService( "STORM-LOGVIEWER", "http://" + TEST_HOST + ":8477", "/cluster/storm", USE_MOCK_SERVICES );
++    driver.setupService( "SOLR", "http://" + TEST_HOST + ":8983", "/cluster/solr", USE_MOCK_SERVICES );
 +    driver.setupGateway( config, "cluster", createTopology(), USE_GATEWAY );
 +    LOG_EXIT();
 +  }
 +
 +  @AfterClass
 +  public static void cleanupSuite() throws Exception {
 +    LOG_ENTER();
 +    if( CLEANUP_TEST ) {
 +      driver.cleanup();
 +    }
 +    LOG_EXIT();
 +  }
 +
 +  @After
 +  public void cleanupTest() {
 +    driver.reset();
 +  }
 +
 +  /**
 +   * Creates a topology that is deployed to the gateway instance for the test suite.
 +   * Note that this topology is shared by all of the test methods in this suite.
 +   * @return A populated XML structure for a topology file.
 +   */
 +  private static XMLTag createTopology() {
 +    XMLTag xml = XMLDoc.newDocument( true )
 +        .addRoot( "topology" )
 +          .addTag( "gateway" )
 +            .addTag( "provider" )
 +              .addTag( "role" ).addText( "webappsec" )
 +              .addTag("name").addText("WebAppSec")
 +              .addTag("enabled").addText("true")
 +              .addTag( "param" )
 +                .addTag("name").addText("csrf.enabled")
 +                .addTag("value").addText("true").gotoParent().gotoParent()
 +            .addTag("provider")
 +              .addTag("role").addText("authentication")
 +              .addTag("name").addText("ShiroProvider")
 +              .addTag("enabled").addText("true")
 +              .addTag( "param" )
 +                .addTag("name").addText("main.ldapRealm")
 +                .addTag("value").addText("KnoxLdapRealm").gotoParent()
 +              .addTag( "param" )
 +                .addTag( "name" ).addText( "main.ldapRealm.userDnTemplate" )
 +                .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" ).gotoParent()
 +              .addTag( "param" )
 +                .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
 +                .addTag( "value" ).addText( driver.getLdapUrl() ).gotoParent()
 +              .addTag( "param" )
 +                .addTag( "name" ).addText( "main.ldapRealm.contextFactory.authenticationMechanism" )
 +                .addTag( "value" ).addText( "simple" ).gotoParent()
 +              .addTag( "param" )
 +                .addTag( "name" ).addText( "urls./**" )
 +                .addTag( "value" ).addText( "authcBasic" ).gotoParent().gotoParent()
 +            .addTag("provider")
 +              .addTag("role").addText("identity-assertion")
 +              .addTag("enabled").addText("true")
 +              .addTag("name").addText("Default").gotoParent()
 +            .addTag("provider")
 +              .addTag( "role" ).addText( "authorization" )
 +              .addTag( "enabled" ).addText( "true" )
 +              .addTag("name").addText("AclsAuthz").gotoParent()
 +              .addTag("param")
 +                .addTag("name").addText( "webhdfs-acl" )
 +                .addTag("value").addText( "hdfs;*;*" ).gotoParent()
 +          .gotoRoot()
 +          .addTag("service")
 +            .addTag("role").addText("WEBHDFS")
 +            .addTag("url").addText(driver.getRealUrl("WEBHDFS")).gotoParent()
 +          .addTag( "service" )
 +            .addTag( "role" ).addText( "NAMENODE" )
 +            .addTag( "url" ).addText( driver.getRealUrl( "NAMENODE" ) ).gotoParent()
 +          .addTag( "service" )
 +            .addTag( "role" ).addText( "DATANODE" )
 +            .addTag( "url" ).addText( driver.getRealUrl( "DATANODE" ) ).gotoParent()
 +          .addTag( "service" )
 +            .addTag( "role" ).addText( "JOBTRACKER" )
 +            .addTag( "url" ).addText( driver.getRealUrl( "JOBTRACKER" ) ).gotoParent()
 +          .addTag( "service" )
 +            .addTag( "role" ).addText( "WEBHCAT" )
 +            .addTag( "url" ).addText( driver.getRealUrl( "WEBHCAT" ) ).gotoParent()
 +          .addTag( "service" )
 +            .addTag( "role" ).addText( "OOZIE" )
 +            .addTag( "url" ).addText( driver.getRealUrl( "OOZIE" ) ).gotoParent()
 +          .addTag( "service" )
 +            .addTag( "role" ).addText( "HIVE" )
 +            .addTag( "url" ).addText( driver.getRealUrl( "HIVE" ) ).gotoParent()
 +          .addTag( "service" )
 +            .addTag( "role" ).addText( "WEBHBASE" )
 +            .addTag( "url" ).addText( driver.getRealUrl( "WEBHBASE" ) ).gotoParent()
 +        .addTag("service")
 +            .addTag("role").addText("RESOURCEMANAGER")
 +            .addTag("url").addText(driver.getRealUrl("RESOURCEMANAGER")).gotoParent()
 +        .addTag("service")
 +            .addTag("role").addText("FALCON")
 +            .addTag("url").addText(driver.getRealUrl("FALCON")).gotoParent()
 +        .addTag("service")
 +            .addTag("role").addText("STORM")
 +            .addTag("url").addText(driver.getRealUrl("STORM")).gotoParent()
 +        .addTag("service")
 +            .addTag("role").addText("STORM-LOGVIEWER")
 +            .addTag("url").addText(driver.getRealUrl("STORM-LOGVIEWER")).gotoParent()
 +        .addTag("service")
++            .addTag("role").addText("SOLR")
++            .addTag("url").addText(driver.getRealUrl("SOLR")).gotoParent()
++        .addTag("service")
 +        .addTag("role").addText("SERVICE-TEST")
 +        .gotoRoot();
 +//     System.out.println( "GATEWAY=" + xml.toString() );
 +    return xml;
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testBasicJsonUseCase() throws IOException {
 +    LOG_ENTER();
 +    String root = "/tmp/GatewayBasicFuncTest/testBasicJsonUseCase";
 +    String username = "hdfs";
 +    String password = "hdfs-password";
 +    /* Create a directory.
 +    curl -i -X PUT "http://<HOST>:<PORT>/<PATH>?op=MKDIRS[&permission=<OCTAL>]"
 +
 +    The client receives a respond with a boolean JSON object:
 +    HTTP/1.1 HttpStatus.SC_OK OK
 +    Content-Type: application/json
 +    Transfer-Encoding: chunked
 +
 +    {"boolean": true}
 +    */
 +    driver.getMock( "WEBHDFS" )
 +        .expect()
 +        .method( "PUT" )
 +        .pathInfo( "/v1" + root + "/dir" )
 +        .queryParam( "op", "MKDIRS" )
 +        .queryParam( "user.name", username )
 +        .respond()
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "webhdfs-success.json" ) )
 +        .contentType( "application/json" );
 +    Cookie cookie = given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .queryParam( "op", "MKDIRS" )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_OK )
 +        .header( "Set-Cookie", containsString( "JSESSIONID" ) )
 +        .header( "Set-Cookie", containsString( "HttpOnly" ) )
 +        .contentType( "application/json" )
 +        .content( "boolean", is( true ) )
 +        .when().put( driver.getUrl( "WEBHDFS" ) + "/v1" + root + "/dir" ).getDetailedCookie( "JSESSIONID" );
 +    assertThat( cookie.isSecured(), is( true ) );
 +    assertThat( cookie.getPath(), is( "/gateway/cluster" ) );
 +    assertThat( cookie.getValue().length(), greaterThan( 16 ) );
 +    driver.assertComplete();
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testBasicOutboundHeaderUseCase() throws IOException {
 +    LOG_ENTER();
 +    String root = "/tmp/GatewayBasicFuncTest/testBasicOutboundHeaderUseCase";
 +    String username = "hdfs";
 +    String password = "hdfs-password";
 +    InetSocketAddress gatewayAddress = driver.gateway.getAddresses()[0];
 +    String gatewayHostName = gatewayAddress.getHostName();
 +    String gatewayAddrName = InetAddress.getByName(gatewayHostName).getHostAddress();
 +
 +    driver.getMock( "WEBHDFS" )
 +        .expect()
 +        .method( "PUT" )
 +        .pathInfo( "/v1" + root + "/dir/file" )
 +        .header( "Host", driver.getRealAddr( "WEBHDFS" ) )
 +        .queryParam( "op", "CREATE" )
 +        .queryParam( "user.name", username )
 +        .respond()
 +        .status( HttpStatus.SC_TEMPORARY_REDIRECT )
 +        .header("Location", driver.getRealUrl("DATANODE") + "/v1" + root + "/dir/file?op=CREATE&user.name=hdfs");
 +    Response response = given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .queryParam( "op", "CREATE" )
 +        .expect()
 +        //.log().ifError()
 +        .statusCode( HttpStatus.SC_TEMPORARY_REDIRECT )
 +        .when().put( driver.getUrl("WEBHDFS") + "/v1" + root + "/dir/file" );
 +    String location = response.getHeader( "Location" );
 +    //System.out.println( location );
 +    log.debug( "Redirect location: " + response.getHeader( "Location" ) );
 +    if( driver.isUseGateway() ) {
 +      MatcherAssert.assertThat( location, anyOf(
 +          startsWith( "http://" + gatewayHostName + ":" + gatewayAddress.getPort() + "/" ),
 +          startsWith( "http://" + gatewayAddrName + ":" + gatewayAddress.getPort() + "/" ) ) );
 +      MatcherAssert.assertThat( location, containsString( "?_=" ) );
 +    }
 +    MatcherAssert.assertThat(location, not(containsString("host=")));
 +    MatcherAssert.assertThat(location, not(containsString("port=")));
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testBasicOutboundEncodedHeaderUseCase() throws IOException {
 +    LOG_ENTER();
 +    String root = "/tmp/GatewayBasicFuncTest/testBasicOutboundHeaderUseCase";
 +    String username = "hdfs";
 +    String password = "hdfs-password";
 +    InetSocketAddress gatewayAddress = driver.gateway.getAddresses()[0];
 +    String gatewayHostName = gatewayAddress.getHostName();
 +    String gatewayAddrName = InetAddress.getByName(gatewayHostName).getHostAddress();
 +
 +    driver.getMock( "WEBHDFS" )
 +        .expect()
 +        .method( "PUT" )
 +        .pathInfo( "/v1" + root + "/dir/fileレポー" )
 +        .header( "Host", driver.getRealAddr( "WEBHDFS" ) )
 +        .queryParam( "op", "CREATE" )
 +        .queryParam( "user.name", username )
 +        .respond()
 +        .status( HttpStatus.SC_TEMPORARY_REDIRECT )
 +        .header("Location", driver.getRealUrl("DATANODE") + "/v1" + root + "/dir/file%E3%83%AC%E3%83%9D%E3%83%BC?op=CREATE&user.name=hdfs");
 +    Response response = given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .queryParam( "op", "CREATE" )
 +        .expect()
 +        //.log().ifError()
 +        .statusCode( HttpStatus.SC_TEMPORARY_REDIRECT )
 +        .when().put( driver.getUrl("WEBHDFS") + "/v1" + root + "/dir/fileレポー" );
 +//        .when().put( driver.getUrl("WEBHDFS") + "/v1" + root + "/dir/file%E3%83%AC%E3%83%9D%E3%83%BC" );
 +    String location = response.getHeader( "Location" );
 +    //System.out.println( location );
 +    log.debug( "Redirect location: " + response.getHeader( "Location" ) );
 +    if( driver.isUseGateway() ) {
 +      MatcherAssert.assertThat( location, containsString("/dir/file%E3%83%AC%E3%83%9D%E3%83%BC") );
 +    }
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testHdfsTildeUseCase() throws IOException {
 +    LOG_ENTER();
 +    String root = "/tmp/GatewayBasicFuncTest/testHdfsTildeUseCase";
 +    String username = "hdfs";
 +    String password = "hdfs-password";
 +    InetSocketAddress gatewayAddress = driver.gateway.getAddresses()[0];
 +
 +    // Attempt to delete the test directory in case a previous run failed.
 +    // Ignore any result.
 +    // Cleanup anything that might have been leftover because the test failed previously.
 +    driver.getMock( "WEBHDFS" )
 +        .expect()
 +        .method( "DELETE" )
 +        .from( "testHdfsTildeUseCase" )
 +        .pathInfo( "/v1/user/hdfs" + root )
 +        .queryParam( "op", "DELETE" )
 +        .queryParam( "user.name", username )
 +        .queryParam( "recursive", "true" )
 +        .respond()
 +        .status( HttpStatus.SC_OK );
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .queryParam( "op", "DELETE" )
 +        .queryParam( "recursive", "true" )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_OK )
 +        .when().delete( driver.getUrl( "WEBHDFS" ) + "/v1/~" + root + ( driver.isUseGateway() ? "" : "?user.name=" + username ) );
 +    driver.assertComplete();
 +
 +    driver.getMock( "WEBHDFS" )
 +        .expect()
 +        .method( "PUT" )
 +        .pathInfo( "/v1/user/hdfs/dir" )
 +        .queryParam( "op", "MKDIRS" )
 +        .queryParam( "user.name", username )
 +        .respond()
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "webhdfs-success.json" ) )
 +        .contentType("application/json");
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .queryParam( "op", "MKDIRS" )
 +        .expect()
 +        //.log().all();
 +        .statusCode( HttpStatus.SC_OK )
 +        .contentType( "application/json" )
 +        .content( "boolean", is( true ) )
 +        .when().put( driver.getUrl( "WEBHDFS" ) + "/v1/~/dir" );
 +    driver.assertComplete();
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testBasicHdfsUseCase() throws IOException {
 +    LOG_ENTER();
 +    String root = "/tmp/GatewayBasicFuncTest/testBasicHdfsUseCase";
 +    String username = "hdfs";
 +    String password = "hdfs-password";
 +    InetSocketAddress gatewayAddress = driver.gateway.getAddresses()[0];
 +    String gatewayHostName = gatewayAddress.getHostName();
 +    String gatewayAddrName = InetAddress.getByName( gatewayHostName ).getHostAddress();
 +
 +    // Attempt to delete the test directory in case a previous run failed.
 +    // Ignore any result.
 +    // Cleanup anything that might have been leftover because the test failed previously.
 +    driver.getMock( "WEBHDFS" )
 +        .expect()
 +        .method( "DELETE" )
 +        .from( "testBasicHdfsUseCase-1" )
 +        .pathInfo( "/v1" + root )
 +        .queryParam( "op", "DELETE" )
 +        .queryParam( "user.name", username )
 +        .queryParam( "recursive", "true" )
 +        .respond()
 +        .status( HttpStatus.SC_OK );
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .queryParam( "op", "DELETE" )
 +        .queryParam( "recursive", "true" )
 +        .expect()
 +        //.log().all()
 +        .statusCode( HttpStatus.SC_OK )
 +        .when().delete( driver.getUrl( "WEBHDFS" ) + "/v1" + root + ( driver.isUseGateway() ? "" : "?user.name=" + username ) );
 +    driver.assertComplete();
 +
 +    /* Create a directory.
 +    curl -i -X PUT "http://<HOST>:<PORT>/<PATH>?op=MKDIRS[&permission=<OCTAL>]"
 +
 +    The client receives a respond with a boolean JSON object:
 +    HTTP/1.1 HttpStatus.SC_OK OK
 +    Content-Type: application/json
 +    Transfer-Encoding: chunked
 +
 +    {"boolean": true}
 +    */
 +    driver.getMock( "WEBHDFS" )
 +        .expect()
 +        .method( "PUT" )
 +        .pathInfo( "/v1" + root + "/dir" )
 +        .queryParam( "op", "MKDIRS" )
 +        .queryParam( "user.name", username )
 +        .respond()
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "webhdfs-success.json" ) )
 +        .contentType( "application/json" );
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .queryParam( "op", "MKDIRS" )
 +        .expect()
 +        //.log().all();
 +        .statusCode( HttpStatus.SC_OK )
 +        .contentType( "application/json" )
 +        .content( "boolean", is( true ) )
 +        .when().put( driver.getUrl( "WEBHDFS" ) + "/v1" + root + "/dir" );
 +    driver.assertComplete();
 +
 +    driver.getMock( "WEBHDFS" )
 +        .expect()
 +        .method( "GET" )
 +        .pathInfo( "/v1" + root )
 +        .queryParam( "op", "LISTSTATUS" )
 +        .queryParam( "user.name", username )
 +        .respond()
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "webhdfs-liststatus-test.json" ) )
 +        .contentType( "application/json" );
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .queryParam( "op", "LISTSTATUS" )
 +        .expect()
 +        //.log().ifError()
 +        .statusCode( HttpStatus.SC_OK )
 +        .content( "FileStatuses.FileStatus[0].pathSuffix", is( "dir" ) )
 +        .when().get( driver.getUrl( "WEBHDFS" ) + "/v1" + root );
 +    driver.assertComplete();
 +
 +    //NEGATIVE: Test a bad password.
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, "invalid-password" )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .queryParam( "op", "LISTSTATUS" )
 +        .expect()
 +        //.log().ifError()
 +        .statusCode( HttpStatus.SC_UNAUTHORIZED )
 +        .when().get( driver.getUrl( "WEBHDFS" ) + "/v1" + root );
 +    driver.assertComplete();
 +
 +    //NEGATIVE: Test a bad user.
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( "hdfs-user", "hdfs-password" )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .queryParam( "op", "LISTSTATUS" )
 +        .expect()
 +        //.log().ifError()
 +        .statusCode( HttpStatus.SC_UNAUTHORIZED )
 +        .when().get( driver.getUrl( "WEBHDFS" ) + "/v1" + root );
 +    driver.assertComplete();
 +
 +    //NEGATIVE: Test a valid but unauthorized user.
 +    given()
 +      //.log().all()
 +      .auth().preemptive().basic( "mapred-user", "mapred-password" )
 +      .header("X-XSRF-Header", "jksdhfkhdsf")
 +      .queryParam( "op", "LISTSTATUS" )
 +      .expect()
 +      //.log().ifError()
 +      .statusCode( HttpStatus.SC_UNAUTHORIZED )
 +      .when().get( driver.getUrl( "WEBHDFS" ) + "/v1" + root );
 +
 +    /* Add a file.
 +    curl -i -X PUT "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=CREATE
 +                       [&overwrite=<true|false>][&blocksize=<LONG>][&replication=<SHORT>]
 +                     [&permission=<OCTAL>][&buffersize=<INT>]"
 +
 +    The expect is redirected to a datanode where the file data is to be written:
 +    HTTP/1.1 307 TEMPORARY_REDIRECT
 +    Location: http://<DATANODE>:<PORT>/webhdfs/v1/<PATH>?op=CREATE...
 +    Content-Length: 0
 +
 +    Step 2: Submit another HTTP PUT expect using the URL in the Location header with the file data to be written.
 +    curl -i -X PUT -T <LOCAL_FILE> "http://<DATANODE>:<PORT>/webhdfs/v1/<PATH>?op=CREATE..."
 +
 +    The client receives a HttpStatus.SC_CREATED Created respond with zero content length and the WebHDFS URI of the file in the Location header:
 +    HTTP/1.1 HttpStatus.SC_CREATED Created
 +    Location: webhdfs://<HOST>:<PORT>/<PATH>
 +    Content-Length: 0
 +    */
 +    driver.getMock( "WEBHDFS" )
 +        .expect()
 +        .method( "PUT" )
 +        .pathInfo( "/v1" + root + "/dir/file" )
 +        .queryParam( "op", "CREATE" )
 +        .queryParam( "user.name", username )
 +        .respond()
 +        .status( HttpStatus.SC_TEMPORARY_REDIRECT )
 +        .header( "Location", driver.getRealUrl( "DATANODE" ) + "/v1" + root + "/dir/file?op=CREATE&user.name=hdfs" );
 +    driver.getMock( "DATANODE" )
 +        .expect()
 +        .method( "PUT" )
 +        .pathInfo( "/v1" + root + "/dir/file" )
 +        .queryParam( "op", "CREATE" )
 +        .queryParam( "user.name", username )
 +        .contentType( "text/plain" )
 +        .content( driver.getResourceBytes( "test.txt" ) )
 +            //.content( driver.gerResourceBytes( "hadoop-examples.jar" ) )
 +        .respond()
 +        .status( HttpStatus.SC_CREATED )
 +        .header( "Location", "webhdfs://" + driver.getRealAddr( "DATANODE" ) + "/v1" + root + "/dir/file" );
 +    Response response = given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .queryParam( "op", "CREATE" )
 +        .expect()
 +        //.log().ifError()
 +        .statusCode( HttpStatus.SC_TEMPORARY_REDIRECT )
 +        .when().put( driver.getUrl("WEBHDFS") + "/v1" + root + "/dir/file" );
 +    String location = response.getHeader( "Location" );
 +    log.debug( "Redirect location: " + response.getHeader( "Location" ) );
 +    if( driver.isUseGateway() ) {
 +      MatcherAssert.assertThat( location, anyOf(
 +          startsWith( "http://" + gatewayHostName + ":" + gatewayAddress.getPort() + "/" ),
 +          startsWith( "http://" + gatewayAddrName + ":" + gatewayAddress.getPort() + "/" ) ) );
 +      MatcherAssert.assertThat( location, containsString( "?_=" ) );
 +    }
 +    MatcherAssert.assertThat( location, not( containsString( "host=" ) ) );
 +    MatcherAssert.assertThat( location, not( containsString( "port=" ) ) );
 +    response = given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "test.txt" ) )
 +        .contentType( "text/plain" )
 +        .expect()
 +        //.log().ifError()
 +        .statusCode( HttpStatus.SC_CREATED )
 +        .when().put( location );
 +    location = response.getHeader( "Location" );
 +    log.debug( "Created location: " + location );
 +    if( driver.isUseGateway() ) {
 +      MatcherAssert.assertThat( location, anyOf(
 +          startsWith( "http://" + gatewayHostName + ":" + gatewayAddress.getPort() + "/" ),
 +          startsWith( "http://" + gatewayAddrName + ":" + gatewayAddress.getPort() + "/" ) ) );
 +    }
 +    driver.assertComplete();
 +
 +    /* Get the file.
 +    curl -i -L "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=OPEN
 +                       [&offset=<LONG>][&length=<LONG>][&buffersize=<INT>]"
 +
 +    The expect is redirected to a datanode where the file data can be read:
 +    HTTP/1.1 307 TEMPORARY_REDIRECT
 +    Location: http://<DATANODE>:<PORT>/webhdfs/v1/<PATH>?op=OPEN...
 +    Content-Length: 0
 +
 +    The client follows the redirect to the datanode and receives the file data:
 +    HTTP/1.1 HttpStatus.SC_OK OK
 +    Content-Type: application/octet-stream
 +    Content-Length: 22
 +
 +    Hello, webhdfs user!
 +    */
 +    driver.getMock( "WEBHDFS" )
 +        .expect()
 +        .method( "GET" )
 +        .pathInfo( "/v1" + root + "/dir/file" )
 +        .queryParam( "op", "OPEN" )
 +        .queryParam( "user.name", username )
 +        .respond()
 +        .status( HttpStatus.SC_TEMPORARY_REDIRECT )
 +        .header( "Location", driver.getRealUrl( "DATANODE" ) + "/v1" + root + "/dir/file?op=OPEN&user.name=hdfs" );
 +    driver.getMock( "DATANODE" )
 +        .expect()
 +        .method( "GET" )
 +        .pathInfo( "/v1" + root + "/dir/file" )
 +        .queryParam( "op", "OPEN" )
 +        .queryParam( "user.name", username )
 +        .respond()
 +        .status( HttpStatus.SC_OK )
 +        .contentType( "text/plain" )
 +        .content( driver.getResourceBytes( "test.txt" ) );
 +    given()
 +        //.log().all()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .queryParam( "op", "OPEN" )
 +        .expect()
 +        //.log().ifError()
 +        .statusCode( HttpStatus.SC_OK )
 +        .content( is( "TEST" ) )
 +        .when().get( driver.getUrl("WEBHDFS") + "/v1" + root + "/dir/file" );
 +    driver.assertComplete();
 +
 +    /* Delete the directory.
 +    curl -i -X DELETE "http://<host>:<port>/webhdfs/v1/<path>?op=DELETE
 +                                 [&recursive=<true|false>]"
 +
 +    The client receives a respond with a boolean JSON object:
 +    HTTP/1.1 HttpStatus.SC_OK OK
 +    Content-Type: application/json
 +    Transfer-Encoding: chunked
 +
 +    {"boolean": true}
 +    */
 +    // Mock the interaction with the namenode.
 +    driver.getMock( "WEBHDFS" )
 +        .expect()
 +        .from( "testBasicHdfsUseCase-1" )
 +        .method( "DELETE" )
 +        .pathInfo( "/v1" + root )
 +        .queryParam( "op", "DELETE" )
 +        .queryParam( "user.name", username )
 +        .queryParam( "recursive", "true" )
 +        .respond()
 +        .status( HttpStatus.SC_OK );
 +    given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .queryParam( "op", "DELETE" )
 +        .queryParam( "recursive", "true" )
 +        .expect()
 +        //.log().ifError()
 +        .statusCode( HttpStatus.SC_OK )
 +        .when().delete( driver.getUrl( "WEBHDFS" ) + "/v1" + root );
 +    driver.assertComplete();
 +    LOG_EXIT();
 +  }
 +
 +  // User hdfs in groups hadoop, hdfs
 +  // User mapred in groups hadoop, mapred
 +  // User hcat in group hcat
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testPmHdfsM1UseCase() throws IOException {
 +    LOG_ENTER();
 +    String root = "/tmp/GatewayBasicFuncTest/testPmHdfdM1UseCase";
 +    String userA = "hdfs";
 +    String passA = "hdfs-password";
 +    String userB = "mapred";
 +    String passB = "mapred-password";
 +    String userC = "hcat";
 +    String passC = "hcat-password";
 +    String groupA = "hdfs";
 +    String groupB = "mapred";
 +    String groupAB = "hadoop";
 +    String groupC = "hcat";
 +
 +    deleteFile( userA, passA, root, "true", 200 );
 +
 +    createDir( userA, passA, groupA, root + "/dirA700", "700", 200, 200 );
 +    createDir( userA, passA, groupA, root + "/dirA770", "770", 200, 200 );
 +    createDir( userA, passA, groupA, root + "/dirA707", "707", 200, 200 );
 +    createDir( userA, passA, groupA, root + "/dirA777", "777", 200, 200 );
 +    createDir( userA, passA, groupAB, root + "/dirAB700", "700", 200, 200 );
 +    createDir( userA, passA, groupAB, root + "/dirAB770", "770", 200, 200 );
 +    createDir( userA, passA, groupAB, root + "/dirAB707", "707", 200, 200 );
 +    createDir( userA, passA, groupAB, root + "/dirAB777", "777", 200, 200 );
 +
 +    // CREATE: Files
 +    // userA:groupA
 +    createFile( userA, passA, groupA, root + "/dirA700/fileA700", "700", "text/plain", "small1.txt", 307, 201, 200 );
 +    createFile( userA, passA, groupA, root + "/dirA770/fileA770", "770", "text/plain", "small1.txt", 307, 201, 200 );
 +    createFile( userA, passA, groupA, root + "/dirA707/fileA707", "707", "text/plain", "small1.txt", 307, 201, 200 );
 +    createFile( userA, passA, groupA, root + "/dirA777/fileA777", "777", "text/plain", "small1.txt", 307, 201, 200 );
 +    // userA:groupAB
 +    createFile( userA, passA, groupAB, root + "/dirAB700/fileAB700", "700", "text/plain", "small1.txt", 307, 201, 200 );
 +    createFile( userA, passA, groupAB, root + "/dirAB770/fileAB770", "770", "text/plain", "small1.txt", 307, 201, 200 );
 +    createFile( userA, passA, groupAB, root + "/dirAB707/fileAB707", "707", "text/plain", "small1.txt", 307, 201, 200 );
 +    createFile( userA, passA, groupAB, root + "/dirAB777/fileAB777", "777", "text/plain", "small1.txt", 307, 201, 200 );
 +    // userB:groupB
 +    createFile( userB, passB, groupB, root + "/dirA700/fileB700", "700", "text/plain", "small1.txt", 307, 403, 0 );
 +    createFile( userB, passB, groupB, root + "/dirA770/fileB700", "700", "text/plain", "small1.txt", 307, 403, 0 );
 +//kam:20130219[ chmod seems to be broken at least in Sandbox 1.2
 +//    createFile( userB, passB, groupB, root + "/dirA707/fileB700", "700", "text/plain", "small1.txt", 307, 201, 200 );
 +//    createFile( userB, passB, groupB, root + "/dirA777/fileB700", "700", "text/plain", "small1.txt", 307, 201, 200 );
 +//kam]
 +    // userB:groupAB
 +    createFile( userB, passB, groupAB, root + "/dirA700/fileBA700", "700", "text/plain", "small1.txt", 307, 403, 0 );
 +    createFile( userB, passB, groupAB, root + "/dirA770/fileBA700", "700", "text/plain", "small1.txt", 307, 403, 0 );
 +    createFile( userB, passB, groupAB, root + "/dirA707/fileBA700", "700", "text/plain", "small1.txt", 307, 201, 200 );
 +    createFile( userB, passB, groupAB, root + "/dirA777/fileBA700", "700", "text/plain", "small1.txt", 307, 201, 200 );
 +    // userC:groupC
 +    createFile( userC, passC, groupC, root + "/dirA700/fileC700", "700", "text/plain", "small1.txt", 307, 403, 0 );
 +    createFile( userC, passC, groupC, root + "/dirA770/fileC700", "700", "text/plain", "small1.txt", 307, 403, 0 );
 +//kam:20130219[ chmod seems to be broken at least in Sandbox 1.2
 +//    createFile( userC, passC, groupC, root + "/dirA707/fileC700", "700", "text/plain", "small1.txt", 307, 201, 200 );
 +//    createFile( userC, passC, groupC, root + "/dirA777/fileC700", "700", "text/plain", "small1.txt", 307, 201, 200 );
 +//kam]
 +
 +    // READ
 +    // userA
 +    readFile( userA, passA, root + "/dirA700/fileA700", "text/plain", "small1.txt", HttpStatus.SC_OK );
 +    readFile( userA, passA, root + "/dirA770/fileA770", "text/plain", "small1.txt", HttpStatus.SC_OK );
 +    readFile( userA, passA, root + "/dirA707/fileA707", "text/plain", "small1.txt", HttpStatus.SC_OK );
 +    readFile( userA, passA, root + "/dirA777/fileA777", "text/plain", "small1.txt", HttpStatus.SC_OK );
 +    // userB:groupB
 +    readFile( userB, passB, root + "/dirA700/fileA700", "text/plain", "small1.txt", HttpStatus.SC_FORBIDDEN );
 +    readFile( userB, passB, root + "/dirA770/fileA770", "text/plain", "small1.txt", HttpStatus.SC_FORBIDDEN );
 +    readFile( userB, passB, root + "/dirA707/fileA707", "text/plain", "small1.txt", HttpStatus.SC_OK );
 +    readFile( userB, passB, root + "/dirA777/fileA777", "text/plain", "small1.txt", HttpStatus.SC_OK );
 +    // userB:groupAB
 +    readFile( userB, passB, root + "/dirAB700/fileAB700", "text/plain", "small1.txt", HttpStatus.SC_FORBIDDEN );
 +    readFile( userB, passB, root + "/dirAB770/fileAB770", "text/plain", "small1.txt", HttpStatus.SC_FORBIDDEN );
 +    readFile( userB, passB, root + "/dirAB707/fileAB707", "text/plain", "small1.txt", HttpStatus.SC_FORBIDDEN );
 +    readFile( userB, passB, root + "/dirAB777/fileAB777", "text/plain", "small1.txt", HttpStatus.SC_OK );
 +    // userC:groupC
 +    readFile( userC, passC, root + "/dirA700/fileA700", "text/plain", "small1.txt", HttpStatus.SC_FORBIDDEN );
 +    readFile( userC, passC, root + "/dirA770/fileA770", "text/plain", "small1.txt", HttpStatus.SC_FORBIDDEN );
 +    readFile( userC, passC, root + "/dirA707/fileA707", "text/plain", "small1.txt", HttpStatus.SC_OK );
 +    readFile( userC, passC, root + "/dirA777/fileA777", "text/plain", "small1.txt", HttpStatus.SC_OK );
 +
 +    //NEGATIVE: Test a bad password.
 +    if( driver.isUseGateway() ) {
 +      given()
 +          //.log().all()
 +          .auth().preemptive().basic( userA, "invalid-password" )
 +          .header("X-XSRF-Header", "jksdhfkhdsf")
 +          .queryParam( "op", "OPEN" )
 +          .expect()
 +          //.log().all()
 +          .statusCode( HttpStatus.SC_UNAUTHORIZED )
 +          .when().get( driver.getUrl("WEBHDFS") + "/v1" + root + "/dirA700/fileA700" );
 +    }
 +    driver.assertComplete();
 +
 +    // UPDATE (Negative First)
 +    updateFile( userC, passC, root + "/dirA700/fileA700", "text/plain", "small2.txt", 307, 403 );
 +    updateFile( userB, passB, root + "/dirAB700/fileAB700", "text/plain", "small2.txt", 307, 403 );
 +    updateFile( userB, passB, root + "/dirAB770/fileAB700", "text/plain", "small2.txt", 307, 403 );
 +    updateFile( userB, passB, root + "/dirAB770/fileAB770", "text/plain", "small2.txt", 307, 403 );
 +    updateFile( userA, passA, root + "/dirA700/fileA700", "text/plain", "small2.txt", 307, 201 );
 +
 +    // DELETE (Negative First)
 +    deleteFile( userC, passC, root + "/dirA700/fileA700", "false", HttpStatus.SC_FORBIDDEN );
 +    deleteFile( userB, passB, root + "/dirAB700/fileAB700", "false", HttpStatus.SC_FORBIDDEN );
 +    deleteFile( userB, passB, root + "/dirAB770/fileAB770", "false", HttpStatus.SC_FORBIDDEN );
 +    deleteFile( userA, passA, root + "/dirA700/fileA700", "false", HttpStatus.SC_OK );
 +
 +    // Cleanup anything that might have been leftover because the test failed previously.
 +    deleteFile( userA, passA, root, "true", HttpStatus.SC_OK );
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testJavaMapReduceViaWebHCat() throws IOException {
 +    LOG_ENTER();
 +    String root = "/tmp/GatewayBasicFuncTest/testJavaMapReduceViaWebHCat";
 +    String user = "mapred";
 +    String pass = "mapred-password";
 +    String group = "mapred";
 +//    String user = "hcat";
 +//    String pass = "hcat-password";
 +//    String group = "hcat";
 +
 +    // Cleanup anything that might have been leftover because the test failed previously.
 +    deleteFile( user, pass, root, "true", HttpStatus.SC_OK );
 +
 +    /* Put the mapreduce code into HDFS. (hadoop-examples.jar)
 +    curl -X PUT --data-binary @hadoop-examples.jar 'http://192.168.1.163:8888/org.apache.org.apache.hadoop.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/hadoop-examples.jar?user.name=hdfs&op=CREATE'
 +     */
 +    createFile( user, pass, null, root+"/hadoop-examples.jar", "777", "application/octet-stream", findHadoopExamplesJar(), 307, 201, 200 );
 +
 +    /* Put the data file into HDFS (changes.txt)
 +    curl -X PUT --data-binary @changes.txt 'http://192.168.1.163:8888/org.apache.org.apache.hadoop.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/input/changes.txt?user.name=hdfs&op=CREATE'
 +     */
 +    createFile( user, pass, null, root+"/input/changes.txt", "777", "text/plain", "changes.txt", 307, 201, 200 );
 +
 +    /* Create the output directory
 +    curl -X PUT 'http://192.168.1.163:8888/org.apache.org.apache.hadoop.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/output?op=MKDIRS&user.name=hdfs'
 +    */
 +    createDir( user, pass, null, root+"/output", "777", 200, 200 );
 +
 +    /* Submit the job
 +    curl -d user.name=hdfs -d jar=wordcount/hadoop-examples.jar -d class=org.apache.WordCount -d arg=wordcount/input -d arg=wordcount/output 'http://localhost:8888/org.apache.org.apache.hadoop.gateway/cluster/templeton/v1/mapreduce/jar'
 +    {"id":"job_201210301335_0059"}
 +    */
 +    String job = submitJava(
 +        user, pass,
 +        root+"/hadoop-examples.jar", "org.apache.WordCount",
 +        root+"/input", root+"/output",
 +        200 );
 +
 +    /* Get the job status
 +    curl 'http://vm:50111/templeton/v1/queue/:jobid?user.name=hdfs'
 +    */
 +    queryQueue( user, pass, job );
 +
 +    // Can't really check for the output here because the job won't be done.
 +    /* Retrieve results
 +    curl 'http://192.168.1.163:8888/org.apache.org.apache.hadoop.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/input?op=LISTSTATUS'
 +    */
 +
 +    if( CLEANUP_TEST ) {
 +      // Cleanup anything that might have been leftover because the test failed previously.
 +      deleteFile( user, pass, root, "true", HttpStatus.SC_OK );
 +    }
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testPigViaWebHCat() throws IOException {
 +    LOG_ENTER();
 +    String root = "/tmp/GatewayWebHCatFuncTest/testPigViaWebHCat";
 +    String user = "mapred";
 +    String pass = "mapred-password";
 +    String group = "mapred";
 +
 +    // Cleanup if previous run failed.
 +    deleteFile( user, pass, root, "true", 200, 404 );
 +
 +    // Post the data to HDFS
 +    createFile( user, pass, null, root + "/passwd.txt", "777", "text/plain", "passwd.txt", 307, 201, 200 );
 +
 +    // Post the script to HDFS
 +    createFile( user, pass, null, root+"/script.pig", "777", "text/plain", "script.pig", 307, 201, 200 );
 +
 +    // Create the output directory
 +    createDir( user, pass, null, root + "/output", "777", 200, 200 );
 +
 +    // Submit the job
 +    submitPig( user, pass, group, root + "/script.pig", "-v", root + "/output", 200 );
 +
 +    // Check job status (if possible)
 +    // Check output (if possible)
 +
 +    // Cleanup
 +    deleteFile( user, pass, root, "true", 200 );
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testHiveViaWebHCat() throws IOException {
 +    LOG_ENTER();
 +    String user = "hive";
 +    String pass = "hive-password";
 +    String group = "hive";
 +    String root = "/tmp/GatewayWebHCatFuncTest/testHiveViaWebHCat";
 +
 +    // Cleanup if previous run failed.
 +    deleteFile( user, pass, root, "true", 200, 404 );
 +
 +    // Post the data to HDFS
 +
 +    // Post the script to HDFS
 +    createFile(user, pass, null, root + "/script.hive", "777", "text/plain", "script.hive", 307, 201, 200);
 +
 +    // Submit the job
 +    submitHive(user, pass, group, root + "/script.hive", root + "/output", 200);
 +
 +    // Check job status (if possible)
 +    // Check output (if possible)
 +
 +    // Cleanup
 +    deleteFile( user, pass, root, "true", 200 );
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testOozieJobSubmission() throws Exception {
 +    LOG_ENTER();
 +    String root = "/tmp/GatewayBasicFuncTest/testOozieJobSubmission";
 +    String user = "hdfs";
 +    String pass = "hdfs-password";
 +    String group = "hdfs";
 +
 +    // Cleanup anything that might have been leftover because the test failed previously.
 +    deleteFile( user, pass, root, "true", HttpStatus.SC_OK );
 +
 +    /* Put the workflow definition into HDFS */
 +    createFile( user, pass, group, root+"/workflow.xml", "666", "application/octet-stream", "oozie-workflow.xml", 307, 201, 200 );
 +
 +    /* Put the mapreduce code into HDFS. (hadoop-examples.jar)
 +    curl -X PUT --data-binary @hadoop-examples.jar 'http://192.168.1.163:8888/org.apache.org.apache.hadoop.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/hadoop-examples.jar?user.name=hdfs&op=CREATE'
 +     */
 +    createFile( user, pass, group, root+"/lib/hadoop-examples.jar", "777", "application/octet-stream", findHadoopExamplesJar(), 307, 201, 200 );
 +
 +    /* Put the data file into HDFS (changes.txt)
 +    curl -X PUT --data-binary @changes.txt 'http://192.168.1.163:8888/org.apache.org.apache.hadoop.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/input/changes.txt?user.name=hdfs&op=CREATE'
 +     */
 +    createFile( user, pass, group, root+"/input/changes.txt", "666", "text/plain", "changes.txt", 307, 201, 200 );
 +
 +    VelocityEngine velocity = new VelocityEngine();
 +    velocity.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.NullLogSystem" );
 +    velocity.setProperty( RuntimeConstants.RESOURCE_LOADER, "classpath" );
 +    velocity.setProperty( "classpath.resource.loader.class", ClasspathResourceLoader.class.getName() );
 +    velocity.init();
 +
 +    VelocityContext context = new VelocityContext();
 +    context.put( "userName", user );
 +    context.put( "nameNode", "hdfs://sandbox:8020" );
 +    context.put( "jobTracker", "sandbox:50300" );
 +    //context.put( "appPath", "hdfs://sandbox:8020" + root );
 +    context.put( "appPath", root );
 +    context.put( "inputDir", root + "/input" );
 +    context.put( "outputDir", root + "/output" );
 +
 +    //URL url = TestUtils.getResourceUrl( GatewayBasicFuncTest.class, "oozie-jobs-submit-request.xml" );
 +    //String name = url.toExternalForm();
 +    String name = TestUtils.getResourceName( this.getClass(), "oozie-jobs-submit-request.xml" );
 +    Template template = velocity.getTemplate( name );
 +    StringWriter sw = new StringWriter();
 +    template.merge( context, sw );
 +    String request = sw.toString();
 +    //System.out.println( "REQUEST=" + request );
 +
 +    /* Submit the job via Oozie. */
 +    String id = oozieSubmitJob( user, pass, request, 201 );
 +    //System.out.println( "ID=" + id );
 +
 +    String success = "SUCCEEDED";
 +    String status = "UNKNOWN";
 +    long delay = 1000 * 1; // 1 second.
 +    long limit = 1000 * 60; // 60 seconds.
 +    long start = System.currentTimeMillis();
 +    while( System.currentTimeMillis() <= start+limit ) {
 +      status = oozieQueryJobStatus( user, pass, id, 200 );
 +      //System.out.println( "Status=" + status );
 +      if( success.equalsIgnoreCase( status ) ) {
 +        break;
 +      } else {
 +        //System.out.println( "Status=" + status );
 +        Thread.sleep( delay );
 +      }
 +    }
 +    //System.out.println( "Status is " + status + " after " + ((System.currentTimeMillis()-start)/1000) + " seconds." );
 +    MatcherAssert.assertThat( status, is( success ) );
 +
 +    if( CLEANUP_TEST ) {
 +      // Cleanup anything that might have been leftover because the test failed previously.
 +      deleteFile( user, pass, root, "true", HttpStatus.SC_OK );
 +    }
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testBasicHiveJDBCUseCase() throws IOException {
 +    LOG_ENTER();
 +    String root = "/tmp/GatewayHiveJDBCFuncTest/testBasicHiveUseCase";
 +    String username = "hive";
 +    String password = "hive-password";
 +    InetSocketAddress gatewayAddress = driver.gateway.getAddresses()[0];
 +
 +    // This use case emulates simple JDBC scenario which consists of following steps:
 +    // -open connection;
 +    // -configure Hive using 'execute' statements (this also includes execution of 'close operation' requests internally);
 +    // -execution of create table command;
 +    // -execution of select from table command;
 +    // Data insertion is omitted because it causes a lot of additional command during insertion/querying.
 +    // All binary data was intercepted during real scenario and stored into files as array of bytes.
 +
 +    // open session
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/open-session-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/open-session-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    Response response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/open-session-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/open-session-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/open-session-result.bin" ) ) );
 +
 +    driver.assertComplete();
 +
 +    // execute 'set hive.fetch.output.serde=...' (is called internally be JDBC driver)
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/execute-set-fetch-output-serde-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/execute-set-fetch-output-serde-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/execute-set-fetch-output-serde-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/execute-set-fetch-output-serde-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/execute-set-fetch-output-serde-result.bin" ) ) );
 +    driver.assertComplete();
 +
 +    // close operation for execute 'set hive.fetch.output.serde=...'
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/close-operation-1-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/close-operation-1-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/close-operation-1-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/close-operation-1-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/close-operation-1-result.bin" ) ) );
 +    driver.assertComplete();
 +
 +    // execute 'set hive.server2.http.path=...' (is called internally be JDBC driver)
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/execute-set-server2-http-path-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/execute-set-server2-http-path-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/execute-set-server2-http-path-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/execute-set-server2-http-path-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/execute-set-server2-http-path-result.bin" ) ) );
 +    driver.assertComplete();
 +
 +    // close operation for execute 'set hive.server2.http.path=...'
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/close-operation-2-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/close-operation-2-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/close-operation-2-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/close-operation-2-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/close-operation-2-result.bin" ) ) );
 +    driver.assertComplete();
 +
 +    // execute 'set hive.server2.servermode=...' (is called internally be JDBC driver)
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/execute-set-server2-servermode-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/execute-set-server2-servermode-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/execute-set-server2-servermode-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/execute-set-server2-servermode-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/execute-set-server2-servermode-result.bin" ) ) );
 +    driver.assertComplete();
 +
 +    // close operation for execute 'set hive.server2.servermode=...'
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/close-operation-3-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/close-operation-3-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/close-operation-3-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/close-operation-3-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/close-operation-3-result.bin" ) ) );
 +    driver.assertComplete();
 +
 +    // execute 'set hive.security.authorization.enabled=...'
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/execute-set-security-authorization-enabled-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/execute-set-security-authorization-enabled-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/execute-set-security-authorization-enabled-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/execute-set-security-authorization-enabled-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/execute-set-security-authorization-enabled-result.bin" ) ) );
 +    driver.assertComplete();
 +
 +    // close operation for execute 'set hive.security.authorization.enabled=...'
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/close-operation-4-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/close-operation-4-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/close-operation-4-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/close-operation-4-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/close-operation-4-result.bin" ) ) );
 +    driver.assertComplete();
 +
 +    // execute 'create table...'
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/execute-create-table-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/execute-create-table-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/execute-create-table-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/execute-create-table-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/execute-create-table-result.bin" ) ) );
 +    driver.assertComplete();
 +
 +    // close operation for execute 'create table...'
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/close-operation-5-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/close-operation-5-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/close-operation-5-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/close-operation-5-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/close-operation-5-result.bin" ) ) );
 +    driver.assertComplete();
 +
 +    // execute 'select * from...'
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/execute-select-from-table-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/execute-select-from-table-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/execute-select-from-table-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/execute-select-from-table-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/execute-select-from-table-result.bin" ) ) );
 +    driver.assertComplete();
 +
 +    // execute 'GetResultSetMetadata' (is called internally be JDBC driver)
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/get-result-set-metadata-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/get-result-set-metadata-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/get-result-set-metadata-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/get-result-set-metadata-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/get-result-set-metadata-result.bin" ) ) );
 +    driver.assertComplete();
 +
 +    // execute 'FetchResults' (is called internally be JDBC driver)
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/fetch-results-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/fetch-results-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/fetch-results-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/fetch-results-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/fetch-results-result.bin" ) ) );
 +    driver.assertComplete();
 +
 +    // close operation for execute 'select * from...'
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/close-operation-6-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/close-operation-6-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/close-operation-6-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/close-operation-6-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/close-operation-6-result.bin" ) ) );
 +    driver.assertComplete();
 +
 +    // close session
 +    driver.getMock( "HIVE" )
 +        .expect()
 +        .method( "POST" )
 +        .content( driver.getResourceBytes( "hive/close-session-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .respond()
 +        .characterEncoding( "UTF-8" )
 +        .status( HttpStatus.SC_OK )
 +        .content( driver.getResourceBytes( "hive/close-session-result.bin" ) )
 +        .contentType( "application/x-thrift" );
 +    response = given()
 +        .auth().preemptive().basic( username, password )
 +        .header("X-XSRF-Header", "jksdhfkhdsf")
 +        .content( driver.getResourceBytes( "hive/close-session-request.bin" ) )
 +        .contentType( "application/x-thrift" )
 +        .expect()
 +        .statusCode( HttpStatus.SC_OK )
 +        //.content( is( driver.getResourceBytes( "hive/close-session-result.bin" ) ) )
 +        .contentType( "application/x-thrift" )
 +        .when().post( driver.getUrl( "HIVE" ) );
 +    assertThat( response.body().asByteArray(), is( driver.getResourceBytes( "hive/close-session-result.bin" ) ) );
 +    driver.assertComplete();
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testHBaseGetTableList() throws IOException {
 +    LOG_ENTER();
 +    String username = "hbase";
 +    String password = "hbase-password";
 +    String resourceName = "hbase/table-list";
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "GET" )
 +    .pathInfo( "/" )
 +    .header( "Accept", ContentType.XML.toString() )
 +    .respond()
 +    .status( HttpStatus.SC_OK )
 +    .content( driver.getResourceBytes( resourceName + ".xml" ) )
 +    .contentType( ContentType.XML.toString() );
 +
 +    Response response = given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .header( "Accept", ContentType.XML.toString() )
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .contentType( ContentType.XML )
 +    .when().get( driver.getUrl( "WEBHBASE" ) );
 +
 +    MatcherAssert
 +        .assertThat(
 +            the( response.getBody().asString() ),
 +            isEquivalentTo( the( driver.getResourceString( resourceName + ".xml", UTF8 ) ) ) );
 +    driver.assertComplete();
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "GET" )
 +    .pathInfo( "/" )
 +    .header( "Accept", ContentType.JSON.toString() )
 +    .respond()
 +    .status( HttpStatus.SC_OK )
 +    .content( driver.getResourceBytes( resourceName + ".json" ) )
 +    .contentType( ContentType.JSON.toString() );
 +
 +    response = given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .header( "Accept", ContentType.JSON.toString() )
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .contentType( ContentType.JSON )
 +    .when().get( driver.getUrl( "WEBHBASE" ) );
 +
 +    MatcherAssert
 +    .assertThat( response.getBody().asString(), sameJSONAs( driver.getResourceString( resourceName + ".json", UTF8 ) ) );
 +    driver.assertComplete();
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "GET" )
 +    .pathInfo( "/" )
 +    .header( "Accept", "application/x-protobuf" )
 +    .respond()
 +    .status( HttpStatus.SC_OK )
 +    .content( driver.getResourceString( resourceName + ".protobuf", UTF8 ), UTF8 )
 +    .contentType( "application/x-protobuf" );
 +
 +    given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .header( "Accept", "application/x-protobuf" )
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .contentType( "application/x-protobuf" )
 +    .content( is( driver.getResourceString( resourceName + ".protobuf", UTF8 ) ) )
 +    .when().get( driver.getUrl( "WEBHBASE" ) );
 +    driver.assertComplete();
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testHBaseCreateTableAndVerifySchema() throws IOException {
 +    LOG_ENTER();
 +    String username = "hbase";
 +    String password = "hbase-password";
 +    String resourceName = "hbase/table-schema";
 +    String path = "/table/schema";
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "PUT" )
 +    .pathInfo( path )
 +    .respond()
 +    .status( HttpStatus.SC_CREATED )
 +    .content( driver.getResourceBytes( resourceName + ".xml" ) )
 +    .contentType( ContentType.XML.toString() )
 +    .header( "Location", driver.getRealUrl( "WEBHBASE" ) + path  );
 +
 +    given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .expect()
 +    .statusCode( HttpStatus.SC_CREATED )
 +    .contentType( ContentType.XML )
 +    .header( "Location", startsWith( driver.getUrl( "WEBHBASE" ) + path ) )
 +    .when().put(driver.getUrl("WEBHBASE") + path);
 +    driver.assertComplete();
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "PUT" )
 +    .pathInfo( path )
 +    .respond()
 +    .status(HttpStatus.SC_CREATED)
 +    .content(driver.getResourceBytes(resourceName + ".json"))
 +    .contentType(ContentType.JSON.toString())
 +    .header("Location", driver.getRealUrl("WEBHBASE") + path);
 +
 +    given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .expect()
 +    .statusCode( HttpStatus.SC_CREATED )
 +    .contentType( ContentType.JSON )
 +    .header( "Location", startsWith( driver.getUrl( "WEBHBASE" ) + path ) )
 +    .when().put( driver.getUrl( "WEBHBASE" ) + path );
 +    driver.assertComplete();
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "PUT" )
 +    .pathInfo( path )
 +    .respond()
 +    .status( HttpStatus.SC_CREATED )
 +    .content( driver.getResourceBytes( resourceName + ".protobuf" ) )
 +    .contentType( "application/x-protobuf" )
 +    .header("Location", driver.getRealUrl("WEBHBASE") + path);
 +
 +    given()
 +    .auth().preemptive().basic(username, password)
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .expect()
 +    .statusCode(HttpStatus.SC_CREATED)
 +    .contentType("application/x-protobuf")
 +    .header("Location", startsWith(driver.getUrl("WEBHBASE") + path))
 +    .when().put(driver.getUrl("WEBHBASE") + path);
 +    driver.assertComplete();
 +
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testHBaseGetTableSchema() throws IOException {
 +    LOG_ENTER();
 +    String username = "hbase";
 +    String password = "hbase-password";
 +    String resourceName = "hbase/table-metadata";
 +    String path = "/table/schema";
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "GET" )
 +    .pathInfo( path )
 +    .header("Accept", ContentType.XML.toString())
 +    .respond()
 +    .status(HttpStatus.SC_OK)
 +    .content(driver.getResourceBytes(resourceName + ".xml"))
 +    .contentType(ContentType.XML.toString());
 +
 +    Response response = given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .header( "Accept", ContentType.XML.toString() )
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .contentType( ContentType.XML )
 +    .when().get( driver.getUrl( "WEBHBASE" ) + path );
 +
 +    MatcherAssert
 +        .assertThat(
 +            the(response.getBody().asString()),
 +            isEquivalentTo(the(driver.getResourceString(resourceName + ".xml", UTF8))));
 +    driver.assertComplete();
 +
 +    driver.getMock("WEBHBASE")
 +    .expect()
 +    .method("GET")
 +    .pathInfo(path)
 +    .header("Accept", ContentType.JSON.toString())
 +    .respond()
 +    .status(HttpStatus.SC_OK)
 +    .content(driver.getResourceBytes(resourceName + ".json"))
 +    .contentType(ContentType.JSON.toString());
 +
 +    response = given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .header( "Accept", ContentType.JSON.toString() )
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .contentType( ContentType.JSON )
 +    .when().get( driver.getUrl( "WEBHBASE" ) + path );
 +
 +    MatcherAssert
 +    .assertThat(response.getBody().asString(), sameJSONAs(driver.getResourceString(resourceName + ".json", UTF8)));
 +    driver.assertComplete();
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "GET" )
 +    .pathInfo( path )
 +    .header( "Accept", "application/x-protobuf" )
 +    .respond()
 +    .status( HttpStatus.SC_OK )
 +    .content( driver.getResourceBytes( resourceName + ".protobuf" ) )
 +    .contentType("application/x-protobuf");
 +
 +    response = given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .header( "Accept", "application/x-protobuf" )
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    //.content( is( driver.getResourceBytes( resourceName + ".protobuf" ) ) )
 +    .contentType( "application/x-protobuf" )
 +    .when().get( driver.getUrl( "WEBHBASE" ) + path );
 +    // RestAssured seems to be screwing up the binary comparison so do it explicitly.
 +    assertThat( driver.getResourceBytes( resourceName + ".protobuf" ), is( response.body().asByteArray() ) );
 +    driver.assertComplete();
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testHBaseInsertDataIntoTable() throws IOException {
 +    LOG_ENTER();
 +    String username = "hbase";
 +    String password = "hbase-password";
 +
 +    String resourceName = "hbase/table-data";
 +    String singleRowPath = "/table/testrow";
 +    String multipleRowPath = "/table/false-row-key";
 +
 +    //PUT request
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "PUT" )
 +    .pathInfo( multipleRowPath )
 +    //.header( "Content-Type", ContentType.XML.toString() )
 +    .content( driver.getResourceBytes( resourceName + ".xml" ) )
 +    .contentType( ContentType.XML.toString() )
 +    .respond()
 +    .status(HttpStatus.SC_OK);
 +
 +    given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    //.header( "Content-Type", ContentType.XML.toString() )
 +    .content( driver.getResourceBytes( resourceName + ".xml" ) )
 +    .contentType( ContentType.XML.toString() )
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .when().put(driver.getUrl("WEBHBASE") + multipleRowPath);
 +    driver.assertComplete();
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "PUT" )
 +    .pathInfo( singleRowPath )
 +    //.header( "Content-Type", ContentType.JSON.toString() )
 +    .contentType( ContentType.JSON.toString() )
 +    .respond()
 +    .status( HttpStatus.SC_OK );
 +
 +    given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    //.header( "Content-Type", ContentType.JSON.toString() )
 +    .content( driver.getResourceBytes( resourceName + ".json" ) )
 +    .contentType( ContentType.JSON.toString() )
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .when().put(driver.getUrl("WEBHBASE") + singleRowPath);
 +    driver.assertComplete();
 +
 +    driver.getMock("WEBHBASE")
 +    .expect()
 +    .method("PUT")
 +    .pathInfo(multipleRowPath)
 +    //.header( "Content-Type", "application/x-protobuf" )
 +    .contentType("application/x-protobuf")
 +    .content(driver.getResourceBytes(resourceName + ".protobuf"))
 +    .respond()
 +    .status(HttpStatus.SC_OK);
 +
 +    given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    //.header( "Content-Type", "application/x-protobuf" )
 +    .content( driver.getResourceBytes( resourceName + ".protobuf" ) )
 +    .contentType( "application/x-protobuf" )
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .when().put( driver.getUrl( "WEBHBASE" ) + multipleRowPath );
 +    driver.assertComplete();
 +
 +    //POST request
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "POST" )
 +    .pathInfo( multipleRowPath )
 +    //.header( "Content-Type", ContentType.XML.toString() )
 +    .content( driver.getResourceBytes( resourceName + ".xml" ) )
 +    .contentType( ContentType.XML.toString() )
 +    .respond()
 +    .status( HttpStatus.SC_OK );
 +
 +    given()
 +      .auth().preemptive().basic( username, password )
 +      .header("X-XSRF-Header", "jksdhfkhdsf")
 +      //.header( "Content-Type", ContentType.XML.toString() )
 +      .content( driver.getResourceBytes( resourceName + ".xml" ) )
 +      .contentType( ContentType.XML.toString() )
 +      .expect()
 +      .statusCode( HttpStatus.SC_OK )
 +      .when().post( driver.getUrl( "WEBHBASE" ) + multipleRowPath );
 +    driver.assertComplete();
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "POST" )
 +    .pathInfo( singleRowPath )
 +    //.header( "Content-Type", ContentType.JSON.toString() )
 +    .contentType( ContentType.JSON.toString() )
 +    .respond()
 +    .status( HttpStatus.SC_OK );
 +
 +    given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    //.header( "Content-Type", ContentType.JSON.toString() )
 +    .content( driver.getResourceBytes( resourceName + ".json" ) )
 +    .contentType( ContentType.JSON.toString() )
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .when().post( driver.getUrl( "WEBHBASE" ) + singleRowPath );
 +    driver.assertComplete();
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "POST" )
 +    .pathInfo( multipleRowPath )
 +    //.header( "Content-Type", "application/x-protobuf" )
 +    .content( driver.getResourceBytes( resourceName + ".protobuf" ) )
 +    .contentType( "application/x-protobuf" )
 +    .respond()
 +    .status( HttpStatus.SC_OK );
 +
 +    given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    //.header( "Content-Type", "application/x-protobuf" )
 +    .content( driver.getResourceBytes( resourceName + ".protobuf" ) )
 +    .contentType( "application/x-protobuf" )
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .when().post(driver.getUrl("WEBHBASE") + multipleRowPath);
 +    driver.assertComplete();
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testHBaseDeleteDataFromTable() {
 +    LOG_ENTER();
 +    String username = "hbase";
 +    String password = "hbase-password";
 +
 +    String tableId = "table";
 +    String rowId = "row";
 +    String familyId = "family";
 +    String columnId = "column";
 +
 +    driver.getMock("WEBHBASE")
 +    .expect()
 +    .from("testHBaseDeleteDataFromTable-1")
 +    .method("DELETE")
 +    .pathInfo("/" + tableId + "/" + rowId)
 +    .respond()
 +    .status(HttpStatus.SC_OK);
 +
 +    given()
 +    .auth().preemptive().basic(username, password)
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .when().delete(driver.getUrl("WEBHBASE") + "/" + tableId + "/" + rowId);
 +    driver.assertComplete();
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .from("testHBaseDeleteDataFromTable-2")
 +    .method("DELETE")
 +    .pathInfo("/" + tableId + "/" + rowId + "/" + familyId)
 +    .respond()
 +    .status( HttpStatus.SC_OK );
 +
 +    given()
 +    .auth().preemptive().basic(username, password)
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .when().delete(driver.getUrl("WEBHBASE") + "/" + tableId + "/" + rowId + "/" + familyId);
 +    driver.assertComplete();
 +
 +    driver.getMock("WEBHBASE")
 +    .expect()
 +    .from("testHBaseDeleteDataFromTable-3")
 +    .method("DELETE")
 +    .pathInfo("/" + tableId + "/" + rowId + "/" + familyId + ":" + columnId)
 +    .respond()
 +    .status(HttpStatus.SC_OK);
 +
 +    given()
 +    .auth().preemptive().basic(username, password)
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .when().delete(driver.getUrl("WEBHBASE") + "/" + tableId + "/" + rowId + "/" + familyId + ":" + columnId);
 +    driver.assertComplete();
 +
 +    LOG_EXIT();
 +  }
 +
 +  @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
 +  public void testHBaseQueryTableData() throws IOException {
 +    LOG_ENTER();
 +    String username = "hbase";
 +    String password = "hbase-password";
 +
 +    String resourceName = "hbase/table-data";
 +
 +    String allRowsPath = "/table/*";
 +    String rowsStartsWithPath = "/table/row*";
 +    String rowsWithKeyPath = "/table/row";
 +    String rowsWithKeyAndColumnPath = "/table/row/family:col";
 +
 +    driver.getMock("WEBHBASE")
 +    .expect()
 +    .method("GET")
 +    .pathInfo(allRowsPath)
 +    .header("Accept", ContentType.XML.toString())
 +    .respond()
 +    .status(HttpStatus.SC_OK)
 +    .content(driver.getResourceBytes(resourceName + ".xml"))
 +    .contentType(ContentType.XML.toString());
 +
 +    Response response = given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .header( "Accept", ContentType.XML.toString() )
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .contentType( ContentType.XML )
 +    .when().get( driver.getUrl( "WEBHBASE" ) + allRowsPath );
 +
 +    MatcherAssert
 +    .assertThat(
 +        the(response.getBody().asString()),
 +        isEquivalentTo(the(driver.getResourceString(resourceName + ".xml", UTF8))));
 +    driver.assertComplete();
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "GET" )
 +    .pathInfo( rowsStartsWithPath )
 +    .header( "Accept", ContentType.XML.toString() )
 +    .respond()
 +    .status( HttpStatus.SC_OK )
 +    .content( driver.getResourceBytes( resourceName + ".xml" ) )
 +    .contentType(ContentType.XML.toString());
 +
 +    response = given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .header( "Accept", ContentType.XML.toString() )
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .contentType( ContentType.XML )
 +    .when().get( driver.getUrl( "WEBHBASE" ) + rowsStartsWithPath );
 +
 +    MatcherAssert
 +    .assertThat(
 +        the(response.getBody().asString()),
 +        isEquivalentTo(the(driver.getResourceString(resourceName + ".xml", UTF8))));
 +    driver.assertComplete();
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "GET" )
 +    .pathInfo( rowsWithKeyPath )
 +    .header( "Accept", ContentType.JSON.toString() )
 +    .respond()
 +    .status( HttpStatus.SC_OK )
 +    .content( driver.getResourceBytes( resourceName + ".json" ) )
 +    .contentType( ContentType.JSON.toString() );
 +
 +    response = given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .header( "Accept", ContentType.JSON.toString() )
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .contentType( ContentType.JSON )
 +    .when().get( driver.getUrl( "WEBHBASE" ) + rowsWithKeyPath );
 +
 +    MatcherAssert
 +    .assertThat( response.getBody().asString(), sameJSONAs( driver.getResourceString( resourceName + ".json", UTF8 ) ) );
 +    driver.assertComplete();
 +
 +    driver.getMock( "WEBHBASE" )
 +    .expect()
 +    .method( "GET" )
 +    .pathInfo( rowsWithKeyAndColumnPath )
 +    .header( "Accept", ContentType.JSON.toString() )
 +    .respond()
 +    .status( HttpStatus.SC_OK )
 +    .content( driver.getResourceBytes( resourceName + ".json" ) )
 +    .contentType( ContentType.JSON.toString() );
 +
 +    response = given()
 +    .auth().preemptive().basic( username, password )
 +    .header("X-XSRF-Header", "jksdhfkhdsf")
 +    .header( "Accept", ContentType.JSON.toString() )
 +    .expect()
 +    .statusCode( HttpStatus.SC_OK )
 +    .contentType( ContentType.JSON )
 +    .when().get( driver.getUrl( "WEBHBASE" ) + rowsWithKeyAndColumnPath );
 +
 +    MatcherAssert
 +    .assertThat( response.getBody().asS

<TRUNCATED>

[32/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeProcessor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeProcessor.java
deleted file mode 100644
index c42233a..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeProcessor.java
+++ /dev/null
@@ -1,86 +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.hadoop.gateway.securequery;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-import org.apache.hadoop.gateway.util.urltemplate.Builder;
-import org.apache.hadoop.gateway.util.urltemplate.Query;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.io.UnsupportedEncodingException;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-public class SecureQueryDecodeProcessor implements UrlRewriteStepProcessor<SecureQueryDecodeDescriptor> {
-
-  private static final String ENCODED_PARAMETER_NAME = "_";
-
-  @Override
-  public String getType() {
-    return SecureQueryDecodeDescriptor.STEP_NAME;
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, SecureQueryDecodeDescriptor descriptor ) throws Exception {
-  }
-
-  @Override
-  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
-    //TODO: Need some way to get a reference to the keystore service and the encryption key in particular.
-    Template currUrl = context.getCurrentUrl();
-    Builder newUrl = new Builder( currUrl );
-    Map<String,Query> map = newUrl.getQuery();
-    Query query = map.remove( ENCODED_PARAMETER_NAME );
-    if( query != null ) {
-      String value = query.getFirstValue().getPattern();
-      value = decode( value );
-      StringTokenizer outerParser = new StringTokenizer( value, "&" );
-      while( outerParser.hasMoreTokens() ) {
-        String pair = outerParser.nextToken();
-        StringTokenizer innerParser = new StringTokenizer( pair, "=" );
-        if( innerParser.hasMoreTokens() ) {
-          String paramName = innerParser.nextToken();
-          if( innerParser.hasMoreTokens() ) {
-            String paramValue = innerParser.nextToken();
-            // Need to take out any existing query param.
-            // If we don't then someone could override something in the encoded param.
-            map.remove( paramName );
-            newUrl.addQuery( paramName, "", paramValue, true );
-          } else {
-            newUrl.addQuery( paramName, "", null, true );
-          }
-        }
-      }
-      context.setCurrentUrl( newUrl.build() );
-    }
-    return UrlRewriteStepStatus.SUCCESS;
-  }
-
-  @Override
-  public void destroy() {
-  }
-
-  private static String decode( String string ) throws UnsupportedEncodingException {
-    return new String( Base64.decodeBase64( string ), "UTF-8" );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecryptDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecryptDescriptor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecryptDescriptor.java
deleted file mode 100644
index 8db2070..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecryptDescriptor.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.hadoop.gateway.securequery;
-
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
-
-public class SecureQueryDecryptDescriptor
-    extends UrlRewriteActionDescriptorBase
-    implements UrlRewriteActionDescriptor {
-
-  static final String STEP_NAME = "decrypt-query";
-
-  public SecureQueryDecryptDescriptor() {
-    super( STEP_NAME );
-  }
-
-  @Override
-  public String getParam() {
-    return null;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecryptProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecryptProcessor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecryptProcessor.java
deleted file mode 100644
index 0687cb4..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecryptProcessor.java
+++ /dev/null
@@ -1,119 +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.hadoop.gateway.securequery;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.security.CryptoService;
-import org.apache.hadoop.gateway.services.security.EncryptionResult;
-import org.apache.hadoop.gateway.util.urltemplate.Builder;
-import org.apache.hadoop.gateway.util.urltemplate.Query;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.io.UnsupportedEncodingException;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-public class SecureQueryDecryptProcessor implements UrlRewriteStepProcessor<SecureQueryDecryptDescriptor> {
-
-  private static final String ENCRYPTED_PARAMETER_NAME = "_";
-
-  private String clusterName;
-  private CryptoService cryptoService;
-
-  @Override
-  public String getType() {
-    return SecureQueryDecryptDescriptor.STEP_NAME;
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, SecureQueryDecryptDescriptor descriptor ) throws Exception {
-    clusterName = environment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE );
-    GatewayServices services = environment.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
-    cryptoService = (CryptoService) services.getService(GatewayServices.CRYPTO_SERVICE);
-  }
-
-  @Override
-  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
-    //TODO: Need some way to get a reference to the keystore service and the encryption key in particular.
-    Template currUrl = context.getCurrentUrl();
-    Builder newUrl = new Builder( currUrl );
-    Map<String,Query> map = newUrl.getQuery();
-    Query query = map.remove( ENCRYPTED_PARAMETER_NAME );
-    UrlRewriteStepStatus status = UrlRewriteStepStatus.FAILURE;
-    status = getUrlRewriteStepStatus(context, newUrl, map, query, status);
-    return status;
-  }
-
-  private UrlRewriteStepStatus getUrlRewriteStepStatus(UrlRewriteContext context, Builder newUrl, Map<String, Query> map, Query query, UrlRewriteStepStatus status) throws UnsupportedEncodingException {
-    if( query != null ) {
-      String value = query.getFirstValue().getPattern();
-      value = decode( value );
-      status = getUrlRewriteStepStatus(context, newUrl, map, status, value);
-    }
-    return status;
-  }
-
-  private UrlRewriteStepStatus getUrlRewriteStepStatus(UrlRewriteContext context, Builder newUrl, Map<String, Query> map, UrlRewriteStepStatus status, String value) {
-    if( value != null ) {
-       StringTokenizer outerParser = new StringTokenizer( value, "&" );
-       while( outerParser.hasMoreTokens() ) {
-         String pair = outerParser.nextToken();
-         StringTokenizer innerParser = new StringTokenizer( pair, "=" );
-         if( innerParser.hasMoreTokens() ) {
-           String paramName = innerParser.nextToken();
-           if( innerParser.hasMoreTokens() ) {
-             String paramValue = innerParser.nextToken();
-             // Need to remove from the clear parameters any param name in the encoded params.
-             // If we don't then someone could override something in the encoded param.
-             map.remove( paramName );
-             newUrl.addQuery( paramName, "", paramValue, true );
-           } else {
-             newUrl.addQuery( paramName, "", null, true );
-           }
-         }
-       }
-       context.setCurrentUrl( newUrl.build() );
-       context.getParameters().resolve( "gateway.name" );
-       status = UrlRewriteStepStatus.SUCCESS;
-    }
-    return status;
-  }
-
-  @Override
-  public void destroy() {
-  }
-
-  String decode( String string ) throws UnsupportedEncodingException {
-    byte[] bytes = Base64.decodeBase64( string );
-    EncryptionResult result = EncryptionResult.fromByteArray(bytes);
-    byte[] clear = cryptoService.decryptForCluster(clusterName, 
-        "encryptQueryString", 
-        result.cipher, 
-        result.iv, 
-        result.salt);
-    if (clear != null) {
-      return new String(clear);
-    }
-    return null;
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDeploymentContributor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDeploymentContributor.java
deleted file mode 100644
index 33a0c85..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDeploymentContributor.java
+++ /dev/null
@@ -1,113 +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.hadoop.gateway.securequery;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.services.security.AliasService;
-import org.apache.hadoop.gateway.services.security.AliasServiceException;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-import java.util.List;
-
-public class SecureQueryDeploymentContributor
-    extends ProviderDeploymentContributorBase
-    implements ProviderDeploymentContributor {
-
-  private static SecureQueryMessages log = MessagesFactory.get( SecureQueryMessages.class );
-  public static final String PROVIDER_ROLE_NAME = "secure-query";
-  public static final String PROVIDER_IMPL_NAME = "default";
-  private AliasService as;
-
-  @Override
-  public String getRole() {
-    return PROVIDER_ROLE_NAME;
-  }
-
-  @Override
-  public String getName() {
-    return PROVIDER_IMPL_NAME;
-  }
-  
-  public void setAliasService(AliasService as) {
-    this.as = as;
-  }
-
-  @Override
-  public void initializeContribution(DeploymentContext context) {
-    super.initializeContribution(context);
-
-    String clusterName = context.getTopology().getName();
-    
-    // we don't want to overwrite an existing alias from a previous topology deployment
-    // so we can't just blindly generateAlias here.
-    // this version of getPassword will generate a value for it only if missing
-    try {
-      this.as.getPasswordFromAliasForCluster(clusterName, "encryptQueryString", true);
-    } catch (AliasServiceException e) {
-      log.unableCreatePasswordForEncryption(e);
-    }
-  }
-
-  @Override
-  public void contributeProvider( DeploymentContext context, Provider provider ) {
-    if( provider.isEnabled() ) {
-//      UrlRewriteRulesDescriptor rules = context.getDescriptor( REWRITE_ROLE_NAME );
-//      if( rules != null ) {
-//        HostmapFunctionDescriptor func = rules.addFunction( HostmapFunctionDescriptor.FUNCTION_NAME );
-//        if( func != null ) {
-//          Asset asset = createAsset( provider );
-//          context.getWebArchive().addAsWebInfResource(
-//              asset, HostmapFunctionProcessor.DESCRIPTOR_DEFAULT_FILE_NAME );
-//          func.config( HostmapFunctionProcessor.DESCRIPTOR_DEFAULT_LOCATION );
-//        }
-//      }
-    }
-  }
-
-//  private Asset createAsset( Provider provider ) {
-//    StringWriter buffer = new StringWriter();
-//    PrintWriter writer = new PrintWriter( buffer );
-//    for( Map.Entry<String,String> entry : provider.getParams().entrySet() ) {
-//      String externalHosts = entry.getKey();
-//      String internalHosts = entry.getValue();
-//      writer.print( externalHosts );
-//      writer.print( "=" );
-//      writer.println( internalHosts ) ;
-//    }
-//    writer.close();
-//    String string = buffer.toString();
-//    Asset asset = new StringAsset( string );
-//    return asset;
-//  }
-
-  @Override
-  public void contributeFilter(
-      DeploymentContext context,
-      Provider provider,
-      Service service,
-      ResourceDescriptor resource,
-      List<FilterParamDescriptor> params ) {
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeDescriptor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeDescriptor.java
deleted file mode 100644
index a29be4e..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeDescriptor.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.hadoop.gateway.securequery;
-
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
-
-public class SecureQueryEncodeDescriptor
-    extends UrlRewriteActionDescriptorBase
-    implements UrlRewriteActionDescriptor {
-
-  static final String STEP_NAME = "encode-query";
-
-  public SecureQueryEncodeDescriptor() {
-    super( STEP_NAME );
-  }
-
-  @Override
-  public String getParam() {
-    return null;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeProcessor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeProcessor.java
deleted file mode 100644
index 0b32c05..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncodeProcessor.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.hadoop.gateway.securequery;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-public class SecureQueryEncodeProcessor
-    implements UrlRewriteStepProcessor<SecureQueryEncodeDescriptor> {
-
-  private static final String ENCODED_PARAMETER_NAME = "_";
-
-  @Override
-  public String getType() {
-    return SecureQueryEncodeDescriptor.STEP_NAME;
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, SecureQueryEncodeDescriptor descriptor ) throws Exception {
-  }
-
-  @Override
-  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
-    //TODO: Need some way to get a reference to the keystore service and the encryption key in particular.
-    Template url = context.getCurrentUrl();
-    String str = url.toString();
-    String path = str;
-    String query = null;
-    int index = str.indexOf( '?' );
-    if( index >= 0 ) {
-      path = str.substring( 0, index );
-      if( index < str.length() ) {
-        query = str.substring( index + 1 );
-      }
-    }
-    if( query != null ) {
-      query = Base64.encodeBase64String( query.getBytes( "UTF-8" ) );
-      query = removeTrailingEquals( query );
-      url = Parser.parseLiteral( path + "?" + ENCODED_PARAMETER_NAME +"=" + query );
-      context.setCurrentUrl( url );
-    }
-    return UrlRewriteStepStatus.SUCCESS;
-  }
-
-  @Override
-  public void destroy() {
-  }
-
-  private static String removeTrailingEquals( String s ) {
-    int i = s.length()-1;
-    while( i > 0 && s.charAt( i ) == '=' ) {
-      i--;
-    }
-    return s.substring( 0, i+1 );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncryptDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncryptDescriptor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncryptDescriptor.java
deleted file mode 100644
index 9f3d7b9..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncryptDescriptor.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.hadoop.gateway.securequery;
-
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
-
-public class SecureQueryEncryptDescriptor
-    extends UrlRewriteActionDescriptorBase
-    implements UrlRewriteActionDescriptor {
-
-  static final String STEP_NAME = "encrypt-query";
-
-  public SecureQueryEncryptDescriptor() {
-    super( STEP_NAME );
-  }
-
-  @Override
-  public String getParam() {
-    return null;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncryptProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncryptProcessor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncryptProcessor.java
deleted file mode 100644
index fe587ba..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryEncryptProcessor.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.hadoop.gateway.securequery;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.security.CryptoService;
-import org.apache.hadoop.gateway.services.security.EncryptionResult;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.io.UnsupportedEncodingException;
-
-public class SecureQueryEncryptProcessor
-    implements UrlRewriteStepProcessor<SecureQueryEncryptDescriptor> {
-
-  private static final String ENCRYPTED_PARAMETER_NAME = "_";
-
-  private String clusterName;
-  private CryptoService cryptoService = null;
-
-  @Override
-  public String getType() {
-    return SecureQueryEncryptDescriptor.STEP_NAME;
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, SecureQueryEncryptDescriptor descriptor ) throws Exception {
-    clusterName = environment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE );
-    GatewayServices services = environment.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
-    cryptoService = (CryptoService) services.getService(GatewayServices.CRYPTO_SERVICE);
-  }
-
-  @Override
-  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
-    //TODO: Need some way to get a reference to the keystore service and the encryption key in particular.
-    Template url = context.getCurrentUrl();
-    String str = url.toString();
-    String path = str;
-    String query = null;
-    int index = str.indexOf( '?' );
-    if( index >= 0 ) {
-      path = str.substring( 0, index );
-      if( index < str.length() ) {
-        query = str.substring( index + 1 );
-      }
-    }
-    if( query != null ) {
-      query = encode( query );
-      url = Parser.parseLiteral( path + "?" + ENCRYPTED_PARAMETER_NAME +"=" + query );
-      context.setCurrentUrl( url );
-    }
-    return UrlRewriteStepStatus.SUCCESS;
-  }
-
-  @Override
-  public void destroy() {
-  }
-
-  private String encode( String string ) throws UnsupportedEncodingException {
-    EncryptionResult result = cryptoService.encryptForCluster(clusterName, "encryptQueryString", string.getBytes("UTF-8"));
-    string = Base64.encodeBase64URLSafeString(result.toByteAray());
-    return string;
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryMessages.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryMessages.java
deleted file mode 100644
index 27cadaa..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryMessages.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.securequery;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-import org.apache.hadoop.gateway.i18n.messages.StackTrace;
-
-@Messages(logger="org.apache.hadoop.gateway.securequery")
-public interface SecureQueryMessages {
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to create or verify the presence of a password for query string encryption: {0}" )
-  void unableCreatePasswordForEncryption(@StackTrace( level = MessageLevel.DEBUG ) Exception e);
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecodeDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecodeDescriptor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecodeDescriptor.java
new file mode 100644
index 0000000..069dc65
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecodeDescriptor.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.knox.gateway.securequery;
+
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
+
+public class SecureQueryDecodeDescriptor
+    extends UrlRewriteActionDescriptorBase
+    implements UrlRewriteActionDescriptor {
+
+  static final String STEP_NAME = "decode-query";
+
+  public SecureQueryDecodeDescriptor() {
+    super( STEP_NAME );
+  }
+
+  @Override
+  public String getParam() {
+    return null;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecodeProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecodeProcessor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecodeProcessor.java
new file mode 100644
index 0000000..c007021
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecodeProcessor.java
@@ -0,0 +1,87 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.securequery;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+import org.apache.knox.gateway.util.urltemplate.Builder;
+import org.apache.knox.gateway.util.urltemplate.Query;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Map;
+import java.util.StringTokenizer;
+
+public class SecureQueryDecodeProcessor implements
+    UrlRewriteStepProcessor<SecureQueryDecodeDescriptor> {
+
+  private static final String ENCODED_PARAMETER_NAME = "_";
+
+  @Override
+  public String getType() {
+    return SecureQueryDecodeDescriptor.STEP_NAME;
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, SecureQueryDecodeDescriptor descriptor ) throws Exception {
+  }
+
+  @Override
+  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
+    //TODO: Need some way to get a reference to the keystore service and the encryption key in particular.
+    Template currUrl = context.getCurrentUrl();
+    Builder newUrl = new Builder( currUrl );
+    Map<String,Query> map = newUrl.getQuery();
+    Query query = map.remove( ENCODED_PARAMETER_NAME );
+    if( query != null ) {
+      String value = query.getFirstValue().getPattern();
+      value = decode( value );
+      StringTokenizer outerParser = new StringTokenizer( value, "&" );
+      while( outerParser.hasMoreTokens() ) {
+        String pair = outerParser.nextToken();
+        StringTokenizer innerParser = new StringTokenizer( pair, "=" );
+        if( innerParser.hasMoreTokens() ) {
+          String paramName = innerParser.nextToken();
+          if( innerParser.hasMoreTokens() ) {
+            String paramValue = innerParser.nextToken();
+            // Need to take out any existing query param.
+            // If we don't then someone could override something in the encoded param.
+            map.remove( paramName );
+            newUrl.addQuery( paramName, "", paramValue, true );
+          } else {
+            newUrl.addQuery( paramName, "", null, true );
+          }
+        }
+      }
+      context.setCurrentUrl( newUrl.build() );
+    }
+    return UrlRewriteStepStatus.SUCCESS;
+  }
+
+  @Override
+  public void destroy() {
+  }
+
+  private static String decode( String string ) throws UnsupportedEncodingException {
+    return new String( Base64.decodeBase64( string ), "UTF-8" );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecryptDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecryptDescriptor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecryptDescriptor.java
new file mode 100644
index 0000000..f463fec
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecryptDescriptor.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.knox.gateway.securequery;
+
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
+
+public class SecureQueryDecryptDescriptor
+    extends UrlRewriteActionDescriptorBase
+    implements UrlRewriteActionDescriptor {
+
+  static final String STEP_NAME = "decrypt-query";
+
+  public SecureQueryDecryptDescriptor() {
+    super( STEP_NAME );
+  }
+
+  @Override
+  public String getParam() {
+    return null;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecryptProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecryptProcessor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecryptProcessor.java
new file mode 100644
index 0000000..3cccc4d
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDecryptProcessor.java
@@ -0,0 +1,120 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.securequery;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.CryptoService;
+import org.apache.knox.gateway.services.security.EncryptionResult;
+import org.apache.knox.gateway.util.urltemplate.Builder;
+import org.apache.knox.gateway.util.urltemplate.Query;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Map;
+import java.util.StringTokenizer;
+
+public class SecureQueryDecryptProcessor implements
+    UrlRewriteStepProcessor<SecureQueryDecryptDescriptor> {
+
+  private static final String ENCRYPTED_PARAMETER_NAME = "_";
+
+  private String clusterName;
+  private CryptoService cryptoService;
+
+  @Override
+  public String getType() {
+    return SecureQueryDecryptDescriptor.STEP_NAME;
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, SecureQueryDecryptDescriptor descriptor ) throws Exception {
+    clusterName = environment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE );
+    GatewayServices services = environment.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
+    cryptoService = (CryptoService) services.getService(GatewayServices.CRYPTO_SERVICE);
+  }
+
+  @Override
+  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
+    //TODO: Need some way to get a reference to the keystore service and the encryption key in particular.
+    Template currUrl = context.getCurrentUrl();
+    Builder newUrl = new Builder( currUrl );
+    Map<String,Query> map = newUrl.getQuery();
+    Query query = map.remove( ENCRYPTED_PARAMETER_NAME );
+    UrlRewriteStepStatus status = UrlRewriteStepStatus.FAILURE;
+    status = getUrlRewriteStepStatus(context, newUrl, map, query, status);
+    return status;
+  }
+
+  private UrlRewriteStepStatus getUrlRewriteStepStatus(UrlRewriteContext context, Builder newUrl, Map<String, Query> map, Query query, UrlRewriteStepStatus status) throws UnsupportedEncodingException {
+    if( query != null ) {
+      String value = query.getFirstValue().getPattern();
+      value = decode( value );
+      status = getUrlRewriteStepStatus(context, newUrl, map, status, value);
+    }
+    return status;
+  }
+
+  private UrlRewriteStepStatus getUrlRewriteStepStatus(UrlRewriteContext context, Builder newUrl, Map<String, Query> map, UrlRewriteStepStatus status, String value) {
+    if( value != null ) {
+       StringTokenizer outerParser = new StringTokenizer( value, "&" );
+       while( outerParser.hasMoreTokens() ) {
+         String pair = outerParser.nextToken();
+         StringTokenizer innerParser = new StringTokenizer( pair, "=" );
+         if( innerParser.hasMoreTokens() ) {
+           String paramName = innerParser.nextToken();
+           if( innerParser.hasMoreTokens() ) {
+             String paramValue = innerParser.nextToken();
+             // Need to remove from the clear parameters any param name in the encoded params.
+             // If we don't then someone could override something in the encoded param.
+             map.remove( paramName );
+             newUrl.addQuery( paramName, "", paramValue, true );
+           } else {
+             newUrl.addQuery( paramName, "", null, true );
+           }
+         }
+       }
+       context.setCurrentUrl( newUrl.build() );
+       context.getParameters().resolve( "gateway.name" );
+       status = UrlRewriteStepStatus.SUCCESS;
+    }
+    return status;
+  }
+
+  @Override
+  public void destroy() {
+  }
+
+  String decode( String string ) throws UnsupportedEncodingException {
+    byte[] bytes = Base64.decodeBase64( string );
+    EncryptionResult result = EncryptionResult.fromByteArray(bytes);
+    byte[] clear = cryptoService.decryptForCluster(clusterName, 
+        "encryptQueryString", 
+        result.cipher, 
+        result.iv, 
+        result.salt);
+    if (clear != null) {
+      return new String(clear);
+    }
+    return null;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDeploymentContributor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDeploymentContributor.java
new file mode 100644
index 0000000..dead39f
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryDeploymentContributor.java
@@ -0,0 +1,113 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.securequery;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributor;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.services.security.AliasService;
+import org.apache.knox.gateway.services.security.AliasServiceException;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+import java.util.List;
+
+public class SecureQueryDeploymentContributor
+    extends ProviderDeploymentContributorBase
+    implements ProviderDeploymentContributor {
+
+  private static SecureQueryMessages log = MessagesFactory.get( SecureQueryMessages.class );
+  public static final String PROVIDER_ROLE_NAME = "secure-query";
+  public static final String PROVIDER_IMPL_NAME = "default";
+  private AliasService as;
+
+  @Override
+  public String getRole() {
+    return PROVIDER_ROLE_NAME;
+  }
+
+  @Override
+  public String getName() {
+    return PROVIDER_IMPL_NAME;
+  }
+  
+  public void setAliasService(AliasService as) {
+    this.as = as;
+  }
+
+  @Override
+  public void initializeContribution(DeploymentContext context) {
+    super.initializeContribution(context);
+
+    String clusterName = context.getTopology().getName();
+    
+    // we don't want to overwrite an existing alias from a previous topology deployment
+    // so we can't just blindly generateAlias here.
+    // this version of getPassword will generate a value for it only if missing
+    try {
+      this.as.getPasswordFromAliasForCluster(clusterName, "encryptQueryString", true);
+    } catch (AliasServiceException e) {
+      log.unableCreatePasswordForEncryption(e);
+    }
+  }
+
+  @Override
+  public void contributeProvider( DeploymentContext context, Provider provider ) {
+    if( provider.isEnabled() ) {
+//      UrlRewriteRulesDescriptor rules = context.getDescriptor( REWRITE_ROLE_NAME );
+//      if( rules != null ) {
+//        HostmapFunctionDescriptor func = rules.addFunction( HostmapFunctionDescriptor.FUNCTION_NAME );
+//        if( func != null ) {
+//          Asset asset = createAsset( provider );
+//          context.getWebArchive().addAsWebInfResource(
+//              asset, HostmapFunctionProcessor.DESCRIPTOR_DEFAULT_FILE_NAME );
+//          func.config( HostmapFunctionProcessor.DESCRIPTOR_DEFAULT_LOCATION );
+//        }
+//      }
+    }
+  }
+
+//  private Asset createAsset( Provider provider ) {
+//    StringWriter buffer = new StringWriter();
+//    PrintWriter writer = new PrintWriter( buffer );
+//    for( Map.Entry<String,String> entry : provider.getParams().entrySet() ) {
+//      String externalHosts = entry.getKey();
+//      String internalHosts = entry.getValue();
+//      writer.print( externalHosts );
+//      writer.print( "=" );
+//      writer.println( internalHosts ) ;
+//    }
+//    writer.close();
+//    String string = buffer.toString();
+//    Asset asset = new StringAsset( string );
+//    return asset;
+//  }
+
+  @Override
+  public void contributeFilter(
+      DeploymentContext context,
+      Provider provider,
+      Service service,
+      ResourceDescriptor resource,
+      List<FilterParamDescriptor> params ) {
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncodeDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncodeDescriptor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncodeDescriptor.java
new file mode 100644
index 0000000..45f3ddc
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncodeDescriptor.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.knox.gateway.securequery;
+
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
+
+public class SecureQueryEncodeDescriptor
+    extends UrlRewriteActionDescriptorBase
+    implements UrlRewriteActionDescriptor {
+
+  static final String STEP_NAME = "encode-query";
+
+  public SecureQueryEncodeDescriptor() {
+    super( STEP_NAME );
+  }
+
+  @Override
+  public String getParam() {
+    return null;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncodeProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncodeProcessor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncodeProcessor.java
new file mode 100644
index 0000000..b3aeb24
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncodeProcessor.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.knox.gateway.securequery;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+public class SecureQueryEncodeProcessor
+    implements UrlRewriteStepProcessor<SecureQueryEncodeDescriptor> {
+
+  private static final String ENCODED_PARAMETER_NAME = "_";
+
+  @Override
+  public String getType() {
+    return SecureQueryEncodeDescriptor.STEP_NAME;
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, SecureQueryEncodeDescriptor descriptor ) throws Exception {
+  }
+
+  @Override
+  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
+    //TODO: Need some way to get a reference to the keystore service and the encryption key in particular.
+    Template url = context.getCurrentUrl();
+    String str = url.toString();
+    String path = str;
+    String query = null;
+    int index = str.indexOf( '?' );
+    if( index >= 0 ) {
+      path = str.substring( 0, index );
+      if( index < str.length() ) {
+        query = str.substring( index + 1 );
+      }
+    }
+    if( query != null ) {
+      query = Base64.encodeBase64String( query.getBytes( "UTF-8" ) );
+      query = removeTrailingEquals( query );
+      url = Parser.parseLiteral( path + "?" + ENCODED_PARAMETER_NAME +"=" + query );
+      context.setCurrentUrl( url );
+    }
+    return UrlRewriteStepStatus.SUCCESS;
+  }
+
+  @Override
+  public void destroy() {
+  }
+
+  private static String removeTrailingEquals( String s ) {
+    int i = s.length()-1;
+    while( i > 0 && s.charAt( i ) == '=' ) {
+      i--;
+    }
+    return s.substring( 0, i+1 );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncryptDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncryptDescriptor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncryptDescriptor.java
new file mode 100644
index 0000000..23b79cf
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncryptDescriptor.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.knox.gateway.securequery;
+
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
+
+public class SecureQueryEncryptDescriptor
+    extends UrlRewriteActionDescriptorBase
+    implements UrlRewriteActionDescriptor {
+
+  static final String STEP_NAME = "encrypt-query";
+
+  public SecureQueryEncryptDescriptor() {
+    super( STEP_NAME );
+  }
+
+  @Override
+  public String getParam() {
+    return null;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncryptProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncryptProcessor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncryptProcessor.java
new file mode 100644
index 0000000..5e44d20
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryEncryptProcessor.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.knox.gateway.securequery;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.CryptoService;
+import org.apache.knox.gateway.services.security.EncryptionResult;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.io.UnsupportedEncodingException;
+
+public class SecureQueryEncryptProcessor
+    implements UrlRewriteStepProcessor<SecureQueryEncryptDescriptor> {
+
+  private static final String ENCRYPTED_PARAMETER_NAME = "_";
+
+  private String clusterName;
+  private CryptoService cryptoService = null;
+
+  @Override
+  public String getType() {
+    return SecureQueryEncryptDescriptor.STEP_NAME;
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, SecureQueryEncryptDescriptor descriptor ) throws Exception {
+    clusterName = environment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE );
+    GatewayServices services = environment.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
+    cryptoService = (CryptoService) services.getService(GatewayServices.CRYPTO_SERVICE);
+  }
+
+  @Override
+  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
+    //TODO: Need some way to get a reference to the keystore service and the encryption key in particular.
+    Template url = context.getCurrentUrl();
+    String str = url.toString();
+    String path = str;
+    String query = null;
+    int index = str.indexOf( '?' );
+    if( index >= 0 ) {
+      path = str.substring( 0, index );
+      if( index < str.length() ) {
+        query = str.substring( index + 1 );
+      }
+    }
+    if( query != null ) {
+      query = encode( query );
+      url = Parser.parseLiteral( path + "?" + ENCRYPTED_PARAMETER_NAME +"=" + query );
+      context.setCurrentUrl( url );
+    }
+    return UrlRewriteStepStatus.SUCCESS;
+  }
+
+  @Override
+  public void destroy() {
+  }
+
+  private String encode( String string ) throws UnsupportedEncodingException {
+    EncryptionResult result = cryptoService.encryptForCluster(clusterName, "encryptQueryString", string.getBytes("UTF-8"));
+    string = Base64.encodeBase64URLSafeString(result.toByteAray());
+    return string;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryMessages.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryMessages.java
new file mode 100644
index 0000000..62f0e9f
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryMessages.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.securequery;
+
+import org.apache.knox.gateway.i18n.messages.Message;
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.Messages;
+import org.apache.knox.gateway.i18n.messages.StackTrace;
+
+@Messages(logger="org.apache.hadoop.gateway.securequery")
+public interface SecureQueryMessages {
+
+  @Message( level = MessageLevel.ERROR, text = "Failed to create or verify the presence of a password for query string encryption: {0}" )
+  void unableCreatePasswordForEncryption(@StackTrace( level = MessageLevel.DEBUG ) Exception e);
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index 14ed327..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.securequery.SecureQueryDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor b/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
deleted file mode 100644
index c5f9376..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
+++ /dev/null
@@ -1,22 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.securequery.SecureQueryEncodeDescriptor
-org.apache.hadoop.gateway.securequery.SecureQueryDecodeDescriptor
-org.apache.hadoop.gateway.securequery.SecureQueryEncryptDescriptor
-org.apache.hadoop.gateway.securequery.SecureQueryDecryptDescriptor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor b/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
deleted file mode 100644
index f216d77..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
+++ /dev/null
@@ -1,22 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.securequery.SecureQueryEncodeProcessor
-org.apache.hadoop.gateway.securequery.SecureQueryDecodeProcessor
-org.apache.hadoop.gateway.securequery.SecureQueryEncryptProcessor
-org.apache.hadoop.gateway.securequery.SecureQueryDecryptProcessor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..45705ad
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.securequery.SecureQueryDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor b/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
new file mode 100644
index 0000000..4e7c21f
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
@@ -0,0 +1,22 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.securequery.SecureQueryEncodeDescriptor
+org.apache.knox.gateway.securequery.SecureQueryDecodeDescriptor
+org.apache.knox.gateway.securequery.SecureQueryEncryptDescriptor
+org.apache.knox.gateway.securequery.SecureQueryDecryptDescriptor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor b/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
new file mode 100644
index 0000000..27f5951
--- /dev/null
+++ b/gateway-provider-rewrite-step-secure-query/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
@@ -0,0 +1,22 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.securequery.SecureQueryEncodeProcessor
+org.apache.knox.gateway.securequery.SecureQueryDecodeProcessor
+org.apache.knox.gateway.securequery.SecureQueryEncryptProcessor
+org.apache.knox.gateway.securequery.SecureQueryDecryptProcessor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeDescriptorTest.java b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeDescriptorTest.java
deleted file mode 100644
index cb496e8..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeDescriptorTest.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.hadoop.gateway.securequery;
-
-import org.junit.Test;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-public class SecureQueryDecodeDescriptorTest {
-
-  @Test
-  public void testGetAndSet() {
-    SecureQueryDecodeDescriptor descriptor = new SecureQueryDecodeDescriptor();
-    assertThat( descriptor.type(), is( "decode-query" ) );
-    assertThat( descriptor.getParam(), nullValue() );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeProcessorTest.java b/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeProcessorTest.java
deleted file mode 100644
index b6a7c5c..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeProcessorTest.java
+++ /dev/null
@@ -1,125 +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.hadoop.gateway.securequery;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-import org.easymock.Capture;
-import org.easymock.EasyMock;
-import org.junit.Test;
-import sun.misc.BASE64Encoder;
-
-import java.io.IOException;
-import java.net.URL;
-import java.util.List;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-public class SecureQueryDecodeProcessorTest {
-
-  @Test
-  public void testSimpleQueryDecode() throws Exception {
-    UrlRewriteEnvironment environment = new UrlRewriteEnvironment() {
-      @Override
-      public URL getResource( String name ) throws IOException {
-        return null;
-      }
-
-      @Override
-      public <T> T getAttribute( String name ) {
-        return null;
-      }
-
-      @Override
-      public List<String> resolve( String name ) {
-        return null;
-      }
-    };
-
-    BASE64Encoder encoder = new BASE64Encoder();
-    String encQuery = encoder.encode( "test-query".getBytes("utf-8" ) );
-    encQuery = encQuery.replaceAll( "\\=", "" );
-    String inString = "http://host:0/root/path?_=" + encQuery;
-    Template inTemplate = Parser.parseLiteral( inString );
-
-    UrlRewriteContext context = EasyMock.createNiceMock( UrlRewriteContext.class );
-    EasyMock.expect( context.getCurrentUrl() ).andReturn( inTemplate );
-    Capture<Template> outTemplate = new Capture<Template>();
-    context.setCurrentUrl( EasyMock.capture( outTemplate ) );
-    EasyMock.replay( context );
-
-    SecureQueryDecodeDescriptor descriptor = new SecureQueryDecodeDescriptor();
-    SecureQueryDecodeProcessor processor = new SecureQueryDecodeProcessor();
-    processor.initialize( environment, descriptor );
-    processor.process( context );
-
-    String outActual = outTemplate.getValue().toString();
-    assertThat( outActual, is( "http://host:0/root/path?test-query" ) );
-  }
-
-  @Test
-  public void testDecodeQueryWithNonEncodedParams() throws Exception {
-    UrlRewriteEnvironment environment = new UrlRewriteEnvironment() {
-      @Override
-      public URL getResource( String name ) throws IOException {
-        return null;
-      }
-
-      @Override
-      public <T> T getAttribute( String name ) {
-        return null;
-      }
-
-      @Override
-      public List<String> resolve( String name ) {
-        return null;
-      }
-    };
-
-    BASE64Encoder encoder = new BASE64Encoder();
-    String inQuery = "test-query=test-value";
-    String encQuery = encoder.encode( inQuery.getBytes( "utf-8" ) );
-    encQuery = encQuery.replaceAll( "\\=", "" );
-    String inString = "http://host:0/root/path?_=" + encQuery + "&clear-param=clear-value";
-    Template inTemplate = Parser.parseLiteral( inString );
-
-    UrlRewriteContext context = EasyMock.createNiceMock( UrlRewriteContext.class );
-    EasyMock.expect( context.getCurrentUrl() ).andReturn( inTemplate );
-    Capture<Template> outTemplate = new Capture<Template>();
-    context.setCurrentUrl( EasyMock.capture( outTemplate ) );
-    EasyMock.replay( context );
-
-    SecureQueryDecodeDescriptor descriptor = new SecureQueryDecodeDescriptor();
-    SecureQueryDecodeProcessor processor = new SecureQueryDecodeProcessor();
-    processor.initialize( environment, descriptor );
-    processor.process( context );
-
-    String outActual = outTemplate.getValue().toString();
-    assertThat( outActual, containsString( "http://host:0/root/path?" ) );
-    assertThat( outActual, containsString( "test-query=test-value" ) );
-    assertThat( outActual, containsString( "clear-param=clear-value" ) );
-    assertThat( outActual, not( containsString( encQuery ) ) );
-  }
-
-
-}


[23/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormFilterReader.java
new file mode 100644
index 0000000..7d82633
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormFilterReader.java
@@ -0,0 +1,105 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.form;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteUtil;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringWriter;
+
+public class FormFilterReader extends Reader {
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+
+  private int offset;
+  private StringWriter writer;
+  private StringBuffer buffer;
+  private Reader reader;
+  private FormReader parser;
+  private FormWriter generator;
+  private UrlRewriteFilterContentDescriptor config;
+
+  public FormFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException {
+    this.reader = reader;
+    this.config = config;
+    parser = new FormReader( reader );
+    writer = new StringWriter();
+    buffer = writer.getBuffer();
+    offset = 0;
+    generator = new FormWriter( writer );
+  }
+
+  @Override
+  public int read( char[] destBuffer, int destOffset, int destCount ) throws IOException {
+    int count = 0;
+    int available = buffer.length() - offset;
+
+    if( available == 0 ) {
+      FormPair pair = parser.getNextPair();
+      if( pair == null ) {
+        count = -1;
+      } else {
+        processPair();
+        available = buffer.length() - offset;
+      }
+    }
+
+    if( available > 0 ) {
+      count = Math.min( destCount, available );
+      buffer.getChars( offset, offset+count, destBuffer, destOffset );
+      offset += count;
+      if( offset == buffer.length() ) {
+        offset = 0;
+        buffer.setLength( 0 );
+      }
+    }
+
+    return count;
+  }
+
+  private void processPair() throws IOException {
+    FormPair pair = parser.getCurrentPair();
+    String name = pair.getName();
+    String value = pair.getValue();
+    String rule = UrlRewriteUtil.pickFirstRuleWithEqualsIgnoreCasePathMatch( config, name );
+    try {
+      value = filterValue( name, pair.getValue(), rule );
+      pair.setValue( value );
+    } catch( Exception e ) {
+      LOG.failedToFilterValue( pair.getValue(), rule, e );
+      // Write original value.
+    }
+    generator.writePair( pair );
+  }
+
+  protected String filterValue( String name, String value, String rule ) {
+    return value;
+  }
+
+  @Override
+  public void close() throws IOException {
+    writer.close();
+    reader.close();
+  }
+
+}
+

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormPair.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormPair.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormPair.java
new file mode 100644
index 0000000..95c896b
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormPair.java
@@ -0,0 +1,51 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.form;
+
+public class FormPair {
+
+  String name;
+  String value;
+
+  public FormPair() {
+    this.name = null;
+    this.value = null;
+  }
+
+  public FormPair( String name, String value ) {
+    this.name = name;
+    this.value = value;
+  }
+
+  public String getName() {
+    return name;
+  }
+
+  public void setName( String name ) {
+    this.name = name;
+  }
+
+  public String getValue() {
+    return value;
+  }
+
+  public void setValue( String value ) {
+    this.value = value;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormReader.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormReader.java
new file mode 100644
index 0000000..af34088
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormReader.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.knox.gateway.filter.rewrite.impl.form;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+
+public class FormReader {
+
+  private static final String DEFFAULT_FORM_ENCODING = "UTF-8";
+
+  private static final int DEFAULT_BUFFER_SIZE = 1024;
+
+  private Reader reader;
+  private FormPair current;
+  private StringBuilder buffer;
+  private int sepIndex;
+
+  public FormReader( Reader reader ) {
+    this.reader = reader;
+    this.current = null;
+    this.buffer = new StringBuilder( DEFAULT_BUFFER_SIZE );
+    this.sepIndex = -1;
+  }
+
+  public FormPair getNextPair() throws IOException {
+    while( true ) {
+      int c = reader.read();
+      switch( c ) {
+        case '=':
+          sepIndex = buffer.length();
+          break;
+        case '&':
+          // Ignore adjacent &s.
+          if( buffer.length() == 0 ) {
+            sepIndex = -1;
+            continue;
+          } else {
+            return createCurrentPair();
+          }
+        case -1:
+          // Ignore adjacent &s.
+          if( buffer.length() == 0 ) {
+            sepIndex = -1;
+            return null;
+          } else {
+            return createCurrentPair();
+          }
+        default:
+          buffer.append( (char)c );
+          break;
+      }
+    }
+  }
+
+  private FormPair createCurrentPair() throws UnsupportedEncodingException {
+    String name;
+    String value;
+    if( sepIndex >= 0 ) {
+      name = buffer.substring( 0, sepIndex );
+      value = buffer.substring( sepIndex );
+    } else {
+      name = buffer.toString();
+      value = "";
+    }
+    name = URLDecoder.decode( name, DEFFAULT_FORM_ENCODING );
+    value = URLDecoder.decode( value, DEFFAULT_FORM_ENCODING );
+    FormPair pair = new FormPair( name, value );
+    current = pair;
+    buffer.setLength( 0 );
+    sepIndex = -1;
+    return pair;
+  }
+
+  public FormPair getCurrentPair() {
+    return current;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormUrlRewriteFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormUrlRewriteFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormUrlRewriteFilterReader.java
new file mode 100644
index 0000000..d8f8ba4
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormUrlRewriteFilterReader.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.knox.gateway.filter.rewrite.impl.form;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.net.URISyntaxException;
+
+public class FormUrlRewriteFilterReader extends FormFilterReader {
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+
+  private Resolver resolver;
+  private UrlRewriter rewriter;
+  private UrlRewriter.Direction direction;
+
+  public FormUrlRewriteFilterReader( Reader reader, UrlRewriter rewriter, Resolver resolver, UrlRewriter.Direction direction, UrlRewriteFilterContentDescriptor config  ) throws IOException {
+    super( reader, config );
+    this.resolver = resolver;
+    this.rewriter = rewriter;
+    this.direction = direction;
+  }
+
+  //TODO: Need to limit which values are attempted to be filtered by the name.
+  @Override
+  protected String filterValue( String name, String value, String rule ) {
+    try {
+      Template input = Parser.parseLiteral( value );
+      Template output = rewriter.rewrite( resolver, input, direction, rule );
+      value = output.getPattern();
+    } catch( URISyntaxException e ) {
+      LOG.failedToParseValueForUrlRewrite( value );
+    }
+    return value;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormUrlRewriteStreamFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormUrlRewriteStreamFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormUrlRewriteStreamFilter.java
new file mode 100644
index 0000000..d75868d
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormUrlRewriteStreamFilter.java
@@ -0,0 +1,59 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.form;
+
+import org.apache.commons.io.input.ReaderInputStream;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStreamFilter;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+public class FormUrlRewriteStreamFilter implements UrlRewriteStreamFilter {
+
+  private static String[] TYPES = new String[]{ "application/x-www-form-urlencoded", "*/x-www-form-urlencoded" };
+  private static String[] NAMES = new String[]{ null };
+
+  @Override
+  public String[] getTypes() {
+    return TYPES;
+  }
+
+  @Override
+  public String[] getNames() {
+    return NAMES;
+  }
+
+  @Override
+  public InputStream filter(
+      InputStream stream,
+      String encoding,
+      UrlRewriter rewriter,
+      Resolver resolver,
+      UrlRewriter.Direction direction,
+      UrlRewriteFilterContentDescriptor config )
+          throws IOException {
+    return new ReaderInputStream(
+        new FormUrlRewriteFilterReader(
+            new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormWriter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormWriter.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormWriter.java
new file mode 100644
index 0000000..b59d4d4
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormWriter.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.knox.gateway.filter.rewrite.impl.form;
+
+import java.io.IOException;
+import java.io.Writer;
+import java.net.URLEncoder;
+
+public class FormWriter {
+
+  private static final String DEFFAULT_FORM_ENCODING = "UTF-8";
+
+  private Writer writer;
+  boolean first;
+
+  public FormWriter( Writer writer ) {
+    this.writer = writer;
+    this.first = true;
+  }
+
+  public void writePair( FormPair pair ) throws IOException {
+    if( first ) {
+      first = false;
+    } else {
+      writer.write( "&" );
+    }
+    writer.write( URLEncoder.encode( pair.getName(), DEFFAULT_FORM_ENCODING ) );
+    writer.write( "=" );
+    writer.write( URLEncoder.encode( pair.getValue(), DEFFAULT_FORM_ENCODING ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlFilterReader.java
new file mode 100644
index 0000000..c141fa6
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlFilterReader.java
@@ -0,0 +1,61 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.html;
+
+import javax.xml.namespace.QName;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+
+import java.io.IOException;
+import java.io.Reader;
+
+//map.put( "meta", buildTagPattern( ".*url\\s*=\\s*['\"]?(.*?)[;\\s'\"\\/>].*" ) );
+//map.put( "link", buildTagPattern( ".*href\\s*=\\s*['\"]?(.*?)['\"\\>].*" ) );
+//map.put( "a", buildTagPattern( ".*href\\s*=\\s*['\"]?(.*?)['\"\\>].*" ) );
+//map.put( "th", buildTagPattern( ".*window.document.location\\s*=\\s*['\"]?(.*?)['\"\\>].*" ) );
+//    assertMatch( pattern, "<meta HTTP-EQUIV=\"REFRESH\" content=\"0;url=dfshealth.jsp\"/>", "meta" );
+//String markup = "<link href=\"/static/org.apache.hadoop.css\" rel=\"stylesheet\" type=\"text/css\" >";
+//String markup = "<a href=\"dfsnodelist.jsp?whatNodes=DECOMMISSIONING\">";
+//String markup = "th class=headerASC onClick=\"window.document.location='/dfsnodelist.jsp?whatNodes=LIVE&sorter/field=name&sorter/order=DSC'\" title=\"sort on this column\">";
+
+public abstract class HtmlFilterReader extends HtmlFilterReaderBase {
+
+  public HtmlFilterReader( Reader reader ) throws IOException, ParserConfigurationException {
+    super( reader );
+  }
+
+  public HtmlFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException, ParserConfigurationException {
+    super( reader, config );
+  }
+
+  protected abstract String filterAttribute( String tagName, String attributeName, String attributeValue, String ruleName );
+
+  protected abstract String filterText( String tagName, String text, String ruleName );
+
+  @Override
+  protected final String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
+    return filterAttribute( elementName.getLocalPart(), attributeName.getLocalPart(), attributeValue, ruleName );
+  }
+
+  @Override
+  protected final String filterText( QName elementName, String text, String ruleName ) {
+    return filterText( elementName.getLocalPart(), text, ruleName );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlFilterReaderBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlFilterReaderBase.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlFilterReaderBase.java
new file mode 100644
index 0000000..b90771b
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlFilterReaderBase.java
@@ -0,0 +1,327 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.html;
+
+import net.htmlparser.jericho.Attribute;
+import net.htmlparser.jericho.Attributes;
+import net.htmlparser.jericho.EndTag;
+import net.htmlparser.jericho.Segment;
+import net.htmlparser.jericho.StartTag;
+import net.htmlparser.jericho.StreamedSource;
+import net.htmlparser.jericho.Tag;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteFilterReader;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteUtil;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.util.XmlUtils;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import javax.xml.namespace.QName;
+import javax.xml.parsers.ParserConfigurationException;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Stack;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public abstract class HtmlFilterReaderBase extends Reader implements
+    UrlRewriteFilterReader {
+
+  private static final String SCRIPTTAG = "script";
+  private static final UrlRewriteFilterPathDescriptor.Compiler<Pattern> REGEX_COMPILER = new RegexCompiler();
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+
+  private Document document;
+  private Stack<Level> stack;
+  private Reader reader;
+  private StreamedSource parser;
+  private Iterator<Segment> iterator;
+  private int lastSegEnd;
+  private int offset;
+  private StringWriter writer;
+  private StringBuffer buffer;
+  private UrlRewriteFilterContentDescriptor config = null;
+
+  protected HtmlFilterReaderBase( Reader reader ) throws IOException, ParserConfigurationException {
+    this.reader = reader;
+    document = XmlUtils.createDocument( false );
+    stack = new Stack<Level>();
+    parser = new StreamedSource( reader );
+    iterator = parser.iterator();
+    writer = new StringWriter();
+    buffer = writer.getBuffer();
+    offset = 0;
+  }
+
+  protected HtmlFilterReaderBase( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException, ParserConfigurationException {
+    this(reader);
+    this.config = config;
+  }
+
+  protected abstract String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName );
+
+  protected abstract String filterText( QName elementName, String text, String ruleName );
+
+  @Override
+  public int read( char[] destBuffer, int destOffset, int destCount ) throws IOException {
+    int count = 0;
+    int available = buffer.length() - offset;
+
+    if( available == 0 ) {
+      if( iterator.hasNext() ) {
+        iterator.next();
+        processCurrentSegment();
+        available = buffer.length() - offset;
+      } else {
+        count = -1;
+      }
+    }
+
+    if( available > 0 ) {
+      count = Math.min( destCount, available );
+      buffer.getChars( offset, offset + count, destBuffer, destOffset );
+      offset += count;
+      if( offset == buffer.length() ) {
+        offset = 0;
+        buffer.setLength( 0 );
+      }
+    }
+
+    return count;
+  }
+
+  private void processCurrentSegment() {
+    Segment segment = parser.getCurrentSegment();
+    // If this tag is inside the previous tag (e.g. a server tag) then
+    // ignore it as it was already output along with the previous tag.
+    if( segment.getEnd() <= lastSegEnd ) {
+      return;
+    }
+    lastSegEnd = segment.getEnd();
+    if( segment instanceof Tag ) {
+      if( segment instanceof StartTag ) {
+        processStartTag( (StartTag)segment );
+      } else if ( segment instanceof EndTag ) {
+        processEndTag( (EndTag)segment );
+      } else {
+        writer.write( segment.toString() );
+      }
+    } else {
+      processText( segment );
+    }
+  }
+
+  private void processEndTag( EndTag tag ) {
+    while( !stack.isEmpty() ) {
+      Level popped = stack.pop();
+      if( popped.getTag().getName().equalsIgnoreCase( tag.getName() ) ) {
+        break;
+      }
+    }
+    writer.write( tag.toString() );
+  }
+
+  private void processStartTag( StartTag tag ) {
+    if( "<".equals( tag.getTagType().getStartDelimiter() ) ) {
+      Element e = document.createElement( tag.getNameSegment().toString() );
+      stack.push( new Level( tag ) );
+      writer.write( "<" );
+      writer.write( tag.getNameSegment().toString() );
+      Attributes attributes = tag.getAttributes();
+      if( !attributes.isEmpty() ) {
+        for( Attribute attribute : attributes ) {
+          processAttribute( attribute );
+        }
+      }
+      if( tag.toString().trim().endsWith( "/>" ) || tag.isEmptyElementTag() ) {
+        stack.pop();
+        writer.write( "/>" );
+      } else {
+        writer.write( ">" );
+      }
+    } else {
+      writer.write( tag.toString() );
+    }
+  }
+
+  private void processAttribute( Attribute attribute ) {
+    writer.write( " " );
+    writer.write( attribute.getName() );
+    if(attribute.hasValue()) {
+      /*
+       * non decoded value, return the raw value of the attribute as it appears
+       * in the source document, without decoding, see KNOX-791.
+       */
+      String inputValue = attribute.getValueSegment().toString();
+      String outputValue = inputValue;
+      try {
+        Level tag = stack.peek();
+        String name = getRuleName(inputValue);
+        outputValue = filterAttribute( tag.getQName(), tag.getQName( attribute.getName() ), inputValue, name );
+        if( outputValue == null ) {
+          outputValue = inputValue;
+        }
+      } catch ( Exception e ) {
+        LOG.failedToFilterAttribute( attribute.getName(), e );
+      }
+      writer.write( "=" );
+      writer.write( attribute.getQuoteChar() );
+      writer.write( outputValue );
+      writer.write( attribute.getQuoteChar() );
+    }
+  }
+
+  private String getRuleName(String inputValue) {
+    if( config != null && !config.getSelectors().isEmpty() ) {
+      for( UrlRewriteFilterPathDescriptor selector : config.getSelectors() ) {
+        if ( selector instanceof UrlRewriteFilterApplyDescriptor) {
+          UrlRewriteFilterApplyDescriptor apply = (UrlRewriteFilterApplyDescriptor)selector;
+          Matcher matcher = apply.compiledPath( REGEX_COMPILER ).matcher( inputValue );
+            if (matcher.matches()) {
+              return apply.rule();
+            }
+          }
+        }
+      }
+      return null;
+    }
+
+  private void processText( Segment segment ) {
+    String inputValue = segment.toString();
+    String outputValue = inputValue;
+    try {
+      if( stack.isEmpty() ) {
+        // This can happen for whitespace outside of the root element.
+        //outputValue = filterText( null, inputValue );
+      } else {
+        String tagName = stack.peek().getTag().getName();
+        if (SCRIPTTAG.equals(tagName) && config != null && !config.getSelectors().isEmpty() ) {
+          // embedded javascript content
+          outputValue = UrlRewriteUtil.filterJavaScript( inputValue, config, this, REGEX_COMPILER );
+        } else {
+          outputValue = filterText( stack.peek().getQName(), inputValue, getRuleName(inputValue) );
+        }
+      }
+      if( outputValue == null ) {
+        outputValue = inputValue;
+      }
+    } catch ( Exception e ) {
+      LOG.failedToFilterValue( inputValue, null, e );
+    }
+    writer.write( outputValue );
+  }
+
+  @Override
+  public void close() throws IOException {
+    parser.close();
+    reader.close();
+    writer.close();
+    stack.clear();
+  }
+
+  private String getNamespace( String prefix ) {
+    String namespace = null;
+    for( Level level : stack ) {
+      namespace = level.getNamespace( prefix );
+      if( namespace != null ) {
+        break;
+      }
+    }
+    return namespace;
+  }
+
+  private static class Level {
+    private StartTag tag;
+    private QName name;
+    private Map<String,String> namespaces;
+
+    private Level( StartTag tag ) {
+      this.tag = tag;
+      this.name = null;
+      this.namespaces = null;
+    }
+
+    private StartTag getTag() {
+      return tag;
+    }
+
+    private QName getQName() {
+      if( name == null ) {
+        name = getQName( tag.getName() );
+      }
+      return name;
+    }
+
+    private String getNamespace( String prefix ) {
+      return getNamespaces().get( prefix );
+    }
+
+    private QName getQName( String name ) {
+      String prefix;
+      String local;
+      int colon = ( name == null ? -1 : name.indexOf( ':' ) );
+      if( colon < 0 ) {
+        prefix = "";
+        local = name;
+      } else {
+        prefix = name.substring( 0, colon );
+        local = ( colon + 1 < name.length() ? name.substring( colon + 1 ) : "" );
+      }
+      String namespace = getNamespace( prefix );
+      return new QName( namespace, local, prefix );
+    }
+
+    private Map<String,String> getNamespaces() {
+      if( namespaces == null ) {
+        namespaces = new HashMap<>();
+        parseNamespaces();
+      }
+      return namespaces;
+    }
+
+    private void parseNamespaces() {
+      Attributes attributes = tag.getAttributes();
+      if( attributes != null ) {
+        for( Attribute attribute : tag.getAttributes() ) {
+          String name = attribute.getName();
+          if( name.toLowerCase().startsWith( "xmlns" ) ) {
+            int colon = name.indexOf( ":", 5 );
+            String prefix;
+            if( colon <= 0 ) {
+              prefix = "";
+            } else {
+              prefix = name.substring( colon );
+            }
+            namespaces.put( prefix, attribute.getValue() );
+          }
+        }
+      }
+    }
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlImportFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlImportFunctionDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlImportFunctionDescriptor.java
new file mode 100644
index 0000000..ee11b7f
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlImportFunctionDescriptor.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.html;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+public class HtmlImportFunctionDescriptor implements
+    UrlRewriteFunctionDescriptor<HtmlImportFunctionDescriptor> {
+
+  public static final String FUNCTION_NAME = "import";
+
+  @Override
+  public String name() {
+    return FUNCTION_NAME;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessor.java
new file mode 100644
index 0000000..280f1b5
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessor.java
@@ -0,0 +1,90 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.html;
+
+import org.apache.knox.gateway.filter.rewrite.api.FrontendFunctionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptorFactory;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteFunctionProcessorFactory;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * This function enhances the 'frontend' function with the ability to add a prefix to the rewritten frontend portion
+ * along with the '@import' literal. This is a workaround for the requirement to provide the ability to rewrite
+ * a portion of html content that contains a tag like the following
+ *
+ * <head> <style type=\"text/css\">@import "pretty.css";</style></head>
+ *
+ * and needs to be rewritten to something like
+ *
+ * <head> <style type=\"text/css\">@import "http://localhost:8443/sandbox/service/pretty.css";</style></head>
+ *
+ * The rewrite rule could then contain the $import function that would delegate to the frontend function.
+ *
+ * If there are more than one params passed, the first one is used as a prefix to the value of the frontend function.
+ *
+ */
+public class HtmlImportFunctionProcessor implements UrlRewriteFunctionProcessor<HtmlImportFunctionDescriptor> {
+
+  private static final String IMPORT_LITERAL = "@import";
+
+  private UrlRewriteFunctionProcessor frontend;
+
+  @Override
+  public void initialize(UrlRewriteEnvironment environment, HtmlImportFunctionDescriptor descriptor) throws Exception {
+    UrlRewriteFunctionDescriptor frontendDescriptor = UrlRewriteFunctionDescriptorFactory
+        .create(FrontendFunctionDescriptor.FUNCTION_NAME);
+    frontend = UrlRewriteFunctionProcessorFactory.create(FrontendFunctionDescriptor.FUNCTION_NAME, frontendDescriptor);
+    frontend.initialize(environment, frontendDescriptor);
+  }
+
+  @Override
+  public void destroy() throws Exception {
+    frontend.destroy();
+  }
+
+  @Override
+  public List<String> resolve(UrlRewriteContext context, List<String> parameters) throws Exception {
+    String prefix = "";
+    if ( parameters != null && parameters.size() > 1 ) {
+      prefix = parameters.get(0);
+      parameters = parameters.subList(1, parameters.size());
+    }
+    List<String> frontendValues = frontend.resolve(context, parameters);
+    StringBuffer buffer = new StringBuffer(IMPORT_LITERAL);
+    buffer.append(" ");
+    buffer.append(prefix);
+    if ( frontendValues != null && frontendValues.size() > 0 ) {
+      for ( String value : frontendValues ) {
+        buffer.append(value);
+      }
+    }
+    return Arrays.asList(buffer.toString());
+  }
+
+  @Override
+  public String name() {
+    return HtmlImportFunctionDescriptor.FUNCTION_NAME;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlPrefixDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlPrefixDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlPrefixDescriptor.java
new file mode 100644
index 0000000..0f37b50
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlPrefixDescriptor.java
@@ -0,0 +1,48 @@
+package org.apache.knox.gateway.filter.rewrite.impl.html;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership.  The ASF
+ * licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+/**
+ * {@link UrlRewriteFunctionDescriptor} for the variable {@link
+ * HtmlPrefixDescriptor#FUNCTION_NAME}
+ *
+ * @since 0.14.0
+ */
+public class HtmlPrefixDescriptor
+    implements UrlRewriteFunctionDescriptor<HtmlPrefixDescriptor> {
+
+  /**
+   * variable name used in rewrite.xml
+   */
+  public static final String FUNCTION_NAME = "prefix";
+
+  /**
+   * Create an instance
+   */
+  public HtmlPrefixDescriptor() {
+    super();
+  }
+
+  @Override
+  public String name() {
+    return FUNCTION_NAME;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlPrefixProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlPrefixProcessor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlPrefixProcessor.java
new file mode 100644
index 0000000..d7983ef
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlPrefixProcessor.java
@@ -0,0 +1,104 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with this
+ * work for additional information regarding copyright ownership.  The ASF
+ * licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * 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.knox.gateway.filter.rewrite.impl.html;
+
+import org.apache.knox.gateway.filter.rewrite.api.FrontendFunctionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptorFactory;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteFunctionProcessorFactory;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * This function enhances the 'frontend' function with the ability to add a
+ * prefix to the rewritten frontend portion along with the literals
+ * provided as an argument.
+ * <p>
+ * <div ng-include src=\"'components/navbar/navbar.html?v=1498928142479'\"></div>
+ * <p>
+ * and needs to be rewritten to something like
+ * <p>
+ * <div ng-include src=\"'http://localhost:8443/sandbox/service/components/navbar/navbar.html?v=1498928142479'\"></div>
+ * <p>
+ * The rewrite rule could then contain the $prefix function that would delegate
+ * to the frontend function.
+ * <p>
+ * The parameter to the function would be the symbol used as a prefix.
+ */
+
+public class HtmlPrefixProcessor
+    implements UrlRewriteFunctionProcessor<HtmlPrefixDescriptor> {
+
+  private UrlRewriteFunctionProcessor frontend;
+
+  /**
+   * Create an instance
+   */
+  public HtmlPrefixProcessor() {
+    super();
+  }
+
+  @Override
+  public void initialize(final UrlRewriteEnvironment environment,
+      final HtmlPrefixDescriptor descriptor) throws Exception {
+
+    final UrlRewriteFunctionDescriptor frontendDescriptor = UrlRewriteFunctionDescriptorFactory
+        .create(FrontendFunctionDescriptor.FUNCTION_NAME);
+
+    frontend = UrlRewriteFunctionProcessorFactory
+        .create(FrontendFunctionDescriptor.FUNCTION_NAME, frontendDescriptor);
+
+    frontend.initialize(environment, frontendDescriptor);
+  }
+
+  @Override
+  public String name() {
+    return HtmlPrefixDescriptor.FUNCTION_NAME;
+  }
+
+  @Override
+  public void destroy() throws Exception {
+    frontend.destroy();
+  }
+
+  @Override
+  public List<String> resolve(UrlRewriteContext context,
+      List<String> parameters) throws Exception {
+    String prefix = "";
+
+    if ((parameters != null) && (parameters.size() > 1)) {
+      prefix = parameters.get(0);
+      parameters = parameters.subList(1, parameters.size());
+    }
+
+    final List<String> frontendValues = frontend.resolve(context, parameters);
+
+    final StringBuffer buffer = new StringBuffer();
+    buffer.append(prefix);
+    if (frontendValues != null && frontendValues.size() > 0) {
+      for (final String value : frontendValues) {
+        buffer.append(value);
+      }
+    }
+
+    return Arrays.asList(buffer.toString());
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlUrlRewriteFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlUrlRewriteFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlUrlRewriteFilterReader.java
new file mode 100644
index 0000000..faade4f
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlUrlRewriteFilterReader.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.knox.gateway.filter.rewrite.impl.html;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import javax.xml.parsers.ParserConfigurationException;
+import java.io.IOException;
+import java.io.Reader;
+import java.net.URISyntaxException;
+
+public class HtmlUrlRewriteFilterReader extends HtmlFilterReader {
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+  
+  private Resolver resolver;
+  private UrlRewriter rewriter;
+  private UrlRewriter.Direction direction;
+
+  public HtmlUrlRewriteFilterReader( Reader reader, UrlRewriter rewriter, Resolver resolver, UrlRewriter.Direction direction, UrlRewriteFilterContentDescriptor config )
+      throws IOException, ParserConfigurationException {
+    super( reader, config );
+    this.resolver = resolver;
+    this.rewriter = rewriter;
+    this.direction = direction;
+  }
+
+  //TODO: Need to limit which values are attempted to be filtered by the name.
+  @Override
+  public String filterValueString( String name, String value, String rule ) {
+    try {
+      Template input = Parser.parseLiteral( value );
+      Template output = rewriter.rewrite( resolver, input, direction, rule );
+      if( output != null ) {
+        value = output.getPattern();
+      }
+    } catch( URISyntaxException e ) {
+      LOG.failedToParseValueForUrlRewrite( value );
+    }
+    return value;
+  }
+
+  @Override
+  protected String filterAttribute( String tagName, String attributeName, String attributeValue, String ruleName ) {
+    return filterValueString( attributeName, attributeValue, ruleName );
+  }
+
+  @Override
+  protected String filterText( String tagName, String text, String ruleName ) {
+    return filterValueString( tagName, text, ruleName );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlUrlRewriteStreamFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlUrlRewriteStreamFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlUrlRewriteStreamFilter.java
new file mode 100644
index 0000000..543c323
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlUrlRewriteStreamFilter.java
@@ -0,0 +1,64 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.html;
+
+import org.apache.commons.io.input.ReaderInputStream;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStreamFilter;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+
+import javax.xml.parsers.ParserConfigurationException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+public class HtmlUrlRewriteStreamFilter implements UrlRewriteStreamFilter {
+
+  private static String[] TYPES = new String[]{ "application/html", "text/html", "*/html" };
+  private static String[] NAMES = new String[]{ null };
+
+  @Override
+  public String[] getTypes() {
+    return TYPES;
+  }
+
+  @Override
+  public String[] getNames() {
+    return NAMES;
+  }
+
+  @Override
+  public InputStream filter(
+      InputStream stream,
+      String encoding,
+      UrlRewriter rewriter,
+      Resolver resolver,
+      UrlRewriter.Direction direction,
+      UrlRewriteFilterContentDescriptor config )
+          throws IOException {
+    try {
+      return new ReaderInputStream(
+          new HtmlUrlRewriteFilterReader(
+              new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
+    } catch( ParserConfigurationException e ) {
+      throw new IOException( e );
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReader.java
new file mode 100644
index 0000000..89c5eaf
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReader.java
@@ -0,0 +1,91 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.javascript;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteFilterReader;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteUtil;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.util.regex.Pattern;
+
+public abstract class JavaScriptFilterReader extends Reader implements UrlRewriteFilterReader {
+
+  private static final UrlRewriteFilterPathDescriptor.Compiler<Pattern> REGEX_COMPILER = new RegexCompiler();
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+
+  private BufferedReader reader;
+  private int offset;
+  private StringWriter writer;
+  private StringBuffer buffer;
+  private UrlRewriteFilterContentDescriptor config;
+
+  protected JavaScriptFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException {
+    this.reader = new BufferedReader( reader );
+    this.config = config;
+    writer = new StringWriter();
+    buffer = writer.getBuffer();
+    offset = 0;
+  }
+
+  @Override
+  public abstract String filterValueString( String name, String value, String rule );
+
+  @Override
+  public int read( char[] destBuffer, int destOffset, int destCount ) throws IOException {
+    int count = 0;
+    int available = buffer.length() - offset;
+    String cbuff;
+    if( available == 0 ) {
+      cbuff = reader.readLine();
+      if( cbuff != null ) {
+        count = cbuff.length();
+        writer.write( UrlRewriteUtil.filterJavaScript( cbuff, config, this, REGEX_COMPILER ) );
+        writer.write( '\n' );
+        available = buffer.length() - offset;
+      } else {
+        count = -1;
+      }
+    }
+
+    if( available > 0 ) {
+      count = Math.min( destCount, available );
+      buffer.getChars( offset, offset + count, destBuffer, destOffset );
+      offset += count;
+      if( offset == buffer.length() ) {
+        offset = 0;
+        buffer.setLength( 0 );
+      }
+    }
+
+    return count;
+  }
+
+  @Override
+  public void close() throws IOException {
+    reader.close();
+    writer.close();
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteFilterReader.java
new file mode 100644
index 0000000..da1963b
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteFilterReader.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.knox.gateway.filter.rewrite.impl.javascript;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.net.URISyntaxException;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+public class JavaScriptUrlRewriteFilterReader extends JavaScriptFilterReader {
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+
+  private Resolver resolver;
+  private UrlRewriter rewriter;
+  private UrlRewriter.Direction direction;
+
+  public JavaScriptUrlRewriteFilterReader( Reader reader, UrlRewriter rewriter, Resolver resolver, UrlRewriter.Direction direction, UrlRewriteFilterContentDescriptor config )
+      throws IOException {
+    super( reader, config );
+    this.resolver = resolver;
+    this.rewriter = rewriter;
+    this.direction = direction;
+  }
+
+  @Override
+  public String filterValueString( String name, String value, String rule ) {
+    try {
+      Template input = Parser.parseLiteral( value );
+      Template output = rewriter.rewrite( resolver, input, direction, rule );
+      if( output != null ) {
+        value = output.getPattern();
+      }
+    } catch( URISyntaxException e ) {
+      LOG.failedToParseValueForUrlRewrite( value );
+    }
+    return value;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteStreamFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteStreamFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteStreamFilter.java
new file mode 100644
index 0000000..b93d6d3
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteStreamFilter.java
@@ -0,0 +1,65 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.javascript;
+
+import org.apache.commons.io.input.ReaderInputStream;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStreamFilter;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+public class JavaScriptUrlRewriteStreamFilter implements
+    UrlRewriteStreamFilter {
+
+  private static String[] TYPES = new String[]{ "application/javascript", "text/javascript", "*/javascript",
+      "application/x-javascript", "text/x-javascript", "*/x-javascript" };
+  private static String[] NAMES = new String[]{ null };
+
+  @Override
+  public String[] getTypes() {
+    return TYPES;
+  }
+
+  @Override
+  public String[] getNames() {
+    return NAMES;
+  }
+
+  @Override
+  public InputStream filter(
+      InputStream stream,
+      String encoding,
+      UrlRewriter rewriter,
+      Resolver resolver,
+      UrlRewriter.Direction direction,
+      UrlRewriteFilterContentDescriptor config )
+          throws IOException {
+
+    if ( config != null ) {
+      return new ReaderInputStream(
+          new JavaScriptUrlRewriteFilterReader(
+              new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
+    } else {
+      return stream;
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReader.java
new file mode 100644
index 0000000..8286dbc
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReader.java
@@ -0,0 +1,644 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.json;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.fasterxml.jackson.databind.node.TextNode;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterBufferDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterDetectDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterGroupDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.util.JsonPath;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.util.List;
+import java.util.Stack;
+import java.util.regex.Pattern;
+
+class JsonFilterReader extends Reader {
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+
+  private static final UrlRewriteFilterPathDescriptor.Compiler<JsonPath.Expression> JPATH_COMPILER = new JsonPathCompiler();
+  private static final UrlRewriteFilterPathDescriptor.Compiler<Pattern> REGEX_COMPILER = new RegexCompiler();
+
+  private JsonFactory factory;
+  private JsonParser parser;
+  private JsonGenerator generator;
+  private ObjectMapper mapper;
+
+  private Reader reader;
+  private int offset;
+  private StringWriter writer;
+  private StringBuffer buffer;
+  private Stack<Level> stack;
+  private Level bufferingLevel;
+  private UrlRewriteFilterBufferDescriptor bufferingConfig;
+  private UrlRewriteFilterGroupDescriptor config;
+
+
+  public JsonFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException {
+    this.reader = reader;
+    factory = new JsonFactory();
+    mapper = new ObjectMapper();
+    parser = factory.createParser( reader );
+    writer = new StringWriter();
+    buffer = writer.getBuffer();
+    offset = 0;
+    generator = factory.createGenerator( writer );
+    stack = new Stack<Level>();
+    bufferingLevel = null;
+    bufferingConfig = null;
+    this.config = config;
+  }
+
+  @Override
+  public int read( char[] destBuffer, int destOffset, int destCount ) throws IOException {
+    int count = 0;
+    int available = buffer.length() - offset;
+
+    if( available == 0 ) {
+      JsonToken token = parser.nextToken();
+      if( token == null ) {
+        count = -1;
+      } else {
+        processCurrentToken();
+        available = buffer.length() - offset;
+      }
+    }
+
+    if( available > 0 ) {
+      count = Math.min( destCount, available );
+      buffer.getChars( offset, offset+count, destBuffer, destOffset );
+      offset += count;
+      if( offset == buffer.length() ) {
+        offset = 0;
+        buffer.setLength( 0 );
+      }
+    }
+
+    return count;
+  }
+
+  private void processCurrentToken() throws IOException {
+    switch( parser.getCurrentToken() ) {
+      case START_OBJECT:
+        processStartObject();
+        break;
+      case END_OBJECT:
+        processEndObject();
+        break;
+      case START_ARRAY:
+        processStartArray();
+        break;
+      case END_ARRAY:
+        processEndArray();
+        break;
+      case FIELD_NAME:
+        processFieldName(); // Could be the name of an object, array or value.
+        break;
+      case VALUE_STRING:
+        processValueString();
+        break;
+      case VALUE_NUMBER_INT:
+      case VALUE_NUMBER_FLOAT:
+        processValueNumber();
+        break;
+      case VALUE_TRUE:
+      case VALUE_FALSE:
+        processValueBoolean();
+        break;
+      case VALUE_NULL:
+        processValueNull();
+        break;
+      case NOT_AVAILABLE:
+        // Ignore it.
+        break;
+    }
+    generator.flush();
+  }
+
+  private Level pushLevel( String field, JsonNode node, JsonNode scopeNode, UrlRewriteFilterGroupDescriptor scopeConfig ) {
+    if( !stack.isEmpty() ) {
+      Level top = stack.peek();
+      if( scopeNode == null ) {
+        scopeNode = top.scopeNode;
+        scopeConfig = top.scopeConfig;
+      }
+    }
+    Level level = new Level( field, node, scopeNode, scopeConfig );
+    stack.push( level );
+    return level;
+  }
+
+  private void processStartObject() throws IOException {
+    JsonNode node;
+    Level child;
+    Level parent;
+    if( stack.isEmpty() ) {
+      node = mapper.createObjectNode();
+      child = pushLevel( null, node, node, config );
+    } else {
+      child = stack.peek();
+      if( child.node == null ) {
+        child.node = mapper.createObjectNode();
+        parent = stack.get( stack.size()-2 );
+        switch( parent.node.asToken() ) {
+          case START_ARRAY:
+            ((ArrayNode)parent.node ).add( child.node );
+            break;
+          case START_OBJECT:
+            ((ObjectNode)parent.node ).put( child.field, child.node );
+            break;
+          default:
+            throw new IllegalStateException();
+        }
+      } else if( child.isArray() ) {
+        parent = child;
+        node = mapper.createObjectNode();
+        child = pushLevel( null, node, null, null );
+        ((ArrayNode)parent.node ).add( child.node );
+      } else {
+        throw new IllegalStateException();
+      }
+    }
+    if( bufferingLevel == null ) {
+      if( !startBuffering( child ) ) {
+        generator.writeStartObject();
+      }
+    }
+  }
+
+  private void processEndObject() throws IOException {
+    Level child;
+    Level parent;
+    child = stack.pop();
+    if( bufferingLevel == child ) {
+      filterBufferedNode( child );
+      mapper.writeTree( generator, child.node );
+      bufferingLevel = null;
+      bufferingConfig = null;
+    } else if( bufferingLevel == null ) {
+      generator.writeEndObject();
+      if( !stack.isEmpty() ) {
+        parent = stack.peek();
+        switch( parent.node.asToken() ) {
+          case START_ARRAY:
+            ((ArrayNode)parent.node ).removeAll();
+            break;
+          case START_OBJECT:
+            ((ObjectNode)parent.node ).removeAll();
+            break;
+          default:
+            throw new IllegalStateException();
+        }
+      }
+    }
+  }
+
+  private void processStartArray() throws IOException {
+    JsonNode node;
+    Level child;
+    Level parent;
+    if( stack.isEmpty() ) {
+      node = mapper.createArrayNode();
+      child = pushLevel( null, node, node, config );
+    } else {
+      child = stack.peek();
+      if( child.node == null ) {
+        child.node = mapper.createArrayNode();
+        parent = stack.get( stack.size() - 2 );
+        switch( parent.node.asToken() ) {
+          case START_ARRAY:
+            ((ArrayNode)parent.node ).add( child.node );
+            break;
+          case START_OBJECT:
+            ((ObjectNode)parent.node ).put( child.field, child.node );
+            break;
+          default:
+            throw new IllegalStateException();
+        }
+      } else if( child.isArray() ) {
+        parent = child;
+        child = pushLevel( null, mapper.createArrayNode(), null, null );
+        ((ArrayNode)parent.node ).add( child.node );
+      } else {
+        throw new IllegalStateException();
+      }
+    }
+    if( bufferingLevel == null ) {
+      if( !startBuffering( child ) ) {
+        generator.writeStartArray();
+      }
+    }
+  }
+
+  private void processEndArray() throws IOException {
+    Level child;
+    Level parent;
+    child = stack.pop();
+    if( bufferingLevel == child ) {
+      filterBufferedNode( child );
+      mapper.writeTree( generator, child.node );
+      bufferingLevel = null;
+      bufferingConfig = null;
+    } else if( bufferingLevel == null ) {
+      generator.writeEndArray();
+      if( !stack.isEmpty() ) {
+        parent = stack.peek();
+        switch( parent.node.asToken() ) {
+          case START_ARRAY:
+            ((ArrayNode)parent.node ).removeAll();
+            break;
+          case START_OBJECT:
+            ((ObjectNode)parent.node ).removeAll();
+            break;
+          default:
+            throw new IllegalStateException();
+        }
+      }
+    }
+  }
+
+  private void processFieldName() throws IOException {
+    Level child = pushLevel( parser.getCurrentName(), null, null, null );
+    try {
+      child.field = filterFieldName( child.field );
+    } catch( Exception e ) {
+      LOG.failedToFilterFieldName( child.field, e );
+      // Write original name.
+    }
+    if( bufferingLevel == null ) {
+      generator.writeFieldName( child.field );
+    }
+  }
+
+  private void processValueString() throws IOException {
+    Level child;
+    Level parent;
+    String value = null;
+    parent = stack.peek();
+    if( parent.isArray() ) {
+      ArrayNode array = (ArrayNode)parent.node;
+      array.add( parser.getText() );
+      if( bufferingLevel == null ) {
+        value = filterStreamValue( parent );
+        array.set( array.size()-1, new TextNode( value ) );
+      } else {
+        array.removeAll();
+      }
+    } else {
+      child = stack.pop();
+      parent = stack.peek();
+      ((ObjectNode)parent.node ).put( child.field, parser.getText() );
+      if( bufferingLevel == null ) {
+        child.node = parent.node; // Populate the JsonNode of the child for filtering.
+        value = filterStreamValue( child );
+      }
+    }
+    if( bufferingLevel == null ) {
+      if( parent.node.isArray() ) {
+        ((ArrayNode)parent.node).removeAll();
+      } else {
+        ((ObjectNode)parent.node).removeAll();
+      }
+      generator.writeString( value );
+    }
+  }
+
+  private void processValueNumber() throws IOException {
+    Level child;
+    Level parent;
+    parent = stack.peek();
+    if( parent.isArray() ) {
+      if( bufferingLevel != null ) {
+        ArrayNode array = (ArrayNode)parent.node;
+        processBufferedArrayValueNumber( array );
+      }
+    } else {
+      child = stack.pop();
+      if( bufferingLevel != null ) {
+        parent = stack.peek();
+        ObjectNode object = (ObjectNode)parent.node;
+        processBufferedFieldValueNumber( child, object );
+      }
+    }
+    if( bufferingLevel == null ) {
+      processedUnbufferedValueNumber();
+    }
+  }
+
+  private void processedUnbufferedValueNumber() throws IOException {
+    switch( parser.getNumberType() ) {
+      case INT:
+        generator.writeNumber( parser.getIntValue() );
+        break;
+      case LONG:
+        generator.writeNumber( parser.getLongValue() );
+        break;
+      case BIG_INTEGER:
+        generator.writeNumber( parser.getBigIntegerValue() );
+        break;
+      case FLOAT:
+        generator.writeNumber( parser.getFloatValue() );
+        break;
+      case DOUBLE:
+        generator.writeNumber( parser.getDoubleValue() );
+        break;
+      case BIG_DECIMAL:
+        generator.writeNumber( parser.getDecimalValue() );
+        break;
+    }
+  }
+
+  private void processBufferedFieldValueNumber( Level child, ObjectNode object ) throws IOException {
+    //object.put( child.field, parser.getDecimalValue() );
+    switch( parser.getNumberType() ) {
+      case INT:
+        object.put( child.field, parser.getIntValue() );
+        break;
+      case LONG:
+        object.put( child.field, parser.getLongValue() );
+        break;
+      case BIG_INTEGER:
+        object.put( child.field, parser.getDecimalValue() );
+        break;
+      case FLOAT:
+        object.put( child.field, parser.getFloatValue() );
+        break;
+      case DOUBLE:
+        object.put( child.field, parser.getDoubleValue() );
+        break;
+      case BIG_DECIMAL:
+        object.put( child.field, parser.getDecimalValue() );
+        break;
+    }
+  }
+
+  private void processBufferedArrayValueNumber( ArrayNode array ) throws IOException {
+    //array.add( parser.getDecimalValue() );
+    switch( parser.getNumberType() ) {
+      case INT:
+        array.add( parser.getIntValue() );
+        break;
+      case LONG:
+        array.add( parser.getLongValue() );
+        break;
+      case BIG_INTEGER:
+        array.add( parser.getDecimalValue() );
+        break;
+      case FLOAT:
+        array.add( parser.getFloatValue() );
+        break;
+      case DOUBLE:
+        array.add( parser.getDoubleValue() );
+        break;
+      case BIG_DECIMAL:
+        array.add( parser.getDecimalValue() );
+        break;
+    }
+  }
+
+  private void processValueBoolean() throws IOException {
+    Level child;
+    Level parent;
+    parent = stack.peek();
+    if( parent.isArray() ) {
+      ((ArrayNode)parent.node ).add( parser.getBooleanValue() );
+      //dump();
+      if( bufferingLevel == null ) {
+        ((ArrayNode)parent.node ).removeAll();
+      }
+    } else {
+      child = stack.pop();
+      parent = stack.peek();
+      ((ObjectNode)parent.node ).put( child.field, parser.getBooleanValue() );
+      //dump();
+      if( bufferingLevel == null ) {
+        ((ObjectNode)parent.node ).remove( child.field );
+      }
+    }
+    if( bufferingLevel == null ) {
+      generator.writeBoolean( parser.getBooleanValue() );
+    }
+  }
+
+  private void processValueNull() throws IOException {
+    Level child;
+    Level parent = stack.peek();
+    if( parent.isArray() ) {
+      ((ArrayNode)parent.node ).addNull();
+      //dump();
+      if( bufferingLevel == null ) {
+        ((ArrayNode)parent.node ).removeAll();
+      }
+    } else {
+      child = stack.pop();
+      parent = stack.peek();
+      ((ObjectNode)parent.node ).putNull( child.field );
+      //dump();
+      if( bufferingLevel == null ) {
+        ((ObjectNode)parent.node ).remove( child.field );
+      }
+    }
+    if( bufferingLevel == null ) {
+      generator.writeNull();
+    }
+  }
+
+  protected boolean startBuffering( Level node ) {
+    boolean buffered = false;
+    UrlRewriteFilterGroupDescriptor scope = node.scopeConfig;
+    if( scope != null ) {
+      for( UrlRewriteFilterPathDescriptor selector : scope.getSelectors() ) {
+        JsonPath.Expression path = (JsonPath.Expression)selector.compiledPath( JPATH_COMPILER );
+        List<JsonPath.Match> matches = path.evaluate( node.scopeNode );
+        if( matches != null && matches.size() > 0 ) {
+          if( selector instanceof UrlRewriteFilterBufferDescriptor ) {
+            bufferingLevel = node;
+            bufferingConfig = (UrlRewriteFilterBufferDescriptor)selector;
+            buffered = true;
+          }
+          break;
+        }
+      }
+    }
+    return buffered;
+  }
+
+  protected String filterStreamValue( Level node ) {
+    String value;
+    if( node.isArray() ) {
+      value = node.node.get( 0 ).asText();
+    } else {
+      value = node.node.get( node.field ).asText();
+    }
+    String rule = null;
+    UrlRewriteFilterGroupDescriptor scope = node.scopeConfig;
+    //TODO: Scan the top level apply rules for the first match.
+    if( scope != null ) {
+      for( UrlRewriteFilterPathDescriptor selector : scope.getSelectors() ) {
+        JsonPath.Expression path = (JsonPath.Expression)selector.compiledPath( JPATH_COMPILER );
+        List<JsonPath.Match> matches = path.evaluate( node.scopeNode );
+        if( matches != null && matches.size() > 0 ) {
+          JsonPath.Match match = matches.get( 0 );
+          if( match.getNode().isTextual() ) {
+            if( selector instanceof UrlRewriteFilterApplyDescriptor ) {
+              UrlRewriteFilterApplyDescriptor apply = (UrlRewriteFilterApplyDescriptor)selector;
+              rule = apply.rule();
+              break;
+            }
+          }
+        }
+      }
+    }
+    try {
+      value = filterValueString( node.field, value, rule );
+      if( node.isArray() ) {
+        ((ArrayNode)node.node).set( 0, new TextNode( value ) );
+      } else {
+        ((ObjectNode)node.node).put( node.field, value );
+      }
+    } catch( Exception e ) {
+      LOG.failedToFilterValue( value, rule, e );
+    }
+    return value;
+  }
+
+  private void filterBufferedNode( Level node ) {
+    for( UrlRewriteFilterPathDescriptor selector : bufferingConfig.getSelectors() ) {
+      JsonPath.Expression path = (JsonPath.Expression)selector.compiledPath( JPATH_COMPILER );
+      List<JsonPath.Match> matches = path.evaluate( node.node );
+      for( JsonPath.Match match : matches ) {
+        if( selector instanceof UrlRewriteFilterApplyDescriptor ) {
+          if( match.getNode().isTextual() ) {
+            filterBufferedValue( match, (UrlRewriteFilterApplyDescriptor)selector );
+          }
+        } else if( selector instanceof UrlRewriteFilterDetectDescriptor ) {
+          UrlRewriteFilterDetectDescriptor detectConfig = (UrlRewriteFilterDetectDescriptor)selector;
+          JsonPath.Expression detectPath = (JsonPath.Expression)detectConfig.compiledPath( JPATH_COMPILER );
+          List<JsonPath.Match> detectMatches = detectPath.evaluate( node.node );
+          for( JsonPath.Match detectMatch : detectMatches ) {
+            if( detectMatch.getNode().isTextual() ) {
+              String detectValue = detectMatch.getNode().asText();
+              Pattern detectPattern = detectConfig.compiledValue( REGEX_COMPILER );
+              if( detectPattern.matcher( detectValue ).matches() ) {
+                filterBufferedValues( node, detectConfig.getSelectors() );
+              }
+            }
+          }
+        }
+      }
+    }
+  }
+
+  private void filterBufferedValues( Level node, List<UrlRewriteFilterPathDescriptor> selectors ) {
+    for( UrlRewriteFilterPathDescriptor selector : selectors ) {
+      JsonPath.Expression path = (JsonPath.Expression)selector.compiledPath( JPATH_COMPILER );
+      List<JsonPath.Match> matches = path.evaluate( node.node );
+      for( JsonPath.Match match : matches ) {
+        if( match.getNode().isTextual() ) {
+          if( selector instanceof UrlRewriteFilterApplyDescriptor ) {
+            filterBufferedValue( match, (UrlRewriteFilterApplyDescriptor)selector );
+          }
+        }
+      }
+    }
+  }
+
+  private void filterBufferedValue( JsonPath.Match match, UrlRewriteFilterApplyDescriptor apply ) {
+    String field = match.getField();
+    String value = match.getNode().asText();
+    try {
+      value = filterValueString( field, value, apply.rule() );
+      ((ObjectNode)match.getParent().getNode()).put( field, value );
+    } catch( Exception e ) {
+      LOG.failedToFilterValue( value, apply.rule(), e );
+    }
+  }
+
+  protected String filterFieldName( String field ) {
+    return field;
+  }
+
+  protected String filterValueString( String name, String value, String rule ) {
+    return value;
+  }
+
+  @Override
+  public void close() throws IOException {
+    generator.close();
+    writer.close();
+    parser.close();
+    reader.close();
+  }
+
+  private static class Level {
+    String field;
+    JsonNode node;
+    JsonNode scopeNode;
+    UrlRewriteFilterGroupDescriptor scopeConfig;
+    private Level( String field, JsonNode node, JsonNode scopeNode, UrlRewriteFilterGroupDescriptor scopeConfig ) {
+      this.field = field;
+      this.node = node;
+      this.scopeNode = scopeNode;
+      this.scopeConfig = scopeConfig;
+    }
+    public boolean isArray() {
+      return node != null && node.isArray();
+    }
+  }
+
+  private static class JsonPathCompiler implements UrlRewriteFilterPathDescriptor.Compiler<JsonPath.Expression> {
+    @Override
+    public JsonPath.Expression compile( String expression, JsonPath.Expression compiled ) {
+      return JsonPath.compile( expression );
+    }
+  }
+
+  private static class RegexCompiler implements UrlRewriteFilterPathDescriptor.Compiler<Pattern> {
+    @Override
+    public Pattern compile( String expression, Pattern compiled ) {
+      if( compiled != null ) {
+        return compiled;
+      } else {
+        return Pattern.compile( expression );
+      }
+    }
+  }
+
+//  private void dump() throws IOException {
+//    mapper.writeTree( factory.createGenerator( System.out ), stack.get( 0 ).node );
+//    System.out.println();
+//  }
+
+}
+

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonUrlRewriteFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonUrlRewriteFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonUrlRewriteFilterReader.java
new file mode 100644
index 0000000..463987f
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonUrlRewriteFilterReader.java
@@ -0,0 +1,64 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.json;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.net.URISyntaxException;
+
+public class JsonUrlRewriteFilterReader extends JsonFilterReader {
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+
+  private Resolver resolver;
+  private UrlRewriter rewriter;
+  private UrlRewriter.Direction direction;
+
+  public JsonUrlRewriteFilterReader(
+      Reader reader,
+      UrlRewriter rewriter,
+      Resolver resolver,
+      UrlRewriter.Direction direction,
+      UrlRewriteFilterContentDescriptor config )
+          throws IOException {
+    super( reader, config );
+    this.resolver = resolver;
+    this.rewriter = rewriter;
+    this.direction = direction;
+  }
+
+  protected String filterValueString( String name, String value, String rule ) {
+    try {
+      Template input = Parser.parseLiteral( value );
+      Template output = rewriter.rewrite( resolver, input, direction, rule );
+      value = output.getPattern();
+    } catch( URISyntaxException e ) {
+      LOG.failedToParseValueForUrlRewrite( value );
+    }
+    return value;
+  }
+
+}


[24/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterGroupDescriptorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterGroupDescriptorBase.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterGroupDescriptorBase.java
new file mode 100644
index 0000000..bc1dd91
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterGroupDescriptorBase.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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterGroupDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class UrlRewriteFilterGroupDescriptorBase
+    extends UrlRewriteFilterSelectorDescriptorBase
+    implements UrlRewriteFilterGroupDescriptor {
+
+  private List<UrlRewriteFilterPathDescriptor> selectors = new ArrayList<UrlRewriteFilterPathDescriptor>();
+
+  @Override
+  public List<UrlRewriteFilterPathDescriptor> getSelectors() {
+    return selectors;
+  }
+
+  @Override
+  public void addSelector( UrlRewriteFilterPathDescriptor selector ) {
+    this.selectors.add( selector );
+  }
+
+  @Override
+  public UrlRewriteFilterApplyDescriptor addApply( String path, String rule ) {
+    UrlRewriteFilterApplyDescriptor apply = new UrlRewriteFilterApplyDescriptorImpl();
+    apply.path( path );
+    apply.rule( rule );
+    addSelector( apply );
+    return apply;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterReader.java
new file mode 100644
index 0000000..b512a8c
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterReader.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.knox.gateway.filter.rewrite.impl;
+
+import java.util.regex.Pattern;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
+
+
+public interface UrlRewriteFilterReader {
+
+  public String filterValueString( String name, String value, String rule );
+
+  public static class RegexCompiler implements UrlRewriteFilterPathDescriptor.Compiler<Pattern> {
+    @Override
+    public Pattern compile( String expression, Pattern compiled ) {
+      if( compiled != null ) {
+        return compiled;
+      } else {
+        return Pattern.compile( expression );
+      }
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterScopeDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterScopeDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterScopeDescriptorImpl.java
new file mode 100644
index 0000000..bc64870
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterScopeDescriptorImpl.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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterScopeDescriptor;
+
+public class UrlRewriteFilterScopeDescriptorImpl
+    extends UrlRewriteFilterGroupDescriptorBase
+    implements UrlRewriteFilterScopeDescriptor {
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterSelectorDescriptorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterSelectorDescriptorBase.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterSelectorDescriptorBase.java
new file mode 100644
index 0000000..3994128
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterSelectorDescriptorBase.java
@@ -0,0 +1,64 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
+
+public class UrlRewriteFilterSelectorDescriptorBase<T> implements UrlRewriteFilterPathDescriptor<T> {
+
+  private String path;
+  private Object compiledPath;
+
+  @Override
+  public String path() {
+    return path;
+  }
+
+  @Override
+  public T path( String path ) {
+    this.path = path;
+    return (T)this;
+  }
+
+  public void setPath( String path ) {
+    this.path = path;
+  }
+
+  public String getPath()  {
+    return path;
+  }
+
+  @Override
+  public <C> C compiledPath() {
+    return (C)compiledPath;
+  }
+
+  @Override
+  @SuppressWarnings("unchecked")
+  public T compiledPath( Object compiledPath ) {
+    this.compiledPath = compiledPath;
+    return (T)this;
+  }
+
+  @Override
+  public <C> C compiledPath( Compiler<C> compiler ) {
+    compiledPath = compiler.compile( path, (C)compiledPath );
+    return (C)compiledPath;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFunctionProcessorFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFunctionProcessorFactory.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFunctionProcessorFactory.java
new file mode 100644
index 0000000..def7a24
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFunctionProcessorFactory.java
@@ -0,0 +1,113 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptorFactory;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.ServiceLoader;
+
+public abstract class UrlRewriteFunctionProcessorFactory {
+
+  private static final Map<Class<? extends UrlRewriteFunctionDescriptor>,Map<String,Class<? extends UrlRewriteFunctionProcessor>>> MAP
+      = loadProcessors();
+
+  private UrlRewriteFunctionProcessorFactory() {
+  }
+
+  public static UrlRewriteFunctionProcessor create( String name, UrlRewriteFunctionDescriptor descriptor )
+      throws IllegalAccessException, InstantiationException {
+    UrlRewriteFunctionProcessor processor;
+    if( descriptor == null ) {
+      descriptor = UrlRewriteFunctionDescriptorFactory.create( name );
+    }
+    Map<String,Class<? extends UrlRewriteFunctionProcessor>> typeMap;
+    typeMap = MAP.get( descriptor.getClass() );
+    if( typeMap == null ) {
+      Class<? extends UrlRewriteFunctionDescriptor> descriptorInterface = getDescriptorInterface( descriptor );
+      typeMap = MAP.get( descriptorInterface );
+    }
+    if( typeMap == null ) {
+      throw new IllegalArgumentException( descriptor.getClass().getName() );
+    } else {
+      Class<? extends UrlRewriteFunctionProcessor> processorClass = typeMap.get( name );
+      if( processorClass == null ) {
+        throw new IllegalArgumentException( name );
+      } else {
+        processor = processorClass.newInstance();
+      }
+    }
+    return processor;
+  }
+
+  private static Map<Class<? extends UrlRewriteFunctionDescriptor>,Map<String,Class<? extends UrlRewriteFunctionProcessor>>> loadProcessors() {
+    Map<Class<? extends UrlRewriteFunctionDescriptor>,Map<String,Class<? extends UrlRewriteFunctionProcessor>>> descriptorMap
+        = new HashMap<>();
+    ServiceLoader<UrlRewriteFunctionProcessor> processors = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    for( UrlRewriteFunctionProcessor processor : processors ) {
+      Class<? extends UrlRewriteFunctionDescriptor> descriptorInterface = getDescriptorInterface( processor );
+      Map<String,Class<? extends UrlRewriteFunctionProcessor>> typeMap = descriptorMap.get( descriptorInterface );
+      if( typeMap == null ) {
+        typeMap = new HashMap<>();
+        descriptorMap.put( descriptorInterface, typeMap );
+      }
+      String functionName = processor.name();
+      typeMap.put( functionName, processor.getClass() );
+    }
+    return descriptorMap;
+  }
+
+  private static Class<? extends UrlRewriteFunctionDescriptor> getDescriptorInterface(
+      UrlRewriteFunctionDescriptor descriptor ) {
+    Class<? extends UrlRewriteFunctionDescriptor> descriptorClass = null;
+    for( Type interfaceType : descriptor.getClass().getGenericInterfaces() ) {
+      Class genericClass = (Class)interfaceType;
+      if( UrlRewriteFunctionDescriptor.class.isAssignableFrom( genericClass ) ) {
+        descriptorClass = uncheckedDescriptorClassCast( genericClass );
+        break;
+      }
+    }
+    return descriptorClass;
+  }
+
+  private static Class<? extends UrlRewriteFunctionDescriptor> getDescriptorInterface(
+      UrlRewriteFunctionProcessor processor ) {
+    Class<? extends UrlRewriteFunctionDescriptor> descriptorClass = null;
+    Class<? extends UrlRewriteFunctionProcessor> processorClass = processor.getClass();
+    for( Type interfaceType : processorClass.getGenericInterfaces() ) {
+      if( UrlRewriteFunctionProcessor.class.isAssignableFrom(
+          (Class)((ParameterizedType)interfaceType).getRawType() ) ) {
+        ParameterizedType interfaceClass = (ParameterizedType)interfaceType;
+        descriptorClass = uncheckedDescriptorClassCast( interfaceClass.getActualTypeArguments()[ 0 ] );
+        break;
+      }
+    }
+    return descriptorClass;
+  }
+
+  @SuppressWarnings("unchecked")
+  private static Class<? extends UrlRewriteFunctionDescriptor> uncheckedDescriptorClassCast( Type type ) {
+    return (Class<? extends UrlRewriteFunctionDescriptor>)type;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRequest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRequest.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRequest.java
new file mode 100644
index 0000000..f91035c
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRequest.java
@@ -0,0 +1,265 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.AbstractGatewayFilter;
+import org.apache.knox.gateway.filter.GatewayRequestWrapper;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletFilter;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStreamFilterFactory;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.util.MimeTypes;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import javax.activation.MimeType;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletInputStream;
+import javax.servlet.http.HttpServletRequest;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.UnsupportedEncodingException;
+import java.net.URISyntaxException;
+import java.net.URLDecoder;
+import java.util.Arrays;
+import java.util.Enumeration;
+import java.util.List;
+
+import static org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteUtil.pickFirstRuleWithEqualsIgnoreCasePathMatch;
+
+public class UrlRewriteRequest extends GatewayRequestWrapper implements Resolver {
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+  private static final String[] EMPTY_STRING_ARRAY = new String[]{};
+
+  private FilterConfig config;
+  private UrlRewriter rewriter;
+  private String urlRuleName;
+  private String bodyFilterName;
+  private String headersFilterName;
+  private UrlRewriteFilterContentDescriptor headersFilterConfig;
+  private String cookiesFilterName;
+
+  /**
+   * Constructs a request object wrapping the given request.
+   *
+   * @throws IllegalArgumentException if the request is null
+   */
+  public UrlRewriteRequest( FilterConfig config, HttpServletRequest request ) throws IOException {
+    super( request );
+    this.config = config;
+    this.rewriter = UrlRewriteServletContextListener.getUrlRewriter( config.getServletContext() );
+    this.urlRuleName = config.getInitParameter( UrlRewriteServletFilter.REQUEST_URL_RULE_PARAM );
+    this.bodyFilterName = config.getInitParameter( UrlRewriteServletFilter.REQUEST_BODY_FILTER_PARAM );
+    this.headersFilterName = config.getInitParameter( UrlRewriteServletFilter.REQUEST_HEADERS_FILTER_PARAM );
+    this.headersFilterConfig = getRewriteFilterConfig( headersFilterName, UrlRewriteServletFilter.HEADERS_MIME_TYPE );
+    this.cookiesFilterName = config.getInitParameter( UrlRewriteServletFilter.REQUEST_COOKIES_FILTER_PARAM );
+  }
+
+  private Template getSourceUrl() {
+    Template urlTemplate;
+    //KNOX-439[
+    //StringBuffer urlString = super.getRequestURL();
+    StringBuffer urlString = new StringBuffer( 128 );
+    urlString.append( getScheme() );
+    urlString.append( "://" );
+    urlString.append( getServerName() );
+    urlString.append( ":" );
+    urlString.append( getServerPort() );
+    urlString.append( super.getRequestURI() );
+    //]
+    String queryString = super.getQueryString();
+    if( queryString != null ) {
+      urlString.append( '?' );
+      urlString.append( queryString );
+    }
+    try {
+      urlTemplate = Parser.parseLiteral( urlString.toString() );
+    } catch( URISyntaxException e ) {
+      LOG.failedToParseValueForUrlRewrite( urlString.toString() );
+      // Shouldn't be possible given that the URL is constructed from parts of an existing URL.
+      urlTemplate = null;
+    }
+    return urlTemplate;
+  }
+
+  // Note: Source url was added to the request attributes by the GatewayFilter doFilter method.
+  private Template getTargetUrl() {
+    boolean rewriteRequestUrl = true;
+    Template targetUrl;
+    if( rewriteRequestUrl ) {
+      targetUrl = (Template)getAttribute( AbstractGatewayFilter.TARGET_REQUEST_URL_ATTRIBUTE_NAME );
+      if( targetUrl == null ) {
+        Template sourceUrl = getSourceUrl();
+        targetUrl = rewriter.rewrite( this, sourceUrl, UrlRewriter.Direction.IN, urlRuleName );
+        setAttribute( AbstractGatewayFilter.TARGET_REQUEST_URL_ATTRIBUTE_NAME, targetUrl );
+      }
+    } else {
+      targetUrl = (Template)getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_URL_ATTRIBUTE_NAME );
+    }
+    return targetUrl;
+  }
+
+  private String[] splitTargetUrl( Template url ) {
+    if( url == null ) {
+      return EMPTY_STRING_ARRAY;
+    } else {
+      String s = url.toString();
+      return s.split( "\\?" );
+    }
+  }
+
+  @Override
+  public StringBuffer getRequestURL() {
+    return new StringBuffer( getRequestURI() );
+  }
+
+  //TODO: I think this method is implemented wrong based on the HttpServletRequest.getRequestURI docs.
+  // It should not include the scheme or authority parts.
+  @Override
+  public String getRequestURI() {
+    String[] split = splitTargetUrl( getTargetUrl() );
+    if( split.length > 0 ) {
+      return split[0];
+    } else {
+      return "";
+    }
+  }
+
+  @Override
+  public String getQueryString() {
+    String[] split = splitTargetUrl( getTargetUrl() );
+    if( split.length > 1 ) {
+      try {
+        return URLDecoder.decode(split[1], "UTF-8");
+      } catch ( UnsupportedEncodingException e ) {
+        LOG.failedToDecodeQueryString(split[1], e);
+        return split[1];
+      }
+    } else {
+      return null;
+    }
+  }
+
+  private String rewriteValue( UrlRewriter rewriter, String value, String rule ) {
+    try {
+      Template input = Parser.parseLiteral( value );
+      Template output = rewriter.rewrite( this, input, UrlRewriter.Direction.IN, rule );
+      value = output.getPattern();
+    } catch( URISyntaxException e ) {
+      LOG.failedToParseValueForUrlRewrite( value );
+    }
+    return value;
+  }
+
+  @Override
+  public String getHeader( String name ) {
+    String value = super.getHeader( name );
+    if( value != null ) {
+      value = rewriteValue( rewriter, super.getHeader( name ), pickFirstRuleWithEqualsIgnoreCasePathMatch( headersFilterConfig, name ) );
+    }
+    return value;
+  }
+
+  @SuppressWarnings("unchecked")
+  public Enumeration getHeaders( String name ) {
+    return new EnumerationRewriter( rewriter, super.getHeaders( name ), pickFirstRuleWithEqualsIgnoreCasePathMatch( headersFilterConfig, name ) );
+  }
+
+  @Override
+  public List<String> resolve( String name ) {
+    return Arrays.asList( config.getInitParameter( name ) );
+  }
+
+  private class EnumerationRewriter implements Enumeration<String> {
+
+    private UrlRewriter rewriter;
+    private Enumeration<String> delegate;
+    private String rule;
+
+    private EnumerationRewriter( UrlRewriter rewriter, Enumeration<String> delegate, String rule ) {
+      this.rewriter = rewriter;
+      this.delegate = delegate;
+      this.rule = rule;
+    }
+
+    @Override
+    public boolean hasMoreElements() {
+      return delegate.hasMoreElements();
+    }
+
+    @Override
+    public String nextElement() {
+      return rewriteValue( rewriter, delegate.nextElement(), rule );
+    }
+  }
+
+  @Override
+  public ServletInputStream getInputStream() throws IOException {
+    ServletInputStream input = super.getInputStream();
+    if( getContentLength() != 0 ) {
+      MimeType mimeType = getMimeType();
+      UrlRewriteFilterContentDescriptor filterContentConfig = getRewriteFilterConfig( bodyFilterName, mimeType );
+      if (filterContentConfig != null) {
+        String asType = filterContentConfig.asType();
+        if ( asType != null && asType.trim().length() > 0 ) {
+          mimeType = MimeTypes.create(asType, getCharacterEncoding());
+        }
+      }
+      InputStream stream = UrlRewriteStreamFilterFactory.create( mimeType, null, input, rewriter, this, UrlRewriter.Direction.IN, filterContentConfig );
+      input = new UrlRewriteRequestStream( stream );
+    }
+    return input;
+  }
+
+  @Override
+  public BufferedReader getReader() throws IOException {
+    return new BufferedReader( new InputStreamReader( getInputStream(), getCharacterEncoding() ) );
+  }
+
+  @Override
+  public int getContentLength() {
+    // The rewrite might change the content length so return the default of -1 to indicate the length is unknown.
+    int contentLength = super.getContentLength();
+    if( contentLength > 0 ) {
+      contentLength = -1;
+    }
+    return contentLength;
+  }
+
+  private UrlRewriteFilterContentDescriptor getRewriteFilterConfig( String filterName, MimeType mimeType ) {
+    UrlRewriteFilterContentDescriptor filterContentConfig = null;
+    UrlRewriteRulesDescriptor rewriteConfig = rewriter.getConfig();
+    if( rewriteConfig != null ) {
+      UrlRewriteFilterDescriptor filterConfig = rewriteConfig.getFilter( filterName );
+      if( filterConfig != null ) {
+        filterContentConfig = filterConfig.getContent( mimeType );
+      }
+    }
+    return filterContentConfig;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRequestStream.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRequestStream.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRequestStream.java
new file mode 100644
index 0000000..5995317
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRequestStream.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.knox.gateway.filter.rewrite.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.knox.gateway.servlet.SynchronousServletInputStreamAdapter;
+
+//TODO: This needs to be coded much more efficiently!
+public class UrlRewriteRequestStream extends
+    SynchronousServletInputStreamAdapter {
+
+  private InputStream stream;
+
+  public UrlRewriteRequestStream( InputStream stream ) {
+    this.stream = stream;
+  }
+
+  @Override
+  public int read() throws IOException {
+    return stream.read();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteResponse.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteResponse.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteResponse.java
new file mode 100644
index 0000000..d451c26
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteResponse.java
@@ -0,0 +1,331 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.GatewayResponseWrapper;
+import org.apache.knox.gateway.filter.ResponseStreamer;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletFilter;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStreamFilterFactory;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.util.MimeTypes;
+import org.apache.knox.gateway.util.Urls;
+import org.apache.knox.gateway.util.urltemplate.Params;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Template;
+import org.apache.commons.io.IOUtils;
+
+import javax.activation.MimeType;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.URISyntaxException;
+import java.net.UnknownHostException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
+import java.util.zip.ZipException;
+
+import static org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteUtil.getRewriteFilterConfig;
+import static org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteUtil.pickFirstRuleWithEqualsIgnoreCasePathMatch;
+
+/**
+ *
+ */
+public class UrlRewriteResponse extends GatewayResponseWrapper implements Params,
+    ResponseStreamer {
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+
+  // An 8K buffer better matches the underlying buffer sizes.
+  // Testing with 16K made no appreciable difference.
+  private static final int STREAM_BUFFER_SIZE = 8 * 1024;
+
+  private static final Set<String> IGNORE_HEADER_NAMES = new HashSet<>();
+  static {
+    IGNORE_HEADER_NAMES.add( "Content-Length" );
+  }
+
+  private static final String REQUEST_PARAM_PREFIX = "request.";
+  private static final String CLUSTER_PARAM_PREFIX = "cluster.";
+  private static final String GATEWAY_PARAM_PREFIX = "gateway.";
+  public  static final String INBOUND_QUERY_PARAM_PREFIX   = "query.param.";
+
+  private UrlRewriter rewriter;
+  private FilterConfig config;
+  private HttpServletRequest request;
+  private HttpServletResponse response;
+  private ServletOutputStream output;
+  private String bodyFilterName;
+  private String headersFilterName;
+  private UrlRewriteFilterContentDescriptor headersFilterConfig;
+  private String cookiesFilterName;
+  private String xForwardedHostname;
+  private String xForwardedPort;
+  private String xForwardedScheme;
+
+  public UrlRewriteResponse( FilterConfig config, HttpServletRequest request, HttpServletResponse response )
+      throws IOException {
+    super( response );
+    this.rewriter = UrlRewriteServletContextListener.getUrlRewriter( config.getServletContext() );
+    this.config = config;
+    this.request = request;
+    this.response = response;
+    this.output = null;
+    getXForwardedHeaders();
+    this.bodyFilterName = config.getInitParameter( UrlRewriteServletFilter.RESPONSE_BODY_FILTER_PARAM );
+    this.headersFilterName = config.getInitParameter( UrlRewriteServletFilter.RESPONSE_HEADERS_FILTER_PARAM );
+    this.headersFilterConfig = getRewriteFilterConfig( rewriter.getConfig(), headersFilterName, UrlRewriteServletFilter.HEADERS_MIME_TYPE );
+    this.cookiesFilterName = config.getInitParameter( UrlRewriteServletFilter.RESPONSE_COOKIES_FILTER_PARAM );
+  }
+
+  protected boolean ignoreHeader( String name ) {
+    return IGNORE_HEADER_NAMES.contains( name );
+  }
+
+  private String rewriteValue( String value, String rule ) {
+    try {
+      Template input = Parser.parseLiteral( value );
+      Template output = rewriter.rewrite( this, input, UrlRewriter.Direction.OUT, rule );
+      if( output != null ) {
+        value = output.toString();
+      }
+    } catch( URISyntaxException e ) {
+      LOG.failedToParseValueForUrlRewrite( value );
+    }
+    return value;
+  }
+
+  // Ignore the Content-Length from the dispatch respond since the respond body may be rewritten.
+  @Override
+  public void setHeader( String name, String value ) {
+    if( !ignoreHeader( name) ) {
+      value = rewriteValue( value, pickFirstRuleWithEqualsIgnoreCasePathMatch( headersFilterConfig, name ) );
+      super.setHeader( name, value );
+    }
+  }
+
+  // Ignore the Content-Length from the dispatch respond since the respond body may be rewritten.
+  @Override
+  public void addHeader( String name, String value ) {
+    if( !ignoreHeader( name ) ) {
+      String rule = pickFirstRuleWithEqualsIgnoreCasePathMatch( headersFilterConfig, name );
+      value = rewriteValue( value, rule );
+      super.addHeader( name, value );
+    }
+  }
+
+  @Override
+  public OutputStream getRawOutputStream() throws IOException {
+    return response.getOutputStream();
+  }
+
+  @Override
+  public void streamResponse( InputStream input, OutputStream output ) throws IOException {
+    InputStream inStream;
+    OutputStream outStream;
+    boolean isGzip = false;
+    BufferedInputStream inBuffer = new BufferedInputStream(input);
+    try {
+      // Use this way to check whether the input stream is gzip compressed, in case
+      // the content encoding header is unknown, as it could be unset in inbound response
+      inBuffer.mark(STREAM_BUFFER_SIZE);
+      inStream = new GZIPInputStream(inBuffer);
+      isGzip = true;
+    } catch (ZipException e) {
+      inBuffer.reset();
+      inStream = inBuffer;
+    } catch (IOException e) {
+      inBuffer.reset();
+      inStream = inBuffer;
+    }
+
+    MimeType mimeType = getMimeType();
+    UrlRewriteFilterContentDescriptor filterContentConfig =
+        getRewriteFilterConfig( rewriter.getConfig(), bodyFilterName, mimeType );
+    if (filterContentConfig != null) {
+      String asType = filterContentConfig.asType();
+      if ( asType != null && asType.trim().length() > 0 ) {
+        mimeType = MimeTypes.create(asType, getCharacterEncoding());
+      }
+    }
+    InputStream filteredInput = UrlRewriteStreamFilterFactory.create(
+        mimeType, null, inStream, rewriter, this, UrlRewriter.Direction.OUT, filterContentConfig );
+    outStream = (isGzip) ? new GZIPOutputStream(output) : output;
+    IOUtils.copyLarge( filteredInput, outStream, new byte[STREAM_BUFFER_SIZE] );
+    //KNOX-685: outStream.flush();
+    outStream.close();
+  }
+
+  //TODO: Need to buffer the output here and when it is closed, rewrite it and then write the result to the stream.
+  // This should only happen if the caller isn't using the streaming model.
+  @Override
+  public ServletOutputStream getOutputStream() throws IOException {
+    if( output == null ) {
+      output = new UrlRewriteResponseStream( this );
+    }
+    return output;
+  }
+
+  @Override
+  public Set<String> getNames() {
+    return Collections.emptySet();
+  }
+
+  @Override
+  @SuppressWarnings( "unchecked" )
+  public List<String> resolve( String name ) {
+    if( name.startsWith( REQUEST_PARAM_PREFIX ) ) {
+      return Arrays.asList( getRequestParam( name.substring( REQUEST_PARAM_PREFIX.length() ) ) );
+    } else if ( name.startsWith( GATEWAY_PARAM_PREFIX ) ) {
+      return Arrays.asList( getGatewayParam( name.substring( GATEWAY_PARAM_PREFIX.length() ) ) );
+    } else if ( name.startsWith( CLUSTER_PARAM_PREFIX ) ) {
+      return Arrays.asList( getClusterParam( name.substring( GATEWAY_PARAM_PREFIX.length() ) ) );
+    } else if ( name.startsWith( INBOUND_QUERY_PARAM_PREFIX ) ) {
+      return getInboundQueryParam(name.substring(INBOUND_QUERY_PARAM_PREFIX.length()));
+    } else {
+      return Arrays.asList( config.getInitParameter( name ) );
+    }
+  }
+
+  // KNOX-464: Doing this because Jetty only returns the string version of the IP address for request.getLocalName().
+  // Hopefully the local hostname will be cached so this will not be a significant performance hit.
+  // Previously this was an inline request.getServerName() but this ended up mixing the hostname from the Host header
+  // and the local port which was making load balancer configuration difficult if not impossible.
+  private String getRequestLocalHostName() {
+    String hostName = request.getLocalName();
+    try {
+      hostName = InetAddress.getByName( hostName ).getHostName();
+    } catch( UnknownHostException e ) {
+      // Ignore it and use the original hostname.
+    }
+    return hostName;
+  }
+
+  private String getGatewayParam( String name ) {
+    if( "url".equals( name ) ) {
+      if( xForwardedPort == null ) {
+        return xForwardedScheme + "://" + xForwardedHostname + request.getContextPath();
+      } else {
+        return xForwardedScheme + "://" + xForwardedHostname + ":" + xForwardedPort + request.getContextPath();
+      }
+    } else if( "scheme".equals( name ) ) {
+      return xForwardedScheme;
+    } else if( "host".equals( name ) ) {
+      return xForwardedHostname;
+    } else if( "port".equals( name ) ) {
+        return xForwardedPort;
+    } else if( "addr".equals( name ) || "address".equals( name ) ) {
+      if( xForwardedPort == null ) {
+        return xForwardedHostname;
+      } else {
+        return xForwardedHostname + ":" + xForwardedPort;
+      }
+    } else if( "path".equals( name ) ) {
+      return request.getContextPath();
+    } else {
+      return null;
+    }
+  }
+
+  private String getClusterParam( String name ) {
+    if( "name".equals( name ) ) {
+      return config.getServletContext().getServletContextName();
+    } else {
+      return null;
+    }
+  }
+
+  private List <String> getInboundQueryParam(String name ){
+     List <String> inboundHosts = null;
+     if( this.request!=null )
+       inboundHosts =
+         Arrays.asList( this.request.getParameterValues(name));
+     return inboundHosts;
+  }
+
+  private String getRequestParam( String name ) {
+    if( "host".equals( name ) ) {
+      return request.getServerName();
+    } else if ( "port".equals( name ) ) {
+      return Integer.toString( request.getLocalPort() );
+    } else if ( "scheme".equals( name ) ) {
+      return request.getScheme();
+    } else if ( "context-path".equals( name ) ) {
+      return Urls.stripLeadingSlash( request.getContextPath() );
+    } else {
+      config.getServletContext().getServletContextName();
+      return null;
+    }
+  }
+
+  @SuppressWarnings("deprecation")
+  public String encodeUrl( String url ) {
+    return this.encodeURL( url );
+  }
+
+  //TODO: Route these through the rewriter.
+  public String encodeURL( String url ) {
+    throw new UnsupportedOperationException();
+  }
+
+  @SuppressWarnings("deprecation")
+  public String encodeRedirectUrl( String url ) {
+    return this.encodeRedirectURL( url );
+  }
+
+  //TODO: Route these through the rewriter.
+  public String encodeRedirectURL( String url ) {
+    throw new UnsupportedOperationException();
+  }
+
+  private void getXForwardedHeaders() {
+    xForwardedHostname = request.getHeader( "X-Forwarded-Host" );
+    xForwardedPort = request.getHeader( "X-Forwarded-Port" );
+    xForwardedScheme = request.getHeader( "X-Forwarded-Proto" );
+    if ( xForwardedScheme == null ) {
+      xForwardedScheme = request.getScheme();
+    }
+    if ( xForwardedHostname != null ) {
+      int separator = xForwardedHostname.indexOf( ":" );
+      if ( separator > 0 ) {
+        //a specific port in the forwarded host wins
+        xForwardedPort = xForwardedHostname.substring(separator + 1, xForwardedHostname.length());
+        xForwardedHostname = xForwardedHostname.substring( 0, separator );
+      }
+    } else {
+      xForwardedHostname = getRequestLocalHostName();
+      xForwardedPort = Integer.toString( request.getLocalPort() );
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteResponseStream.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteResponseStream.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteResponseStream.java
new file mode 100644
index 0000000..300a8b4
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteResponseStream.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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.GatewayResponse;
+import org.apache.knox.gateway.servlet.SynchronousServletOutputStreamAdapter;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+//TODO: This needs to be coded much more efficiently!
+public class UrlRewriteResponseStream extends
+    SynchronousServletOutputStreamAdapter {
+
+  private static final int DEFAULT_BUFFER_SIZE = 1024;
+
+  private GatewayResponse response;
+  private ByteArrayOutputStream buffer;
+
+  public UrlRewriteResponseStream( GatewayResponse response ) {
+    this.response = response;
+    this.buffer = new ByteArrayOutputStream( DEFAULT_BUFFER_SIZE );
+  }
+
+  @Override
+  public void write( int b ) throws IOException {
+    buffer.write( b );
+  }
+
+  @Override
+  public void close() throws IOException {
+    InputStream stream = new ByteArrayInputStream( buffer.toByteArray() );
+    response.streamResponse( stream ) ;
+    stream.close();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRuleDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRuleDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRuleDescriptorImpl.java
new file mode 100644
index 0000000..d86c670
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRuleDescriptorImpl.java
@@ -0,0 +1,195 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFlowDescriptorBase;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.net.URISyntaxException;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.StringTokenizer;
+
+public class UrlRewriteRuleDescriptorImpl extends UrlRewriteFlowDescriptorBase<UrlRewriteRuleDescriptor>
+    implements UrlRewriteRuleDescriptor {
+
+  private String name;
+  private String scope;
+  private String pattern;
+  private Template template;
+  private EnumSet<UrlRewriter.Direction> directions;
+
+  public UrlRewriteRuleDescriptorImpl() {
+    super( "rule" );
+  }
+
+  @Override
+  public String name() {
+    return this.name;
+  }
+
+  @Override
+  public UrlRewriteRuleDescriptor name( String name ) {
+    this.name = name;
+    return this;
+  }
+
+  public void setName( String name ) {
+    name( name );
+  }
+
+  public String getName() {
+    return name;
+  }
+
+  public String getScope() {
+    return scope;
+  }
+
+  public void setScope(String scope) {
+    scope( scope );
+  }
+
+  @Override
+  public String scope() {
+    return scope;
+  }
+
+  @Override
+  public UrlRewriteStepDescriptor scope( String scope ) {
+    this.scope = scope;
+    return this;
+  }
+
+  @Override
+  public EnumSet<UrlRewriter.Direction> directions() {
+    return directions;
+  }
+
+  @Override
+  public UrlRewriteRuleDescriptor directions( String directions ) {
+    this.directions = parseDirections( directions );
+    return this;
+  }
+
+  public void setDirections( String directions ) {
+    directions( directions );
+  }
+
+  public void setDirection( String directions ) {
+    directions( directions );
+  }
+
+  public void setDir( String directions ) {
+    directions( directions );
+  }
+
+  public String getDir() {
+    String s = null;
+    if( directions != null ) {
+      StringBuilder sb = new StringBuilder();
+      for( UrlRewriter.Direction direction: directions ) {
+        if( sb.length() > 0 ) {
+          sb.append( ',' );
+        }
+        sb.append( direction.toString() );
+      }
+      s = sb.toString();
+    }
+    return s;
+  }
+
+  @Override
+  public UrlRewriteRuleDescriptor directions( UrlRewriter.Direction... directions ) {
+    return this;
+  }
+
+  @Override
+  public String pattern() {
+    return pattern;
+  }
+
+  @Override
+  public UrlRewriteRuleDescriptor pattern( String pattern ) throws URISyntaxException {
+    this.pattern = pattern;
+    this.template = Parser.parseTemplate( pattern );
+    return this;
+  }
+
+  public void setPattern( String pattern ) throws URISyntaxException {
+    pattern( pattern );
+  }
+
+  public void setUrl( String pattern ) throws URISyntaxException {
+    pattern( pattern );
+  }
+
+  public String getPattern() {
+    return pattern();
+  }
+
+  @Override
+  public Template template() {
+    return template;
+  }
+
+  @Override
+  public UrlRewriteRuleDescriptor template( Template template ) {
+    this.template = template;
+    this.pattern = template.toString();
+    return this;
+  }
+
+  private static EnumSet<UrlRewriter.Direction> parseDirections( String directions ) {
+    EnumSet<UrlRewriter.Direction> set = EnumSet.noneOf( UrlRewriter.Direction.class );
+    StringTokenizer parser = new StringTokenizer( directions, " ,;:/|+" );
+    while( parser.hasMoreTokens() ) {
+      UrlRewriter.Direction direction = parseDirection( parser.nextToken() );
+      if( direction != null ) {
+        set.add( direction );
+      }
+    }
+    return set;
+  }
+
+  private static UrlRewriter.Direction parseDirection( String direction ) {
+    direction = direction.trim().toLowerCase();
+    return directionNameMap.get( direction );
+  }
+
+  private static Map<String,UrlRewriter.Direction> directionNameMap = new HashMap<>();
+  static {
+    directionNameMap.put( "inbound", UrlRewriter.Direction.IN );
+    directionNameMap.put( "in", UrlRewriter.Direction.IN );
+    directionNameMap.put( "i", UrlRewriter.Direction.IN );
+    directionNameMap.put( "request", UrlRewriter.Direction.IN );
+    directionNameMap.put( "req", UrlRewriter.Direction.IN );
+
+    directionNameMap.put( "outbound", UrlRewriter.Direction.OUT );
+    directionNameMap.put( "out", UrlRewriter.Direction.OUT );
+    directionNameMap.put( "o", UrlRewriter.Direction.OUT );
+    directionNameMap.put( "response", UrlRewriter.Direction.OUT );
+    directionNameMap.put( "res", UrlRewriter.Direction.OUT );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorHolder.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorHolder.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorHolder.java
new file mode 100644
index 0000000..1c3fb11
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorHolder.java
@@ -0,0 +1,65 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.config.GatewayConfig;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
+import org.apache.knox.gateway.filter.rewrite.ext.ScopedMatcher;
+
+import java.util.List;
+
+public class UrlRewriteRuleProcessorHolder extends UrlRewriteStepProcessorHolder {
+
+  private String ruleName;
+
+  private String scope;
+
+  public void initialize( UrlRewriteEnvironment environment, UrlRewriteRuleDescriptor descriptor ) throws Exception {
+    super.initialize( environment, descriptor );
+    ruleName = descriptor.name();
+    //if a scope is set in the rewrite file, use that
+    if (descriptor.scope() != null) {
+      scope = descriptor.scope();
+    } else {
+      //by convention the name of the rules start with ROLENAME/servicename/direction
+      //use the first part of the name to determine the scope, therefore setting the scope of a rule to
+      //be local to that service
+      int slashIndex = ruleName.indexOf('/');
+      if (slashIndex > 0) {
+        scope = ruleName.substring( 0, slashIndex );
+      }
+      //check config to see if the is an override configuration for a given service to have all its rules set to global
+      GatewayConfig gatewayConfig = environment.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
+      if (gatewayConfig != null) {
+        List<String> globalRulesServices = gatewayConfig.getGlobalRulesServices();
+        if ( globalRulesServices.contains(scope) ) {
+          scope = ScopedMatcher.GLOBAL_SCOPE;
+        }
+      }
+    }
+  }
+
+  public String getRuleName() {
+    return ruleName;
+  }
+
+  public String getScope() {
+    return scope;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorImpl.java
new file mode 100644
index 0000000..e02ad23
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRuleProcessorImpl.java
@@ -0,0 +1,59 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptor;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptorExt;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteMatchProcessorExt;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+
+public class UrlRewriteRuleProcessorImpl implements
+    UrlRewriteStepProcessor<UrlRewriteRuleDescriptor> {
+
+  private UrlRewriteMatchProcessorExt matchProcessor;
+
+  @Override
+  public String getType() {
+    return "rule";
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, UrlRewriteRuleDescriptor descriptor ) throws Exception {
+    UrlRewriteMatchDescriptor matchDescriptor = new UrlRewriteMatchDescriptorExt();
+    matchDescriptor.operation( "matches" );
+    matchDescriptor.flow( descriptor.flow() );
+    matchDescriptor.template( descriptor.template() );
+    matchProcessor = new UrlRewriteMatchProcessorExt();
+    matchProcessor.initialize( environment, matchDescriptor );
+  }
+
+  @Override
+  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
+    return matchProcessor.process( context );
+  }
+
+  @Override
+  public void destroy() {
+    matchProcessor.destroy();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRulesDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRulesDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRulesDescriptorImpl.java
new file mode 100644
index 0000000..86dbc2a
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRulesDescriptorImpl.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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptorFactory;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class UrlRewriteRulesDescriptorImpl implements UrlRewriteRulesDescriptor {
+
+  private Map<String,UrlRewriteFunctionDescriptor> funcMap = new HashMap<>();
+  private List<UrlRewriteFunctionDescriptor> funcList = new ArrayList<UrlRewriteFunctionDescriptor>();
+  private List<UrlRewriteRuleDescriptor> ruleList = new ArrayList<UrlRewriteRuleDescriptor>();
+  private Map<String,UrlRewriteRuleDescriptor> ruleMap = new HashMap<>();
+  private List<UrlRewriteFilterDescriptor> filterList = new ArrayList<UrlRewriteFilterDescriptor>();
+  private Map<String,UrlRewriteFilterDescriptor> filterMap = new HashMap<>();
+
+  @Override
+  public void addRules( UrlRewriteRulesDescriptor rules ) {
+    for( UrlRewriteRuleDescriptor rule : rules.getRules() ) {
+      addRule( rule );
+    }
+    for( UrlRewriteFilterDescriptor filter : rules.getFilters() ) {
+      addFilter( filter  );
+    }
+  }
+
+  @Override
+  public UrlRewriteRuleDescriptor getRule( String name ) {
+    return ruleMap.get( name );
+  }
+
+  @Override
+  public List<UrlRewriteRuleDescriptor> getRules() {
+    return ruleList;
+  }
+
+  @Override
+  public UrlRewriteRuleDescriptor addRule( String name ) {
+    UrlRewriteRuleDescriptor rule = newRule();
+    rule.name( name );
+    addRule( rule );
+    return rule;
+  }
+
+  @Override
+  public UrlRewriteRuleDescriptor newRule() {
+    return new UrlRewriteRuleDescriptorImpl();
+  }
+
+  @Override
+  public void addRule( UrlRewriteRuleDescriptor rule ) {
+    ruleList.add( rule );
+    String name = rule.name();
+    if( name != null && name.length() > 0 ) {
+      ruleMap.put( rule.name(), rule );
+    }
+  }
+
+  @Override
+  public List<UrlRewriteFunctionDescriptor> getFunctions() {
+    return funcList;
+  }
+
+  @Override
+  @SuppressWarnings("unchecked")
+  public <T extends UrlRewriteFunctionDescriptor<?>> T getFunction( String name ) {
+    T descriptor = (T)funcMap.get( name );
+    return (T)descriptor;
+  }
+
+  @Override
+  @SuppressWarnings("unchecked")
+  public <T extends UrlRewriteFunctionDescriptor<?>> T addFunction( String name ) {
+    T descriptor = (T)newFunction( name );
+    addFunction( descriptor );
+    return (T)descriptor;
+  }
+
+  @SuppressWarnings("unchecked")
+  protected <T extends UrlRewriteFunctionDescriptor<?>> T newFunction( String name ) {
+    T descriptor = (T)UrlRewriteFunctionDescriptorFactory.create( name );
+    return (T)descriptor;
+  }
+
+  protected void addFunction( UrlRewriteFunctionDescriptor descriptor ) {
+    funcList.add( descriptor );
+    funcMap.put( descriptor.name(), descriptor );
+  }
+
+
+  @Override
+  public List<UrlRewriteFilterDescriptor> getFilters() {
+    return filterList;
+  }
+
+  @Override
+  public UrlRewriteFilterDescriptor getFilter( String name ) {
+    return filterMap.get( name );
+  }
+
+  @Override
+  public UrlRewriteFilterDescriptor newFilter() {
+    return new UrlRewriteFilterDescriptorImpl();
+  }
+
+  @Override
+  public UrlRewriteFilterDescriptor addFilter( String name ) {
+    UrlRewriteFilterDescriptor filter = newFilter();
+    filter.name( name );
+    addFilter( filter );
+    return filter;
+  }
+
+  @Override
+  public void addFilter( UrlRewriteFilterDescriptor descriptor ) {
+    filterList.add( descriptor );
+    filterMap.put( descriptor.name(), descriptor );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorFactory.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorFactory.java
new file mode 100644
index 0000000..7d88f8b
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorFactory.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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.ServiceLoader;
+
+public abstract class UrlRewriteStepProcessorFactory {
+
+  private static final Map<Class<? extends UrlRewriteStepDescriptor>,Map<String,Class<? extends UrlRewriteStepProcessor>>> MAP
+      = loadStepProcessors();
+
+  private UrlRewriteStepProcessorFactory() {
+  }
+
+  public static UrlRewriteStepProcessor create( UrlRewriteStepDescriptor descriptor ) throws IllegalAccessException, InstantiationException {
+    UrlRewriteStepProcessor processor;
+    Map<String,Class<? extends UrlRewriteStepProcessor>> typeMap;
+    typeMap = MAP.get( descriptor.getClass() );
+    if( typeMap == null ) {
+      Class<? extends UrlRewriteStepDescriptor> descriptorInterface = getDescriptorInterface( descriptor );
+      typeMap = MAP.get( descriptorInterface );
+    }
+    if( typeMap == null ) {
+      throw new IllegalArgumentException( descriptor.getClass().getName() );
+    } else {
+      String type = descriptor.type();
+      Class<? extends UrlRewriteStepProcessor> processorClass = typeMap.get( type );
+      if( processorClass == null ) {
+        throw new IllegalArgumentException( type );
+      } else {
+        processor = processorClass.newInstance();
+      }
+    }
+    return processor;
+  }
+
+  private static Map<Class<? extends UrlRewriteStepDescriptor>,Map<String,Class<? extends UrlRewriteStepProcessor>>> loadStepProcessors() {
+    Map<Class<? extends UrlRewriteStepDescriptor>,Map<String,Class<? extends UrlRewriteStepProcessor>>> descriptorMap
+        = new HashMap<>();
+    ServiceLoader<UrlRewriteStepProcessor> processors = ServiceLoader.load( UrlRewriteStepProcessor.class );
+    for( UrlRewriteStepProcessor processor : processors ) {
+      Class<? extends UrlRewriteStepDescriptor> descriptorInterface = getDescriptorInterface( processor );
+      Map<String,Class<? extends UrlRewriteStepProcessor>> typeMap = descriptorMap.get( descriptorInterface );
+      if( typeMap == null ) {
+        typeMap = new HashMap<>();
+        descriptorMap.put( descriptorInterface, typeMap );
+      }
+      String processorType = processor.getType();
+      typeMap.put( processorType, processor.getClass() );
+    }
+    return descriptorMap;
+  }
+
+  private static Class<? extends UrlRewriteStepDescriptor> getDescriptorInterface( UrlRewriteStepDescriptor descriptor ) {
+    Class<? extends UrlRewriteStepDescriptor> descriptorClass = null;
+    for( Type interfaceType : descriptor.getClass().getGenericInterfaces() ) {
+      Class genericClass = (Class)interfaceType;
+      if( UrlRewriteStepDescriptor.class.isAssignableFrom( genericClass ) ) {
+        descriptorClass = uncheckedStepDescriptorClassCast( genericClass );
+        break;
+      }
+    }
+    return descriptorClass;
+  }
+
+  private static Class<? extends UrlRewriteStepDescriptor> getDescriptorInterface( UrlRewriteStepProcessor processor ) {
+    Class<? extends UrlRewriteStepDescriptor> descriptorClass = null;
+    Class<? extends UrlRewriteStepProcessor> processorClass = processor.getClass();
+    for( Type interfaceType : processorClass.getGenericInterfaces() ) {
+      if( UrlRewriteStepProcessor.class.isAssignableFrom( (Class)((ParameterizedType)interfaceType).getRawType() ) ) {
+        ParameterizedType interfaceClass = (ParameterizedType)interfaceType;
+        descriptorClass = uncheckedStepDescriptorClassCast( interfaceClass.getActualTypeArguments()[ 0 ] );
+        break;
+      }
+    }
+    return descriptorClass;
+  }
+
+  @SuppressWarnings("unchecked")
+  private static Class<? extends UrlRewriteStepDescriptor> uncheckedStepDescriptorClassCast( Type type ) {
+    return (Class<? extends UrlRewriteStepDescriptor>)type;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorHolder.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorHolder.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorHolder.java
new file mode 100644
index 0000000..1d4811c
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorHolder.java
@@ -0,0 +1,233 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFlowDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepFlow;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+public class UrlRewriteStepProcessorHolder implements UrlRewriteStepProcessor {
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+
+  private boolean isCondition;
+  private UrlRewriteStepDescriptor descriptor;
+  private UrlRewriteStepProcessor processor;
+  private List<UrlRewriteStepProcessorHolder> childProcessors;
+
+  @Override
+  public String getType() {
+    return "system";
+  }
+
+  public boolean isCondition() {
+    return isCondition;
+  }
+
+  public boolean isAction() {
+    return !isCondition;
+  }
+
+  @Override
+  @SuppressWarnings( "unchecked" )
+  public void initialize( UrlRewriteEnvironment environment, UrlRewriteStepDescriptor descriptor ) throws Exception {
+    UrlRewriteStepProcessor processor = UrlRewriteStepProcessorFactory.create( descriptor );
+    processor.initialize( environment, descriptor );
+    initialize( environment, descriptor, processor );
+  }
+
+  // For unit testing.
+  @SuppressWarnings("unchecked")
+  void initialize( UrlRewriteEnvironment environment, UrlRewriteStepDescriptor descriptor, UrlRewriteStepProcessor processor ) throws Exception {
+    this.descriptor = descriptor;
+    this.processor = processor;
+    this.isCondition = descriptor instanceof UrlRewriteFlowDescriptor;
+    this.childProcessors = new ArrayList<UrlRewriteStepProcessorHolder>();
+    if( isCondition ) {
+      UrlRewriteFlowDescriptor flowDescriptor = (UrlRewriteFlowDescriptor)descriptor;
+      List<UrlRewriteStepDescriptor> stepList = flowDescriptor.steps();
+      if( stepList != null && !stepList.isEmpty() ) {
+        Iterator<UrlRewriteStepDescriptor> stepIterator = stepList.iterator();
+        while( stepIterator.hasNext() ) {
+          UrlRewriteStepDescriptor stepDescriptor = stepIterator.next();
+          UrlRewriteStepProcessorHolder stepProcessor = new UrlRewriteStepProcessorHolder();
+          stepProcessor.initialize( environment, stepDescriptor );
+          childProcessors.add( stepProcessor );
+        }
+      }
+    }
+  }
+
+  // For unit testing.
+  UrlRewriteStepDescriptor getDescriptor() {
+    return descriptor;
+  }
+
+  // For unit testing.
+  UrlRewriteStepProcessor getProcessor() {
+    return processor;
+  }
+
+  @Override
+  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
+    UrlRewriteStepStatus status = UrlRewriteStepStatus.SUCCESS;
+    // If initialization failed then fail processing
+    if( processor != null ) {
+      status = processor.process( context );
+      if( UrlRewriteStepStatus.SUCCESS == status &&
+          descriptor instanceof UrlRewriteFlowDescriptor &&
+          !childProcessors.isEmpty() ) {
+        UrlRewriteFlowDescriptor flowDescriptor = (UrlRewriteFlowDescriptor)descriptor;
+        UrlRewriteStepFlow flow = flowDescriptor.flow();
+        if( flow == null ) {
+          flow = UrlRewriteStepFlow.AND;
+        }
+        switch( flow ) {
+          case ALL:
+            return processAllFlow( context );
+          case AND:
+            return processAndFlow( context );
+          case OR:
+            return processOrFlow( context );
+        }
+      }
+    }
+    return status;
+  }
+
+  private UrlRewriteStepStatus processAllFlow( UrlRewriteContext context ) throws Exception {
+    UrlRewriteStepProcessorState state = new UrlRewriteStepProcessorState( childProcessors.iterator() );
+    UrlRewriteStepStatus stepStatus = UrlRewriteStepStatus.SUCCESS;
+    UrlRewriteStepProcessorHolder step;
+    while( state.hasNext() ) {
+      while( state.hasNextCondition() ) {
+        step = state.nextCondition( stepStatus );
+        stepStatus = step.process( context );
+        if( stepStatus == UrlRewriteStepStatus.FINISHED ) {
+          return stepStatus;
+        }
+      }
+      stepStatus = processActions( context, state );
+      if( stepStatus == UrlRewriteStepStatus.FINISHED ) {
+        return stepStatus;
+      }
+    }
+    return UrlRewriteStepStatus.SUCCESS;
+  }
+
+  // All conditions proceeding a set of one or more actions must succeed for the actions to be executed.
+  private UrlRewriteStepStatus processAndFlow( UrlRewriteContext context ) throws Exception {
+    UrlRewriteStepProcessorState state = new UrlRewriteStepProcessorState( childProcessors.iterator() );
+    UrlRewriteStepStatus stepStatus = UrlRewriteStepStatus.SUCCESS;
+    UrlRewriteStepProcessorHolder step;
+    while( state.hasNext() ) {
+      while( state.hasNextCondition() ) {
+        step = state.nextCondition( stepStatus );
+        stepStatus = step.process( context );
+        if( !( stepStatus == UrlRewriteStepStatus.SUCCESS ) ) {
+          return stepStatus;
+        }
+      }
+      stepStatus = processActions( context, state );
+      if( !( stepStatus == UrlRewriteStepStatus.SUCCESS ) ) {
+        return stepStatus;
+      }
+    }
+    return UrlRewriteStepStatus.SUCCESS;
+  }
+
+  // At least one condition proceeding a set of one or more actions must succedd for the actions to be executed.
+  private UrlRewriteStepStatus processOrFlow( UrlRewriteContext context ) throws Exception {
+    UrlRewriteStepProcessorState state = new UrlRewriteStepProcessorState( childProcessors.iterator() );
+    UrlRewriteStepStatus status = UrlRewriteStepStatus.SUCCESS;
+    UrlRewriteStepProcessorHolder step;
+    while( state.hasNext() ) {
+      UrlRewriteStepStatus flowStatus = UrlRewriteStepStatus.FAILURE;
+      while( state.hasNextCondition() ) {
+        step = state.nextCondition( status );
+        if( flowStatus == UrlRewriteStepStatus.FAILURE ) {
+          status = step.process( context );
+          switch( status ) {
+            case SUCCESS:
+              flowStatus = UrlRewriteStepStatus.SUCCESS;
+              continue;
+            case FINISHED:
+              return status;
+          }
+        }
+      }
+      status = processActions( context, state );
+      if( status != UrlRewriteStepStatus.SUCCESS ) {
+        return status;
+      }
+    }
+    return UrlRewriteStepStatus.SUCCESS;
+  }
+
+  private UrlRewriteStepStatus processActions( UrlRewriteContext context, UrlRewriteStepProcessorState state )
+      throws Exception {
+    UrlRewriteStepStatus flowStatus = UrlRewriteStepStatus.SUCCESS;
+    while( state.hasNextAction() ) {
+      if( flowStatus == UrlRewriteStepStatus.SUCCESS ) {
+        UrlRewriteStepStatus stepStatus = UrlRewriteStepStatus.SUCCESS;
+        UrlRewriteStepProcessorHolder step = state.nextAction( stepStatus );
+        stepStatus = step.process( context );
+        switch( stepStatus ) {
+          case FAILURE:
+            flowStatus = UrlRewriteStepStatus.FAILURE;
+            continue;
+          case FINISHED:
+            return stepStatus;
+        }
+      }
+    }
+    return flowStatus;
+  }
+
+  @Override
+  public void destroy() throws Exception {
+    destroy( processor );
+    if( descriptor instanceof UrlRewriteFlowDescriptor ) {
+      for( UrlRewriteStepProcessorHolder childProcessor : childProcessors ) {
+        destroy( childProcessor );
+      }
+    }
+  }
+
+  public void destroy( UrlRewriteStepProcessor processor ) {
+    if( processor != null ) {
+      try {
+        processor.destroy();
+      } catch( Exception e ) {
+        // Maybe it makes sense to throw exception
+        LOG.failedToDestroyRewriteStepProcessor( e );
+      }
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorState.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorState.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorState.java
new file mode 100644
index 0000000..dead19d
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorState.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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+
+import java.util.Iterator;
+
+class UrlRewriteStepProcessorState {
+
+  private UrlRewriteStepStatus status;
+  private UrlRewriteStepProcessorHolder next;
+  private Iterator<UrlRewriteStepProcessorHolder> steps;
+
+  UrlRewriteStepProcessorState( Iterator<UrlRewriteStepProcessorHolder> steps ) {
+    this.status = UrlRewriteStepStatus.SUCCESS;
+    this.next = null;
+    this.steps = steps;
+  }
+
+  private UrlRewriteStepProcessorHolder peek() {
+    if( next == null && steps.hasNext() ) {
+      next = steps.next();
+      return next;
+    } else if ( next != null ) {
+      return next;
+    } else {
+      return null;
+    }
+  }
+
+  public boolean hasNextCondition() {
+    UrlRewriteStepProcessorHolder curr = peek();
+    return curr != null && curr.isCondition();
+  }
+
+  public boolean hasNextAction() {
+    UrlRewriteStepProcessorHolder curr = peek();
+    return curr != null && curr.isAction();
+  }
+
+  private UrlRewriteStepProcessorHolder take( UrlRewriteStepStatus lastStatus ) {
+    UrlRewriteStepProcessorHolder step = peek();
+    status = lastStatus;
+    next = null;
+    return step;
+  }
+
+  public UrlRewriteStepProcessorHolder nextCondition( UrlRewriteStepStatus lastStatus ){
+    if( hasNextCondition() ) {
+      return take( lastStatus );
+    } else {
+      return null;
+    }
+  }
+
+  public UrlRewriteStepProcessorHolder nextAction( UrlRewriteStepStatus lastStatus ){
+    if( hasNextAction() ) {
+      return take( lastStatus );
+    } else {
+      return null;
+    }
+  }
+
+  public UrlRewriteStepStatus status(){
+    return status;
+  }
+
+  public boolean hasNext() {
+      return next != null || steps.hasNext();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteUtil.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteUtil.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteUtil.java
new file mode 100644
index 0000000..4e68d27
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteUtil.java
@@ -0,0 +1,92 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+
+import javax.activation.MimeType;
+
+public class UrlRewriteUtil {
+
+  public static String pickFirstRuleWithEqualsIgnoreCasePathMatch( UrlRewriteFilterContentDescriptor config, String name ) {
+    String rule = "*";
+    if( config != null && !config.getSelectors().isEmpty() && name != null ) {
+      rule = "";
+      for( UrlRewriteFilterPathDescriptor selector : config.getSelectors() ) {
+        if( name.equalsIgnoreCase( selector.path() ) ) {
+          if( selector instanceof UrlRewriteFilterApplyDescriptor) {
+            rule = ((UrlRewriteFilterApplyDescriptor)selector).rule();
+          }
+          break;
+        }
+      }
+    }
+    return rule;
+  }
+
+  public static UrlRewriteFilterContentDescriptor getRewriteFilterConfig(
+      UrlRewriteRulesDescriptor config, String filterName, MimeType mimeType ) {
+    UrlRewriteFilterContentDescriptor filterContentConfig = null;
+    if( config != null ) {
+      UrlRewriteFilterDescriptor filterConfig = config.getFilter( filterName );
+      if( filterConfig != null ) {
+        filterContentConfig = filterConfig.getContent( mimeType );
+      }
+    }
+    return filterContentConfig;
+  }
+
+  public static String filterJavaScript( String inputValue, UrlRewriteFilterContentDescriptor config,
+      UrlRewriteFilterReader filterReader, UrlRewriteFilterPathDescriptor.Compiler<Pattern> regexCompiler ) {
+    StringBuffer tbuff = new StringBuffer();
+    StringBuffer sbuff = new StringBuffer();
+    sbuff.append( inputValue );
+    if( config != null && !config.getSelectors().isEmpty() ) {
+      for( UrlRewriteFilterPathDescriptor selector : config.getSelectors() ) {
+        if ( selector instanceof UrlRewriteFilterApplyDescriptor ) {
+          UrlRewriteFilterApplyDescriptor apply = (UrlRewriteFilterApplyDescriptor)selector;
+          Matcher matcher = apply.compiledPath( regexCompiler ).matcher( sbuff );
+          int index = 0;
+          while ( matcher.find() ) {
+            int start = matcher.start();
+            int end = matcher.end();
+            if ( start != -1 && end != -1 ) {
+              tbuff.append( sbuff, index, start );
+              String value = matcher.group();
+              value = filterReader.filterValueString( null, value, apply.rule() );
+              tbuff.append(value);
+              index = end;
+            }
+          }
+          tbuff.append( sbuff, index, sbuff.length() );
+          sbuff.setLength( 0 );
+          sbuff.append( tbuff );
+          tbuff.setLength( 0 );
+        }
+      }
+    }
+    return sbuff.toString();
+  }
+}


[36/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServicePortFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServicePortFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServicePortFunctionDescriptor.java
new file mode 100644
index 0000000..fa359e8
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServicePortFunctionDescriptor.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.knox.gateway.svcregfunc.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+public class ServicePortFunctionDescriptor implements
+    UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
+
+  public static final String FUNCTION_NAME = "servicePort";
+
+  @Override
+  public String name() {
+    return FUNCTION_NAME;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptor.java
new file mode 100644
index 0000000..7bb20aa
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptor.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.knox.gateway.svcregfunc.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+public class ServiceSchemeFunctionDescriptor implements
+    UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
+
+  public static final String FUNCTION_NAME = "serviceScheme";
+
+  @Override
+  public String name() {
+    return FUNCTION_NAME;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceUrlFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceUrlFunctionDescriptor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceUrlFunctionDescriptor.java
new file mode 100644
index 0000000..fa51283
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/api/ServiceUrlFunctionDescriptor.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.knox.gateway.svcregfunc.api;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+public class ServiceUrlFunctionDescriptor implements
+    UrlRewriteFunctionDescriptor<ServiceUrlFunctionDescriptor> {
+
+  public static final String FUNCTION_NAME = "serviceUrl";
+
+  @Override
+  public String name() {
+    return FUNCTION_NAME;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceAddressFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceAddressFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceAddressFunctionProcessor.java
new file mode 100644
index 0000000..cf925bb
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceAddressFunctionProcessor.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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.svcregfunc.api.ServiceAddressFunctionDescriptor;
+import org.apache.knox.gateway.util.urltemplate.Host;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Port;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ServiceAddressFunctionProcessor
+    extends ServiceRegistryFunctionProcessorBase<ServiceAddressFunctionDescriptor>
+    implements UrlRewriteFunctionProcessor<ServiceAddressFunctionDescriptor> {
+
+  @Override
+  public String name() {
+    return ServiceAddressFunctionDescriptor.FUNCTION_NAME;
+  }
+
+  @Override
+  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
+    List<String> results = null;
+    if( parameters != null ) {
+      UrlRewriter.Direction direction = context.getDirection();
+      results = new ArrayList<String>( parameters.size() );
+      for( String parameter : parameters ) {
+        parameter = resolve( parameter );
+        results.add( parameter );
+      }
+    }
+    return results;
+  }
+
+  public String resolve( String parameter ) throws Exception {
+    String addr = parameter;
+    String url = lookupServiceUrl( parameter );
+    if( url != null ) {
+      Template template = Parser.parseLiteral( url );
+      Host host = template.getHost();
+      String hostStr = null;
+      if( host != null ) {
+        hostStr = host.getFirstValue().getPattern();
+      }
+
+      Port port = template.getPort();
+      String portStr = null;
+      if( port != null ) {
+        portStr = port.getFirstValue().getPattern();
+      }
+
+      if( hostStr != null && portStr != null ) {
+        addr = hostStr + ":" + portStr;
+      } else if( host != null && port == null ) {
+        addr = hostStr;
+      } else if( host == null && port != null ) {
+        addr = ":" + portStr;
+      }
+    }
+    return addr;
+  }
+
+}
+

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceHostFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceHostFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceHostFunctionProcessor.java
new file mode 100644
index 0000000..1276bc3
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceHostFunctionProcessor.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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.svcregfunc.api.ServiceHostFunctionDescriptor;
+import org.apache.knox.gateway.util.urltemplate.Host;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ServiceHostFunctionProcessor
+    extends ServiceRegistryFunctionProcessorBase<ServiceHostFunctionDescriptor>
+    implements UrlRewriteFunctionProcessor<ServiceHostFunctionDescriptor> {
+
+  @Override
+  public String name() {
+    return ServiceHostFunctionDescriptor.FUNCTION_NAME;
+  }
+
+  @Override
+  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
+    List<String> results = null;
+    if( parameters != null ) {
+      results = new ArrayList<String>( parameters.size() );
+      for( String parameter : parameters ) {
+        String url = lookupServiceUrl( parameter );
+        if( url != null ) {
+          Template template = Parser.parseLiteral( url );
+          Host host = template.getHost();
+          if( host != null ) {
+            parameter = host.getFirstValue().getPattern();
+          }
+        }
+        results.add( parameter );
+      }
+    }
+    return results;
+  }
+
+}
+

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessor.java
new file mode 100644
index 0000000..c8f530c
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessor.java
@@ -0,0 +1,109 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.hostmap.HostMapper;
+import org.apache.knox.gateway.services.hostmap.HostMapperService;
+import org.apache.knox.gateway.svcregfunc.api.ServiceMappedAddressFunctionDescriptor;
+import org.apache.knox.gateway.util.urltemplate.Host;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Port;
+import org.apache.knox.gateway.util.urltemplate.Template;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ServiceMappedAddressFunctionProcessor
+    extends ServiceRegistryFunctionProcessorBase<ServiceMappedAddressFunctionDescriptor>
+    implements UrlRewriteFunctionProcessor<ServiceMappedAddressFunctionDescriptor> {
+
+  private HostMapper hostmap = null;
+
+  @Override
+  public String name() {
+    return ServiceMappedAddressFunctionDescriptor.FUNCTION_NAME;
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, ServiceMappedAddressFunctionDescriptor descriptor ) throws Exception {
+    super.initialize( environment, descriptor );
+    HostMapperService hostmapService = services().getService( GatewayServices.HOST_MAPPING_SERVICE );
+    if( hostmapService != null ) {
+      hostmap = hostmapService.getHostMapper( cluster() );
+    }
+  }
+
+  @Override
+  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
+    List<String> results = null;
+    if( parameters != null ) {
+      UrlRewriter.Direction direction = context.getDirection();
+      results = new ArrayList<String>( parameters.size() );
+      for( String parameter : parameters ) {
+        parameter = resolve( direction, parameter );
+        results.add( parameter );
+      }
+    }
+    return results;
+  }
+
+  public String resolve( UrlRewriter.Direction direction, String parameter ) throws Exception {
+    String addr = parameter;
+    String url = lookupServiceUrl( parameter );
+    if( url != null ) {
+      Template template = Parser.parseLiteral( url );
+      Host host = template.getHost();
+      String hostStr = null;
+      if( host != null ) {
+        hostStr = host.getFirstValue().getPattern();
+        if( hostmap != null ) {
+          switch( direction ) {
+            case IN:
+              hostStr = hostmap.resolveInboundHostName( hostStr );
+              break;
+            case OUT:
+              hostStr = hostmap.resolveOutboundHostName( hostStr );
+              break;
+          }
+        }
+      }
+
+      Port port = template.getPort();
+      String portStr = null;
+      if( port != null ) {
+        portStr = port.getFirstValue().getPattern();
+      }
+
+      if( hostStr != null && portStr != null ) {
+        addr = hostStr + ":" + portStr;
+      } else if( host != null && port == null ) {
+        addr = hostStr;
+      } else if( host == null && port != null ) {
+        addr = ":" + portStr;
+      }
+    }
+    return addr;
+  }
+
+}
+

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessor.java
new file mode 100644
index 0000000..39c162c
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessor.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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.hostmap.HostMapper;
+import org.apache.knox.gateway.services.hostmap.HostMapperService;
+import org.apache.knox.gateway.svcregfunc.api.ServiceMappedHostFunctionDescriptor;
+import org.apache.knox.gateway.util.urltemplate.Host;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Template;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ServiceMappedHostFunctionProcessor
+    extends ServiceRegistryFunctionProcessorBase<ServiceMappedHostFunctionDescriptor>
+    implements UrlRewriteFunctionProcessor<ServiceMappedHostFunctionDescriptor> {
+
+  private HostMapper hostmap;
+
+  @Override
+  public String name() {
+    return ServiceMappedHostFunctionDescriptor.FUNCTION_NAME;
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, ServiceMappedHostFunctionDescriptor descriptor ) throws Exception {
+    super.initialize( environment, descriptor );
+    HostMapperService hostmapService = services().getService( GatewayServices.HOST_MAPPING_SERVICE );
+    if( hostmapService != null ) {
+      hostmap = hostmapService.getHostMapper( cluster() );
+    }
+  }
+
+  @Override
+  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
+    List<String> results = null;
+    if( parameters != null ) {
+      results = new ArrayList<String>( parameters.size() );
+      for( String parameter : parameters ) {
+        String url = lookupServiceUrl( parameter );
+        if( url != null ) {
+          Template template = Parser.parseLiteral( url );
+          Host host = template.getHost();
+          if( host != null ) {
+            String hostStr = host.getFirstValue().getPattern();
+            if( hostmap != null ) {
+              switch( context.getDirection() ) {
+                case UrlRewriter.Direction.IN:
+                  parameter = hostmap.resolveInboundHostName( hostStr );
+                  break;
+                case UrlRewriter.Direction.OUT:
+                  parameter = hostmap.resolveOutboundHostName( hostStr );
+                  break;
+              }
+            } else {
+              parameter = hostStr;
+            }
+          }
+        }
+        results.add( parameter );
+      }
+    }
+    return results;
+  }
+
+}
+

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessor.java
new file mode 100644
index 0000000..9a11823
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessor.java
@@ -0,0 +1,90 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.hostmap.HostMapper;
+import org.apache.knox.gateway.services.hostmap.HostMapperService;
+import org.apache.knox.gateway.svcregfunc.api.ServiceMappedUrlFunctionDescriptor;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+
+public class ServiceMappedUrlFunctionProcessor
+    extends ServiceRegistryFunctionProcessorBase<ServiceMappedUrlFunctionDescriptor>
+    implements UrlRewriteFunctionProcessor<ServiceMappedUrlFunctionDescriptor> {
+
+  private HostMapper hostmap;
+
+  @Override
+  public String name() {
+    return ServiceMappedUrlFunctionDescriptor.FUNCTION_NAME;
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, ServiceMappedUrlFunctionDescriptor descriptor ) throws Exception {
+    super.initialize( environment, descriptor );
+    HostMapperService hostmapService = services().getService( GatewayServices.HOST_MAPPING_SERVICE );
+    if( hostmapService != null ) {
+      hostmap = hostmapService.getHostMapper( cluster() );
+    }
+  }
+
+  @Override
+  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
+    List<String> results = null;
+    if( parameters != null ) {
+      UrlRewriter.Direction direction = context.getDirection();
+      results = new ArrayList<String>( parameters.size() );
+      for( String parameter : parameters ) {
+        parameter = resolve( direction, parameter );
+        results.add( parameter );
+      }
+    }
+    return results;
+  }
+
+  public String resolve( UrlRewriter.Direction direction, String parameter ) throws Exception {
+    String url = lookupServiceUrl( parameter );
+    if( url != null ) {
+      URI outputUri;
+      URI inputUri = new URI( url );
+      String host = inputUri.getHost();
+      if( host != null && hostmap != null ) {
+        switch( direction ) {
+          case IN:
+            host = hostmap.resolveInboundHostName( host );
+            break;
+          case OUT:
+            host = hostmap.resolveOutboundHostName( host );
+            break;
+        }
+      }
+      outputUri = new URI( inputUri.getScheme(), inputUri.getUserInfo(), host, inputUri.getPort(), inputUri.getPath(), inputUri.getQuery(), inputUri.getFragment() );
+      parameter = outputUri.toString();
+    }
+    return parameter;
+  }
+
+}
+

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServicePathFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServicePathFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServicePathFunctionProcessor.java
new file mode 100644
index 0000000..5c613ce
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServicePathFunctionProcessor.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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.svcregfunc.api.ServicePathFunctionDescriptor;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Path;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ServicePathFunctionProcessor
+    extends ServiceRegistryFunctionProcessorBase<ServicePathFunctionDescriptor>
+    implements UrlRewriteFunctionProcessor<ServicePathFunctionDescriptor> {
+
+  @Override
+  public String name() {
+    return ServicePathFunctionDescriptor.FUNCTION_NAME;
+  }
+
+  @Override
+  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
+    List<String> results = null;
+    if( parameters != null ) {
+      results = new ArrayList<String>( parameters.size() );
+      for( String parameter : parameters ) {
+        String url = lookupServiceUrl( parameter );
+        if( url != null ) {
+          Template template = Parser.parseLiteral( url );
+          List<Path> path = template.getPath();
+          if( path != null ) {
+            parameter = toString( path );
+          }
+        }
+        results.add( parameter );
+      }
+    }
+    return results;
+  }
+
+  private String toString( List<Path> paths ) {
+    StringBuilder s = new StringBuilder();
+    for( Path path: paths ) {
+      s.append( '/' );
+      s.append( path.getFirstValue().getPattern() );
+    }
+    if( s.length() == 0 ) {
+      s.append( '/' );
+    }
+    return s.toString();
+  }
+
+}
+

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServicePortFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServicePortFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServicePortFunctionProcessor.java
new file mode 100644
index 0000000..dc28403
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServicePortFunctionProcessor.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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.svcregfunc.api.ServicePortFunctionDescriptor;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Port;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ServicePortFunctionProcessor
+    extends ServiceRegistryFunctionProcessorBase<ServicePortFunctionDescriptor>
+    implements UrlRewriteFunctionProcessor<ServicePortFunctionDescriptor> {
+
+  @Override
+  public String name() {
+    return ServicePortFunctionDescriptor.FUNCTION_NAME;
+  }
+
+  @Override
+  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
+    List<String> results = null;
+    if( parameters != null ) {
+      results = new ArrayList<String>( parameters.size() );
+      for( String parameter : parameters ) {
+        String url = lookupServiceUrl( parameter );
+        if( url != null ) {
+          Template template = Parser.parseLiteral( url );
+          Port port = template.getPort();
+          if( port != null ) {
+            parameter = port.getFirstValue().getPattern();
+          }
+        }
+        results.add( parameter );
+      }
+    }
+    return results;
+  }
+
+}
+

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionProcessorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionProcessorBase.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionProcessorBase.java
new file mode 100644
index 0000000..953f994
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionProcessorBase.java
@@ -0,0 +1,81 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.ha.provider.HaProvider;
+import org.apache.knox.gateway.ha.provider.HaServletContextListener;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+
+abstract class ServiceRegistryFunctionProcessorBase<T extends UrlRewriteFunctionDescriptor> implements UrlRewriteFunctionProcessor<T> {
+
+  private String cluster;
+  private GatewayServices services;
+  private ServiceRegistry registry;
+  private HaProvider haProvider;
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, T descriptor ) throws Exception {
+    if( environment == null ) {
+      throw new IllegalArgumentException( "environment==null" );
+    }
+    cluster = environment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE );
+    if( cluster == null ) {
+      throw new IllegalArgumentException( "cluster==null" );
+    }
+    services = environment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE );
+    if( services == null ) {
+      throw new IllegalArgumentException( "services==null" );
+    }
+    registry = services.getService( GatewayServices.SERVICE_REGISTRY_SERVICE );
+    if( registry == null ) {
+      throw new IllegalArgumentException( "registry==null" );
+    }
+    haProvider = environment.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME);
+  }
+
+  @Override
+  public void destroy() throws Exception {
+    registry = null;
+    cluster = null;
+  }
+
+  public String lookupServiceUrl( String role ) throws Exception {
+    if (haProvider != null && haProvider.isHaEnabled(role)) {
+       return haProvider.getActiveURL(role);
+    }
+    return registry.lookupServiceURL( cluster, role );
+  }
+
+  String cluster() {
+    return cluster;
+  }
+
+  GatewayServices services() {
+    return services;
+  }
+
+  ServiceRegistry registry() {
+    return registry;
+  }
+
+}
+

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessor.java
new file mode 100644
index 0000000..643d2bb
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessor.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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.svcregfunc.api.ServiceSchemeFunctionDescriptor;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Scheme;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ServiceSchemeFunctionProcessor
+    extends ServiceRegistryFunctionProcessorBase<ServiceSchemeFunctionDescriptor>
+    implements UrlRewriteFunctionProcessor<ServiceSchemeFunctionDescriptor> {
+
+  @Override
+  public String name() {
+    return ServiceSchemeFunctionDescriptor.FUNCTION_NAME;
+  }
+
+  @Override
+  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
+    List<String> results = null;
+    if( parameters != null ) {
+      results = new ArrayList<String>( parameters.size() );
+      for( String parameter : parameters ) {
+        String url = lookupServiceUrl( parameter );
+        if( url != null && !url.equals( parameter ) ) {
+          Template template = Parser.parseLiteral( url );
+          Scheme scheme = template.getScheme();
+          if( scheme != null ) {
+            parameter = scheme.getFirstValue().getPattern();
+          }
+        }
+        results.add( parameter );
+      }
+    }
+    return results;
+  }
+
+}
+

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceUrlFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceUrlFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceUrlFunctionProcessor.java
new file mode 100644
index 0000000..1573d48
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceUrlFunctionProcessor.java
@@ -0,0 +1,64 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.svcregfunc.api.ServiceUrlFunctionDescriptor;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+
+public class ServiceUrlFunctionProcessor
+    extends ServiceRegistryFunctionProcessorBase<ServiceUrlFunctionDescriptor>
+    implements UrlRewriteFunctionProcessor<ServiceUrlFunctionDescriptor> {
+
+  @Override
+  public String name() {
+    return ServiceUrlFunctionDescriptor.FUNCTION_NAME;
+  }
+
+  @Override
+  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
+    List<String> results = null;
+    if( parameters != null ) {
+      UrlRewriter.Direction direction = context.getDirection();
+      results = new ArrayList<String>( parameters.size() );
+      for( String parameter : parameters ) {
+        parameter = resolve( parameter );
+        results.add( parameter );
+      }
+    }
+    return results;
+  }
+
+  private String resolve( String parameter ) throws Exception {
+     String url = lookupServiceUrl( parameter );
+     if( url != null ) {
+        URI outputUri;
+        URI inputUri = new URI( url );
+        String host = inputUri.getHost();
+        outputUri = new URI( inputUri.getScheme(), inputUri.getUserInfo(), host, inputUri.getPort(), inputUri.getPath(), inputUri.getQuery(), inputUri.getFragment() );
+        parameter = outputUri.toString();
+     }
+     return parameter;
+  }
+}
+

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor b/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
deleted file mode 100644
index 17adf92..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
+++ /dev/null
@@ -1,27 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.svcregfunc.api.ServiceUrlFunctionDescriptor
-org.apache.hadoop.gateway.svcregfunc.api.ServiceAddressFunctionDescriptor
-org.apache.hadoop.gateway.svcregfunc.api.ServiceSchemeFunctionDescriptor
-org.apache.hadoop.gateway.svcregfunc.api.ServiceHostFunctionDescriptor
-org.apache.hadoop.gateway.svcregfunc.api.ServicePortFunctionDescriptor
-org.apache.hadoop.gateway.svcregfunc.api.ServicePathFunctionDescriptor
-org.apache.hadoop.gateway.svcregfunc.api.ServiceMappedUrlFunctionDescriptor
-org.apache.hadoop.gateway.svcregfunc.api.ServiceMappedAddressFunctionDescriptor
-org.apache.hadoop.gateway.svcregfunc.api.ServiceMappedHostFunctionDescriptor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor b/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
deleted file mode 100644
index 498d286..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
+++ /dev/null
@@ -1,27 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.svcregfunc.impl.ServiceUrlFunctionProcessor
-org.apache.hadoop.gateway.svcregfunc.impl.ServiceAddressFunctionProcessor
-org.apache.hadoop.gateway.svcregfunc.impl.ServiceSchemeFunctionProcessor
-org.apache.hadoop.gateway.svcregfunc.impl.ServiceHostFunctionProcessor
-org.apache.hadoop.gateway.svcregfunc.impl.ServicePortFunctionProcessor
-org.apache.hadoop.gateway.svcregfunc.impl.ServicePathFunctionProcessor
-org.apache.hadoop.gateway.svcregfunc.impl.ServiceMappedUrlFunctionProcessor
-org.apache.hadoop.gateway.svcregfunc.impl.ServiceMappedAddressFunctionProcessor
-org.apache.hadoop.gateway.svcregfunc.impl.ServiceMappedHostFunctionProcessor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor b/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
new file mode 100644
index 0000000..c459e89
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
@@ -0,0 +1,27 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.svcregfunc.api.ServiceUrlFunctionDescriptor
+org.apache.knox.gateway.svcregfunc.api.ServiceAddressFunctionDescriptor
+org.apache.knox.gateway.svcregfunc.api.ServiceSchemeFunctionDescriptor
+org.apache.knox.gateway.svcregfunc.api.ServiceHostFunctionDescriptor
+org.apache.knox.gateway.svcregfunc.api.ServicePortFunctionDescriptor
+org.apache.knox.gateway.svcregfunc.api.ServicePathFunctionDescriptor
+org.apache.knox.gateway.svcregfunc.api.ServiceMappedUrlFunctionDescriptor
+org.apache.knox.gateway.svcregfunc.api.ServiceMappedAddressFunctionDescriptor
+org.apache.knox.gateway.svcregfunc.api.ServiceMappedHostFunctionDescriptor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor b/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
new file mode 100644
index 0000000..0a50aed
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
@@ -0,0 +1,27 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.svcregfunc.impl.ServiceUrlFunctionProcessor
+org.apache.knox.gateway.svcregfunc.impl.ServiceAddressFunctionProcessor
+org.apache.knox.gateway.svcregfunc.impl.ServiceSchemeFunctionProcessor
+org.apache.knox.gateway.svcregfunc.impl.ServiceHostFunctionProcessor
+org.apache.knox.gateway.svcregfunc.impl.ServicePortFunctionProcessor
+org.apache.knox.gateway.svcregfunc.impl.ServicePathFunctionProcessor
+org.apache.knox.gateway.svcregfunc.impl.ServiceMappedUrlFunctionProcessor
+org.apache.knox.gateway.svcregfunc.impl.ServiceMappedAddressFunctionProcessor
+org.apache.knox.gateway.svcregfunc.impl.ServiceMappedHostFunctionProcessor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceAddressFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceAddressFunctionDescriptorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceAddressFunctionDescriptorTest.java
deleted file mode 100644
index c4f9a39..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceAddressFunctionDescriptorTest.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.hadoop.gateway.svcregfunc.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class ServiceAddressFunctionDescriptorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ServiceAddressFunctionDescriptor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ServiceAddressFunctionDescriptor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    ServiceAddressFunctionDescriptor descriptor = new ServiceAddressFunctionDescriptor();
-    assertThat( descriptor.name(), is( "serviceAddr" ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceHostFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceHostFunctionDescriptorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceHostFunctionDescriptorTest.java
deleted file mode 100644
index c52b6e4..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceHostFunctionDescriptorTest.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.hadoop.gateway.svcregfunc.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class ServiceHostFunctionDescriptorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ServiceHostFunctionDescriptor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ServiceHostFunctionDescriptor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    ServiceHostFunctionDescriptor descriptor = new ServiceHostFunctionDescriptor();
-    assertThat( descriptor.name(), is( "serviceHost" ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePathFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePathFunctionDescriptorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePathFunctionDescriptorTest.java
deleted file mode 100644
index a3729a1..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePathFunctionDescriptorTest.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.hadoop.gateway.svcregfunc.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class ServicePathFunctionDescriptorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ServicePathFunctionDescriptor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ServicePathFunctionDescriptor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    ServicePathFunctionDescriptor descriptor = new ServicePathFunctionDescriptor();
-    assertThat( descriptor.name(), is( "servicePath" ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePortFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePortFunctionDescriptorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePortFunctionDescriptorTest.java
deleted file mode 100644
index b95b8d4..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServicePortFunctionDescriptorTest.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.hadoop.gateway.svcregfunc.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class ServicePortFunctionDescriptorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ServicePortFunctionDescriptor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ServicePortFunctionDescriptor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    ServicePortFunctionDescriptor descriptor = new ServicePortFunctionDescriptor();
-    assertThat( descriptor.name(), is( "servicePort" ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptorTest.java
deleted file mode 100644
index e47a96e..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceSchemeFunctionDescriptorTest.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.hadoop.gateway.svcregfunc.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class ServiceSchemeFunctionDescriptorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ServiceSchemeFunctionDescriptor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ServiceSchemeFunctionDescriptor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    ServiceSchemeFunctionDescriptor descriptor = new ServiceSchemeFunctionDescriptor();
-    assertThat( descriptor.name(), is( "serviceScheme" ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceUrlFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceUrlFunctionDescriptorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceUrlFunctionDescriptorTest.java
deleted file mode 100644
index 631a9f1..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/api/ServiceUrlFunctionDescriptorTest.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.hadoop.gateway.svcregfunc.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class ServiceUrlFunctionDescriptorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ServiceUrlFunctionDescriptor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ServiceUrlFunctionDescriptor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    ServiceUrlFunctionDescriptor descriptor = new ServiceUrlFunctionDescriptor();
-    assertThat( descriptor.name(), is( "serviceUrl" ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceAddressFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceAddressFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceAddressFunctionProcessorTest.java
deleted file mode 100644
index 5465907..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceAddressFunctionProcessorTest.java
+++ /dev/null
@@ -1,140 +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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.ha.provider.HaProvider;
-import org.apache.hadoop.gateway.ha.provider.HaServletContextListener;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-import org.apache.hadoop.gateway.svcregfunc.api.ServiceAddressFunctionDescriptor;
-import org.easymock.EasyMock;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
-import static org.junit.Assert.fail;
-
-public class ServiceAddressFunctionProcessorTest {
-
-  ServiceRegistry reg;
-  GatewayServices svc;
-  UrlRewriteEnvironment env;
-  UrlRewriteContext ctx;
-  ServiceAddressFunctionDescriptor desc;
-
-  @Before
-  public void setUp() {
-    reg = EasyMock.createNiceMock( ServiceRegistry.class );
-    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
-
-    svc = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
-
-    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
-
-    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
-
-    desc = EasyMock.createNiceMock( ServiceAddressFunctionDescriptor.class );
-
-    HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
-
-    EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
-
-    EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
-
-    EasyMock.replay( reg, svc, env, desc, ctx, haProvider );
-  }
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ServiceAddressFunctionProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ServiceAddressFunctionProcessor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    ServiceAddressFunctionProcessor func = new ServiceAddressFunctionProcessor();
-    assertThat( func.name(), is( "serviceAddr" ) );
-  }
-
-  @Test
-  public void testInitialize() throws Exception {
-    ServiceAddressFunctionProcessor func = new ServiceAddressFunctionProcessor();
-    try {
-      func.initialize( null, desc );
-      fail( "Should have thrown an IllegalArgumentException" );
-    } catch( IllegalArgumentException e ) {
-      assertThat( e.getMessage(), containsString( "environment" ) );
-    }
-
-    func = new ServiceAddressFunctionProcessor();
-    try {
-      func.initialize( env, null );
-    } catch( Exception e ) {
-      e.printStackTrace();
-      fail( "Should not have thrown an exception" );
-    }
-
-    func.initialize( env, desc );
-
-    assertThat( func.cluster(), is( "test-cluster" ) );
-    assertThat( func.registry(), sameInstance( reg ) );
-  }
-
-  @Test
-  public void testDestroy() throws Exception {
-    ServiceAddressFunctionProcessor func = new ServiceAddressFunctionProcessor();
-    func.initialize( env, desc );
-    func.destroy();
-
-    assertThat( func.cluster(), nullValue() );
-    assertThat( func.registry(), nullValue() );
-  }
-
-  @Test
-  public void testResolve() throws Exception {
-    ServiceAddressFunctionProcessor func = new ServiceAddressFunctionProcessor();
-    func.initialize( env, desc );
-
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-host:777" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
-    assertThat( func.resolve( ctx, null ), nullValue() );
-
-    func.destroy();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceHostFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceHostFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceHostFunctionProcessorTest.java
deleted file mode 100644
index 5c2db7f..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/hadoop/gateway/svcregfunc/impl/ServiceHostFunctionProcessorTest.java
+++ /dev/null
@@ -1,141 +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.hadoop.gateway.svcregfunc.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.ha.provider.HaProvider;
-import org.apache.hadoop.gateway.ha.provider.HaServletContextListener;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-import org.apache.hadoop.gateway.svcregfunc.api.ServiceHostFunctionDescriptor;
-import org.easymock.EasyMock;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
-import static org.junit.Assert.fail;
-
-public class ServiceHostFunctionProcessorTest {
-
-  ServiceRegistry reg;
-  GatewayServices svc;
-  UrlRewriteEnvironment env;
-  UrlRewriteContext ctx;
-  ServiceHostFunctionDescriptor desc;
-
-  @Before
-  public void setUp() {
-    reg = EasyMock.createNiceMock( ServiceRegistry.class );
-    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
-
-    svc = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
-
-    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
-    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
-
-    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
-
-    desc = EasyMock.createNiceMock( ServiceHostFunctionDescriptor.class );
-
-     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
-
-     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
-
-     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
-
-     EasyMock.replay( reg, svc, env, desc, ctx, haProvider );
-
-  }
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ServiceHostFunctionProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ServiceHostFunctionProcessor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    ServiceHostFunctionProcessor func = new ServiceHostFunctionProcessor();
-    assertThat( func.name(), is( "serviceHost" ) );
-  }
-
-  @Test
-  public void testInitialize() throws Exception {
-    ServiceHostFunctionProcessor func = new ServiceHostFunctionProcessor();
-    try {
-      func.initialize( null, desc );
-      fail( "Should have thrown an IllegalArgumentException" );
-    } catch( IllegalArgumentException e ) {
-      assertThat( e.getMessage(), containsString( "environment" ) );
-    }
-
-    func = new ServiceHostFunctionProcessor();
-    try {
-      func.initialize( env, null );
-    } catch( Exception e ) {
-      e.printStackTrace();
-      fail( "Should not have thrown an exception" );
-    }
-
-    func.initialize( env, desc );
-
-    assertThat( func.cluster(), is( "test-cluster" ) );
-    assertThat( func.registry(), sameInstance( reg ) );
-  }
-
-  @Test
-  public void testDestroy() throws Exception {
-    ServiceHostFunctionProcessor func = new ServiceHostFunctionProcessor();
-    func.initialize( env, desc );
-    func.destroy();
-
-    assertThat( func.cluster(), nullValue() );
-    assertThat( func.registry(), nullValue() );
-  }
-
-  @Test
-  public void testResolve() throws Exception {
-    ServiceHostFunctionProcessor func = new ServiceHostFunctionProcessor();
-    func.initialize( env, desc );
-
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-host" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
-    assertThat( func.resolve( ctx, null ), nullValue() );
-
-    func.destroy();
-  }
-
-}


[30/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessor.java
deleted file mode 100644
index c0a5639..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessor.java
+++ /dev/null
@@ -1,182 +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.hadoop.gateway.filter.rewrite.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.ext.ScopedMatcher;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteContextImpl;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteFunctionProcessorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteRuleProcessorHolder;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteStepProcessorHolder;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.util.urltemplate.Matcher;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import static org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter.Direction.IN;
-import static org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter.Direction.OUT;
-
-public class UrlRewriteProcessor implements UrlRewriter {
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-
-  UrlRewriteEnvironment environment;
-  UrlRewriteRulesDescriptor descriptor;
-  Map<String,UrlRewriteRuleProcessorHolder> rules = new HashMap<>();
-  ScopedMatcher inbound = new ScopedMatcher();
-  ScopedMatcher outbound = new ScopedMatcher();
-  Map<String,UrlRewriteFunctionProcessor> functions = new HashMap<>();
-
-  public UrlRewriteProcessor() {
-  }
-
-  // Convert the descriptor into processors.
-  public void initialize( UrlRewriteEnvironment environment, UrlRewriteRulesDescriptor descriptor ) {
-    this.environment = environment;
-    this.descriptor = descriptor;
-    initializeFunctions( descriptor );
-    initializeRules( descriptor );
-  }
-
-  public UrlRewriteRulesDescriptor getConfig() {
-    return descriptor;
-  }
-
-  @SuppressWarnings("unchecked")
-  private void initializeFunctions( UrlRewriteRulesDescriptor rules ) {
-    for( String name : UrlRewriteFunctionDescriptorFactory.getNames() ) {
-      try {
-        UrlRewriteFunctionDescriptor descriptor = rules.getFunction( name );
-        UrlRewriteFunctionProcessor processor = UrlRewriteFunctionProcessorFactory.create( name, descriptor );
-        processor.initialize( environment, descriptor );
-        functions.put( name, processor );
-      } catch( Exception e ) {
-        // Ignore it and it won't be available as a function.
-        LOG.failedToInitializeRewriteFunctions( e );
-      }
-    }
-  }
-
-  private void initializeRules( UrlRewriteRulesDescriptor descriptor ) {
-    for( UrlRewriteRuleDescriptor ruleDescriptor : descriptor.getRules() ) {
-      try {
-        UrlRewriteRuleProcessorHolder ruleProcessor = new UrlRewriteRuleProcessorHolder();
-        ruleProcessor.initialize( environment, ruleDescriptor );
-        if( !rules.containsKey( ruleDescriptor.name() ) ) {
-          rules.put( ruleDescriptor.name(), ruleProcessor );
-        }
-        Template template = ruleDescriptor.template();
-        if( template != null ) {
-          EnumSet<Direction> directions = ruleDescriptor.directions();
-          if( directions == null || directions.isEmpty() ) {
-            inbound.add( template, ruleProcessor );
-            outbound.add( template, ruleProcessor );
-          } else if( directions.contains( IN ) ) {
-            inbound.add( template, ruleProcessor );
-          } else if ( directions.contains( OUT ) ) {
-            outbound.add( template, ruleProcessor );
-          }
-        }
-      } catch( Exception e ) {
-        LOG.failedToInitializeRewriteRules( e );
-      }
-    }
-  }
-
-  public void destroy() {
-    for( UrlRewriteStepProcessorHolder rule : rules.values() ) {
-      try {
-        rule.destroy();
-      } catch ( Exception e ) {
-        LOG.failedToDestroyRewriteStepProcessor( e );
-      }
-    }
-    for( UrlRewriteFunctionProcessor function : functions.values() ) {
-      try {
-        function.destroy();
-      } catch( Exception e ) {
-        LOG.failedToDestroyRewriteFunctionProcessor( e );
-      }
-    }
-  }
-
-  @Override
-  public Template rewrite( Resolver resolver, Template inputUri, Direction direction, String ruleName ) {
-    Template outputUri = inputUri;
-    String serviceRole = null;
-    if (resolver != null) {
-      List<String> serviceRoles = resolver.resolve("service.role");
-      if ( serviceRoles != null && !serviceRoles.isEmpty() ) {
-        serviceRole = serviceRoles.get(0);
-      }
-    }
-    UrlRewriteStepProcessorHolder stepHolder = null;
-    String effectiveRuleName = null;
-    if( ruleName == null || "*".equals( ruleName ) ) {
-      ruleName = null; // Used for logging later.
-      Matcher<UrlRewriteRuleProcessorHolder>.Match match = null;
-      switch( direction ) {
-        case IN:
-          match = inbound.match( outputUri, serviceRole );
-          break;
-        case OUT:
-          match = outbound.match( outputUri, serviceRole );
-          break;
-      }
-      if( match != null ) {
-        stepHolder = match.getValue();
-        effectiveRuleName = match.getValue().getRuleName();
-      }
-    } else if( !ruleName.isEmpty() ) {
-      stepHolder = rules.get( ruleName );
-      effectiveRuleName = ruleName;
-    }
-    if( stepHolder != null ) {
-      UrlRewriteContext context = new UrlRewriteContextImpl( environment, resolver, functions, direction, inputUri );
-      try {
-        UrlRewriteStepStatus stepStatus = stepHolder.process( context );
-        if( UrlRewriteStepStatus.SUCCESS == stepStatus ) {
-          outputUri = context.getCurrentUrl();
-          if( ruleName == null ) {
-            LOG.rewroteUrlViaImplicitRule( inputUri, direction, effectiveRuleName, outputUri );
-          } else {
-            LOG.rewroteUrlViaExplicitRule( inputUri, direction, effectiveRuleName, outputUri );
-          }
-        } else {
-          LOG.failedToRewriteUrl( inputUri, direction, effectiveRuleName, stepStatus );
-          outputUri = null;
-        }
-      } catch( Exception e ) {
-        LOG.failedToRewriteUrlDueToException( inputUri, direction, effectiveRuleName, e );
-        outputUri = null;
-      }
-    } else {
-      LOG.noRuleMatchingUrl( inputUri, direction );
-    }
-    return outputUri;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRuleDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRuleDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRuleDescriptor.java
deleted file mode 100644
index 86d0585..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRuleDescriptor.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.hadoop.gateway.filter.rewrite.api;
-
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.net.URISyntaxException;
-import java.util.EnumSet;
-
-/**
- *  <rule name="..." pattern="..." dir="request" flow="and"><match></match></rule>
- */
-public interface UrlRewriteRuleDescriptor extends UrlRewriteFlowDescriptor<UrlRewriteRuleDescriptor> {
-
-  String name();
-
-  UrlRewriteStepDescriptor name( String name );
-
-  String scope();
-
-  UrlRewriteStepDescriptor scope( String scope );
-
-  EnumSet<UrlRewriter.Direction> directions();
-
-  UrlRewriteRuleDescriptor directions( String directions );
-
-  UrlRewriteRuleDescriptor directions( UrlRewriter.Direction... directions );
-
-  String pattern();
-
-  UrlRewriteRuleDescriptor pattern( String pattern ) throws URISyntaxException;
-
-  Template template();
-
-  UrlRewriteRuleDescriptor template( Template pattern );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptor.java
deleted file mode 100644
index 461a272..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptor.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.hadoop.gateway.filter.rewrite.api;
-
-import java.util.List;
-
-/**
- * <rules><rule></rule></rules>
- */
-public interface UrlRewriteRulesDescriptor {
-
-  void addRules( UrlRewriteRulesDescriptor rules );
-
-  List<UrlRewriteFunctionDescriptor> getFunctions();
-
-  <T extends UrlRewriteFunctionDescriptor<?>> T getFunction( String name );
-
-  <T extends UrlRewriteFunctionDescriptor<?>> T addFunction( String name );
-
-
-  List<UrlRewriteRuleDescriptor> getRules();
-
-  UrlRewriteRuleDescriptor getRule( String name );
-
-  UrlRewriteRuleDescriptor newRule();
-
-  UrlRewriteRuleDescriptor addRule( String name );
-
-  void addRule( UrlRewriteRuleDescriptor rule );
-
-
-  List<UrlRewriteFilterDescriptor> getFilters();
-
-  UrlRewriteFilterDescriptor getFilter( String name );
-
-  UrlRewriteFilterDescriptor newFilter();
-
-  UrlRewriteFilterDescriptor addFilter( String name );
-
-  void addFilter( UrlRewriteFilterDescriptor filter );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactory.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactory.java
deleted file mode 100644
index 08a94b4..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactory.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.hadoop.gateway.filter.rewrite.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteResources;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteRulesDescriptorImpl;
-import org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlUrlRewriteRulesExporter;
-import org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlUrlRewriteRulesImporter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteRulesExporter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteRulesImporter;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.i18n.resources.ResourcesFactory;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.Writer;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-public abstract class UrlRewriteRulesDescriptorFactory {
-
-  private static UrlRewriteResources RES = ResourcesFactory.get( UrlRewriteResources.class );
-
-  private static Map<String, UrlRewriteRulesImporter> IMPORTERS = loadImporters();
-  private static Map<String, UrlRewriteRulesExporter> EXPORTERS = loadExporters();
-
-  private UrlRewriteRulesDescriptorFactory() {
-  }
-
-  public static UrlRewriteRulesDescriptor create() {
-    return new UrlRewriteRulesDescriptorImpl();
-  }
-
-  public static UrlRewriteRulesDescriptor load( String format, Reader reader ) throws IOException {
-    UrlRewriteRulesImporter importer = IMPORTERS.get( format );
-    if( importer == null ) {
-      throw new IllegalArgumentException( RES.noImporterForFormat( format ) );
-    }
-    return importer.load( reader );
-  }
-
-  public static void store( UrlRewriteRulesDescriptor descriptor, String format, Writer writer ) throws IOException {
-    UrlRewriteRulesExporter exporter = EXPORTERS.get( format );
-    if( exporter == null ) {
-      throw new IllegalArgumentException( RES.noExporterForFormat( format ) );
-    }
-    exporter.store( descriptor, writer );
-  }
-
-  private static Map<String, UrlRewriteRulesImporter> loadImporters() {
-    Map<String, UrlRewriteRulesImporter> map = new ConcurrentHashMap<String, UrlRewriteRulesImporter>();
-    map.put( "xml", new XmlUrlRewriteRulesImporter() );
-    return map;
-  }
-
-  private static Map<String, UrlRewriteRulesExporter> loadExporters() {
-    Map<String, UrlRewriteRulesExporter> map = new ConcurrentHashMap<String, UrlRewriteRulesExporter>();
-    map.put( "xml", new XmlUrlRewriteRulesExporter() );
-    return map;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletContextListener.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletContextListener.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletContextListener.java
deleted file mode 100644
index d673845..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletContextListener.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.hadoop.gateway.filter.rewrite.api;
-
-import javax.servlet.ServletContext;
-import javax.servlet.ServletContextEvent;
-import javax.servlet.ServletContextListener;
-
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.net.MalformedURLException;
-import java.net.URL;
-
-public class UrlRewriteServletContextListener implements ServletContextListener {
-
-  public static final String PROCESSOR_ATTRIBUTE_NAME = UrlRewriteProcessor.class.getName();
-  public static final String DESCRIPTOR_LOCATION_INIT_PARAM_NAME = "rewriteDescriptorLocation";
-  public static final String DESCRIPTOR_DEFAULT_FILE_NAME = "rewrite.xml";
-  public static final String DESCRIPTOR_DEFAULT_LOCATION = "/WEB-INF/" + DESCRIPTOR_DEFAULT_FILE_NAME;
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-
-  @Override
-  public void contextInitialized( ServletContextEvent event ) {
-    UrlRewriteRulesDescriptor descriptor = null;
-    try {
-      URL url = locateDescriptor( event.getServletContext() );
-      descriptor = loadDescriptor( url );
-    } catch( IOException e ) {
-      throw new IllegalStateException( e );
-    }
-    ServletContext context = event.getServletContext();
-    UrlRewriteEnvironment environment = new UrlRewriteServletEnvironment( context );
-    UrlRewriteProcessor processor = new UrlRewriteProcessor();
-    processor.initialize( environment, descriptor );
-    event.getServletContext().setAttribute( PROCESSOR_ATTRIBUTE_NAME, processor );
-  }
-
-  @Override
-  public void contextDestroyed( ServletContextEvent event ) {
-    UrlRewriteProcessor processor =
-        (UrlRewriteProcessor)event.getServletContext().getAttribute( PROCESSOR_ATTRIBUTE_NAME );
-    event.getServletContext().removeAttribute( PROCESSOR_ATTRIBUTE_NAME );
-    if( processor != null ) {
-      processor.destroy();
-    }
-  }
-
-  public static UrlRewriter getUrlRewriter( ServletContext context ) {
-    return ((UrlRewriteProcessor)context.getAttribute( PROCESSOR_ATTRIBUTE_NAME ));
-  }
-
-  private static URL locateDescriptor( ServletContext context ) throws IOException {
-    String param = context.getInitParameter( DESCRIPTOR_LOCATION_INIT_PARAM_NAME );
-    if( param == null ) {
-      param = DESCRIPTOR_DEFAULT_LOCATION;
-    }
-    URL url;
-    try {
-      url = context.getResource( param );
-    } catch( MalformedURLException e ) {
-      // Ignore it and try using the value directly as a URL.
-      url = null;
-    }
-    if( url == null ) {
-      url = new URL( param );
-    }
-    if( url == null ) {
-      throw new FileNotFoundException( param );
-    }
-    return url;
-  }
-
-  private static UrlRewriteRulesDescriptor loadDescriptor( URL url ) throws IOException {
-    InputStream stream = url.openStream();
-    Reader reader = new InputStreamReader( stream, "UTF-8" );
-    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.load( "xml", reader );
-    try {
-      reader.close();
-    } catch( IOException closeException ) {
-      LOG.failedToLoadRewriteRulesDescriptor( closeException );
-    }
-    return descriptor;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletEnvironment.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletEnvironment.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletEnvironment.java
deleted file mode 100644
index a5c38ec..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletEnvironment.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.hadoop.gateway.filter.rewrite.api;
-
-import javax.servlet.ServletContext;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.Arrays;
-import java.util.List;
-
-public class UrlRewriteServletEnvironment implements UrlRewriteEnvironment {
-
-  private ServletContext context;
-
-  public UrlRewriteServletEnvironment( ServletContext context ) {
-    this.context = context;
-  }
-
-  @Override
-  public URL getResource( String name ) throws MalformedURLException {
-    URL url = context.getResource( name );
-    return url;
-  }
-
-  @Override
-  public <T> T getAttribute( String name ) {
-    T attribute = (T)context.getAttribute( name );
-    return attribute;
-  }
-
-  @Override
-  public List<String> resolve( String name ) {
-    List<String> values = null;
-    String value = context.getInitParameter( name );
-    if( value != null ) {
-      values = Arrays.asList( value );
-    }
-    return values;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletFilter.java
deleted file mode 100644
index 74ac67a..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletFilter.java
+++ /dev/null
@@ -1,63 +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.hadoop.gateway.filter.rewrite.api;
-
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteRequest;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteResponse;
-import org.apache.hadoop.gateway.util.MimeTypes;
-
-import javax.activation.MimeType;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-
-/**
- *
- */
-public class UrlRewriteServletFilter extends AbstractGatewayFilter {
-
-  public static final String REQUEST_URL_RULE_PARAM = "request.url";
-  public static final String REQUEST_HEADERS_FILTER_PARAM = "request.headers";
-  public static final String REQUEST_COOKIES_FILTER_PARAM = "request.cookies";
-  public static final String REQUEST_BODY_FILTER_PARAM = "request.body";
-  public static final String RESPONSE_HEADERS_FILTER_PARAM = "response.headers";
-  public static final String RESPONSE_COOKIES_FILTER_PARAM = "response.cookies";
-  public static final String RESPONSE_BODY_FILTER_PARAM = "response.body";
-
-  public static final MimeType HEADERS_MIME_TYPE = MimeTypes.create( "application/x-http-headers", null );
-  public static final MimeType COOKIES_MIME_TYPE = MimeTypes.create( "application/x-http-cookies", null );
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-    super.init( filterConfig );
-  }
-
-  @Override
-  protected void doFilter( HttpServletRequest request, HttpServletResponse response, FilterChain chain )
-      throws IOException, ServletException {
-    FilterConfig config = getConfig();
-    UrlRewriteRequest rewriteRequest = new UrlRewriteRequest( config, request );
-    UrlRewriteResponse rewriteResponse = new UrlRewriteResponse( config, rewriteRequest, response );
-    chain.doFilter( rewriteRequest, rewriteResponse );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStepDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStepDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStepDescriptor.java
deleted file mode 100644
index 4bc115e..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStepDescriptor.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.hadoop.gateway.filter.rewrite.api;
-
-public interface UrlRewriteStepDescriptor<T> {
-
-  String type();
-
-  T type( String type );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStepDescriptorFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStepDescriptorFactory.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStepDescriptorFactory.java
deleted file mode 100644
index 9c30c3f..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStepDescriptorFactory.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.hadoop.gateway.filter.rewrite.api;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.ServiceLoader;
-import java.util.Set;
-
-public abstract class UrlRewriteStepDescriptorFactory {
-
-  private static Map<String,Class<? extends UrlRewriteStepDescriptor>> MAP = loadStepDescriptors();
-
-  private UrlRewriteStepDescriptorFactory() {
-  }
-
-  @SuppressWarnings("unchecked")
-  public static <T extends UrlRewriteStepDescriptor<?>> T create( String type ) {
-    try {
-      Class<? extends UrlRewriteStepDescriptor> descriptorClass = MAP.get( type );
-      return (T)descriptorClass.newInstance();
-    } catch( InstantiationException e ) {
-      throw new IllegalArgumentException( type );
-    } catch( IllegalAccessException e ) {
-      throw new IllegalArgumentException( type );
-    }
-  }
-
-  private static Map<String,Class<? extends UrlRewriteStepDescriptor>> loadStepDescriptors() {
-    Map<String,Class<? extends UrlRewriteStepDescriptor>> map
-        = new HashMap<>();
-    ServiceLoader<? extends UrlRewriteStepDescriptor> descriptors
-        = ServiceLoader.load( UrlRewriteStepDescriptor.class );
-    for( UrlRewriteStepDescriptor descriptor : descriptors ) {
-      String descriptorType = descriptor.type();
-      Class<? extends UrlRewriteStepDescriptor> descriptorClass = descriptor.getClass() ;
-      map.put( descriptorType, descriptorClass );
-    }
-    return map;
-  }
-
-  public static Set<String> getTypes() {
-    return MAP.keySet();
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStepFlow.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStepFlow.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStepFlow.java
deleted file mode 100644
index 787e3fd..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStepFlow.java
+++ /dev/null
@@ -1,20 +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.hadoop.gateway.filter.rewrite.api;
-
-public enum UrlRewriteStepFlow { ALL, AND, OR }

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStreamFilterFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStreamFilterFactory.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStreamFilterFactory.java
deleted file mode 100644
index cd7c439..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteStreamFilterFactory.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.hadoop.gateway.filter.rewrite.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStreamFilter;
-import org.apache.hadoop.gateway.util.MimeTypes;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-
-import javax.activation.MimeType;
-import javax.activation.MimeTypeParseException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.ServiceLoader;
-
-public abstract class UrlRewriteStreamFilterFactory {
-
-  private static final String DEFAULT_CHARACTER_ENCODING = "ISO-8859-1";
-
-  private static final Map<String,Map<String,UrlRewriteStreamFilter>> MAP = loadFactories();
-
-  private UrlRewriteStreamFilterFactory() {
-  }
-
-  public static InputStream create(
-      MimeType type,
-      String name,
-      InputStream stream,
-      UrlRewriter rewriter,
-      Resolver resolver,
-      UrlRewriter.Direction direction,
-      UrlRewriteFilterContentDescriptor config )
-          throws IOException {
-    InputStream filteredStream = null;
-    Map<String,UrlRewriteStreamFilter> nameMap = getNameMap( type );
-    UrlRewriteStreamFilter filter = getFilter( nameMap, name );
-    String charset = MimeTypes.getCharset( type, DEFAULT_CHARACTER_ENCODING );
-    if( filter != null ) {
-      filteredStream = filter.filter( stream, charset, rewriter, resolver, direction, config );
-    }
-    return filteredStream;
-  }
-
-  private static Map<String,Map<String,UrlRewriteStreamFilter>> loadFactories() {
-    Map<String,Map<String,UrlRewriteStreamFilter>> typeMap = new HashMap<>();
-    ServiceLoader<UrlRewriteStreamFilter> filters = ServiceLoader.load( UrlRewriteStreamFilter.class );
-    for( UrlRewriteStreamFilter filter : filters ) {
-      String[] types = filter.getTypes();
-      for( String type: types ) {
-        Map<String,UrlRewriteStreamFilter> nameMap = typeMap.get( type );
-        if( nameMap == null ) {
-          nameMap = new LinkedHashMap<String,UrlRewriteStreamFilter>();
-          typeMap.put( type, nameMap );
-        }
-        for( String name: filter.getNames() ) {
-          nameMap.put( name, filter );
-        }
-      }
-    }
-    return typeMap;
-  }
-
-  private static Map<String,UrlRewriteStreamFilter> getNameMap( MimeType type ) {
-    if( type == null ) {
-      type = new MimeType();
-    }
-    Map<String,UrlRewriteStreamFilter> nameMap = MAP.get( type.getBaseType() );
-    try {
-      if( nameMap == null ) {
-        type.setPrimaryType( "*" );
-        nameMap = MAP.get( type.getBaseType() );
-        if( nameMap == null ) {
-          type.setSubType( "*" );
-          nameMap = MAP.get( type.getBaseType() );
-          if( nameMap == null ) {
-            nameMap = MAP.get( null );
-          }
-        }
-      }
-    } catch( MimeTypeParseException e ) {
-      throw new IllegalArgumentException( type.toString(), e );
-    }
-    return nameMap;
-  }
-
-  private static UrlRewriteStreamFilter getFilter( Map<String,UrlRewriteStreamFilter> map, String name ) {
-    UrlRewriteStreamFilter filter = null;
-    if( map != null ) {
-      if( name == null && !map.isEmpty() ) {
-        filter = map.values().iterator().next();
-      } else {
-        filter = map.get( name );
-      }
-    }
-    return filter;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriter.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriter.java
deleted file mode 100644
index 76106f0..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriter.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.filter.rewrite.api;
-
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-public interface UrlRewriter {
-
-  enum Direction { IN, OUT }
-
-  UrlRewriteRulesDescriptor getConfig();
-
-  Template rewrite( Resolver resolver, Template uri, Direction direction, String ruleName );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/ScopedMatcher.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/ScopedMatcher.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/ScopedMatcher.java
deleted file mode 100644
index 7f4ef63..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/ScopedMatcher.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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.filter.rewrite.ext;
-
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteRuleProcessorHolder;
-import org.apache.hadoop.gateway.util.urltemplate.Matcher;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A simple extension to the matcher that takes into account scopes for rules along with the templates themselves.
- * This matcher maintains a list of matchers and delegates to an appropriate matcher based on scope information for the
- * associated rules.
- */
-public class ScopedMatcher extends Matcher<UrlRewriteRuleProcessorHolder> {
-
-  public static final String GLOBAL_SCOPE = "GLOBAL";
-
-  private List<Matcher<UrlRewriteRuleProcessorHolder>> matchers;
-
-  public ScopedMatcher() {
-    super();
-    matchers = new ArrayList<>();
-    matchers.add(new Matcher<UrlRewriteRuleProcessorHolder>());
-  }
-
-  @Override
-  public UrlRewriteRuleProcessorHolder get(Template template) {
-    return super.get(template);
-  }
-
-  @Override
-  public void add(Template template, UrlRewriteRuleProcessorHolder value) {
-    Matcher<UrlRewriteRuleProcessorHolder> matcher = getMatcher(template, value);
-    matcher.add( template, value );
-  }
-
-  @Override
-  public Match match(Template input) {
-    return match(input, null);
-  }
-
-  public Match match(Template input, String scope) {
-    List<Match> matches = new ArrayList<>();
-    for (Matcher<UrlRewriteRuleProcessorHolder> matcher : matchers) {
-      Match match = matcher.match(input);
-      if (match != null) {
-        matches.add(match);
-      }
-    }
-    if (matches.size() == 0) {
-      return null;
-    }
-    if (matches.size() == 1) {
-      return getMatch(matches, scope);
-    }
-    return findBestMatch(matches, scope);
-  }
-
-  private Match findBestMatch(List<Match> matches, String scope) {
-    if (scope != null) {
-      //when multiple matches are found, find the first one that matches in scope
-      for ( Match match : matches ) {
-        String matchedScope = match.getValue().getScope();
-        if ( matchedScope != null && matchedScope.equals(scope) ) {
-          return match;
-        }
-      }
-    }
-    //since no scope match was found return the first global scopeed match
-    for ( Match match : matches ) {
-      String matchedScope = match.getValue().getScope();
-      if ( matchedScope != null && matchedScope.equals(GLOBAL_SCOPE) ) {
-        return match;
-      }
-    }
-    //return the first match from the list
-    return getMatch(matches, scope);
-  }
-
-  private Match getMatch(List<Match> matches, String scope) {
-    Match match = matches.get(0);
-    String matchedScope = match.getValue().getScope();
-    if (matchedScope != null && scope != null && !matchedScope.equals(scope) && !matchedScope.equals(GLOBAL_SCOPE)) {
-      return null;
-    }
-    return match;
-  }
-
-  /**
-   * Returns a matcher for a given template and processor holder. This method takes into account different scopes in
-   * addition to template values. If a matcher exists for a template but the scope is different, a new matcher is
-   * created and returned.
-   * @param template the template for which a matcher is needed
-   * @param holder the rule holder that goes along with the template.
-   * @return a matcher
-   */
-  private Matcher<UrlRewriteRuleProcessorHolder> getMatcher(Template template, UrlRewriteRuleProcessorHolder holder) {
-    for (Matcher<UrlRewriteRuleProcessorHolder> matcher : matchers) {
-      UrlRewriteRuleProcessorHolder matchersHolder = matcher.get(template);
-      if (matchersHolder == null) {
-        return matcher;
-      } else if (holder.getScope() == null && matchersHolder.getScope() == null) {
-        return matcher;
-      }
-    }
-    Matcher<UrlRewriteRuleProcessorHolder> matcher = new Matcher<>();
-    matchers.add(matcher);
-    return matcher;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteActionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteActionDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteActionDescriptor.java
deleted file mode 100644
index ab50e55..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteActionDescriptor.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.hadoop.gateway.filter.rewrite.ext;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
-
-public interface UrlRewriteActionDescriptor extends UrlRewriteStepDescriptor<UrlRewriteActionDescriptor> {
-
-  String operation();
-
-  UrlRewriteActionDescriptor operation( String operation );
-
-  String parameter();
-
-  UrlRewriteActionDescriptor parameter( String parameter );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteActionRewriteDescriptorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteActionRewriteDescriptorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteActionRewriteDescriptorExt.java
deleted file mode 100644
index 1a5cf4a..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteActionRewriteDescriptorExt.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.hadoop.gateway.filter.rewrite.ext;
-
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
-
-public class UrlRewriteActionRewriteDescriptorExt
-    extends UrlRewriteActionDescriptorBase
-    implements UrlRewriteActionDescriptor {
-
-  public UrlRewriteActionRewriteDescriptorExt() {
-    super( "rewrite" );
-  }
-
-  public String template() {
-    return parameter();
-  }
-
-  public UrlRewriteActionRewriteDescriptorExt template( String template ) {
-    parameter( template );
-    return this;
-  }
-
-  public void setTemplate( String template ) {
-    parameter( template );
-  }
-
-  @Override
-  public String getParam() {
-    return null;
-  }
-
-  public String getTemplate() {
-    return parameter();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteActionRewriteProcessorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteActionRewriteProcessorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteActionRewriteProcessorExt.java
deleted file mode 100644
index a2bcb1b..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteActionRewriteProcessorExt.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.hadoop.gateway.filter.rewrite.ext;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-import org.apache.hadoop.gateway.util.urltemplate.Expander;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-public class UrlRewriteActionRewriteProcessorExt
-    implements UrlRewriteStepProcessor<UrlRewriteActionRewriteDescriptorExt> {
-
-  private Template template;
-  private Expander expander;
-
-  @Override
-  public String getType() {
-    return "rewrite";
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, UrlRewriteActionRewriteDescriptorExt descriptor ) throws Exception {
-    this.expander = new Expander();
-    if ( descriptor.parameter() != null ) {
-      this.template = Parser.parseTemplate( descriptor.parameter() );
-    } else {
-      this.template = Parser.parseTemplate( "" );
-    }
-  }
-
-  @Override
-  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
-    Template rewritten = expander.expandToTemplate( template, context.getParameters(), context.getEvaluator() );
-    context.setCurrentUrl( rewritten );
-    return UrlRewriteStepStatus.SUCCESS;
-  }
-
-  @Override
-  public void destroy() {
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptor.java
deleted file mode 100644
index 00e8c97..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptor.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.hadoop.gateway.filter.rewrite.ext;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFlowDescriptor;
-
-public interface UrlRewriteCheckDescriptor extends UrlRewriteFlowDescriptor<UrlRewriteCheckDescriptor> {
-
-  String operation();
-
-  UrlRewriteCheckDescriptor operation( String operation );
-
-  String input();
-
-  UrlRewriteCheckDescriptor input( String input );
-
-  String value();
-
-  UrlRewriteCheckDescriptor value( String value );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptorExt.java
deleted file mode 100644
index b7630b7..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptorExt.java
+++ /dev/null
@@ -1,99 +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.hadoop.gateway.filter.rewrite.ext;
-
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFlowDescriptorBase;
-
-public class UrlRewriteCheckDescriptorExt
-    extends UrlRewriteFlowDescriptorBase<UrlRewriteCheckDescriptor>
-    implements UrlRewriteCheckDescriptor {
-
-  private String operation;
-  private String input;
-  private String value;
-
-  public UrlRewriteCheckDescriptorExt() {
-    super( "check" );
-  }
-
-  @Override
-  public String operation() {
-    return operation;
-  }
-
-  @Override
-  public UrlRewriteCheckDescriptor operation( String operation ) {
-    this.operation = operation;
-    return this;
-  }
-
-  public void setOperation( String operation ) {
-    operation( operation );
-  }
-
-  public void setOper( String operation ) {
-    operation( operation );
-  }
-
-  public void setOp( String operation ) {
-    operation( operation );
-  }
-
-  public String getOper() {
-    return operation();
-  }
-
-  @Override
-  public String input() {
-    return input;
-  }
-
-  @Override
-  public UrlRewriteCheckDescriptor input( String input ) {
-    this.input = input;
-    return this;
-  }
-
-  public void setInput( String input ) {
-    input( input );
-  }
-
-  public String getInput() {
-    return input();
-  }
-
-  @Override
-  public String value() {
-    return value;
-  }
-
-  @Override
-  public UrlRewriteCheckDescriptor value( String value ) {
-    this.value = value;
-    return this;
-  }
-
-  public void setValue( String value ) {
-    value( value );
-  }
-
-  public String getValue() {
-    return value();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteCheckProcessorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteCheckProcessorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteCheckProcessorExt.java
deleted file mode 100644
index aafd3bb..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteCheckProcessorExt.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.hadoop.gateway.filter.rewrite.ext;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-
-public class UrlRewriteCheckProcessorExt implements UrlRewriteStepProcessor<UrlRewriteCheckDescriptor> {
-
-  @Override
-  public String getType() {
-    return "check";
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, UrlRewriteCheckDescriptor descriptor ) throws Exception {
-  }
-
-  @Override
-  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
-    return UrlRewriteStepStatus.FAILURE;
-  }
-
-  @Override
-  public void destroy() {
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteControlDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteControlDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteControlDescriptor.java
deleted file mode 100644
index c6ef973..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteControlDescriptor.java
+++ /dev/null
@@ -1,23 +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.hadoop.gateway.filter.rewrite.ext;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFlowDescriptor;
-
-public interface UrlRewriteControlDescriptor extends UrlRewriteFlowDescriptor<UrlRewriteControlDescriptor> {
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteControlDescriptorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteControlDescriptorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteControlDescriptorExt.java
deleted file mode 100644
index 0a23364..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteControlDescriptorExt.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.hadoop.gateway.filter.rewrite.ext;
-
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFlowDescriptorBase;
-
-public class UrlRewriteControlDescriptorExt
-    extends UrlRewriteFlowDescriptorBase<UrlRewriteControlDescriptor>
-    implements UrlRewriteControlDescriptor {
-
-  public UrlRewriteControlDescriptorExt() {
-    super( "control" );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteControlProcessorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteControlProcessorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteControlProcessorExt.java
deleted file mode 100644
index c43994b..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteControlProcessorExt.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.hadoop.gateway.filter.rewrite.ext;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-
-public class UrlRewriteControlProcessorExt implements UrlRewriteStepProcessor<UrlRewriteControlDescriptor> {
-
-  @Override
-  public String getType() {
-    return "control";
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, UrlRewriteControlDescriptor descriptor ) throws Exception {
-  }
-
-  @Override
-  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
-    return UrlRewriteStepStatus.FAILURE;
-  }
-
-  @Override
-  public void destroy() {
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptor.java
deleted file mode 100644
index 3d133c1..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptor.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.hadoop.gateway.filter.rewrite.ext;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFlowDescriptor;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.net.URISyntaxException;
-
-public interface UrlRewriteMatchDescriptor extends UrlRewriteFlowDescriptor<UrlRewriteMatchDescriptor> {
-
-  String operation();
-
-  UrlRewriteMatchDescriptor operation( String operation );
-
-  String pattern();
-
-  UrlRewriteMatchDescriptor pattern( String pattern ) throws URISyntaxException;
-
-  Template template();
-
-  UrlRewriteMatchDescriptor template( Template pattern );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptorExt.java
deleted file mode 100644
index a8e1130..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptorExt.java
+++ /dev/null
@@ -1,110 +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.hadoop.gateway.filter.rewrite.ext;
-
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFlowDescriptorBase;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.net.URISyntaxException;
-
-public class UrlRewriteMatchDescriptorExt
-    extends UrlRewriteFlowDescriptorBase<UrlRewriteMatchDescriptor>
-    implements UrlRewriteMatchDescriptor {
-
-  private String operation;
-  private String pattern;
-  private Template template;
-
-  public UrlRewriteMatchDescriptorExt() {
-    super( "match" );
-  }
-
-  @Override
-  public String operation() {
-    return operation;
-  }
-
-  public String getOperation() {
-    return operation;
-  }
-
-  @Override
-  public UrlRewriteMatchDescriptor operation( String operation ) {
-    this.operation = operation;
-    return this;
-  }
-
-  public void setOperation( String operation ) {
-    operation( operation );
-  }
-
-  public void setOper( String operation ) {
-    operation( operation );
-  }
-
-  public void setOp( String operation ) {
-    operation( operation );
-  }
-
-  public String getOper() {
-    return operation();
-  }
-
-  @Override
-  public String pattern() {
-    return pattern;
-  }
-
-  @Override
-  public UrlRewriteMatchDescriptor pattern( String pattern ) throws URISyntaxException {
-    this.pattern = pattern;
-    this.template = Parser.parseTemplate( pattern );
-    return this;
-  }
-
-  public void setUrl( String pattern ) throws URISyntaxException {
-    pattern( pattern );
-  }
-
-  public void setPattern( String pattern ) throws URISyntaxException {
-    pattern( pattern );
-  }
-
-  public String getPattern() {
-    return pattern;
-  }
-
-  @Override
-  public Template template() {
-    return template;
-  }
-
-  @Override
-  public UrlRewriteMatchDescriptor template( Template template ) {
-    this.template = template;
-    // The template is now optional for rules.
-    if( template == null ) {
-      this.pattern = null;
-    } else {
-      this.pattern = template.toString();
-    }
-    return this;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteMatchProcessorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteMatchProcessorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteMatchProcessorExt.java
deleted file mode 100644
index 04f919a..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/ext/UrlRewriteMatchProcessorExt.java
+++ /dev/null
@@ -1,66 +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.hadoop.gateway.filter.rewrite.ext;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-import org.apache.hadoop.gateway.util.urltemplate.Matcher;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-public class UrlRewriteMatchProcessorExt implements UrlRewriteStepProcessor<UrlRewriteMatchDescriptor> {
-
-  //private UrlRewriteMatchDescriptor descriptor;
-  private Matcher<Void> matcher;
-
-  @Override
-  public String getType() {
-    return "match";
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, UrlRewriteMatchDescriptor descriptor ) throws Exception {
-    Template template = descriptor.template();
-    if( template == null ) {
-      this.matcher = null;
-    } else {
-      this.matcher = new Matcher<Void>( descriptor.template(), null );
-    }
-  }
-
-  @Override
-  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
-    UrlRewriteStepStatus status = UrlRewriteStepStatus.SUCCESS;
-    if( matcher != null ) {
-      status = UrlRewriteStepStatus.FAILURE;
-      Matcher.Match match = matcher.match( context.getCurrentUrl() );
-      if( match != null ) {
-        context.addParameters( match.getParams() );
-        status = UrlRewriteStepStatus.SUCCESS;
-      }
-    }
-    return status;
-  }
-
-  @Override
-  public void destroy() {
-    matcher = null;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/i18n/UrlRewriteMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/i18n/UrlRewriteMessages.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/i18n/UrlRewriteMessages.java
deleted file mode 100644
index 4f304bc..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/i18n/UrlRewriteMessages.java
+++ /dev/null
@@ -1,87 +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.hadoop.gateway.filter.rewrite.i18n;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-import org.apache.hadoop.gateway.i18n.messages.StackTrace;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-@Messages(logger="org.apache.hadoop.gateway")
-public interface UrlRewriteMessages {
-
-  @Message( level = MessageLevel.DEBUG, text = "Failed to parse value as URL: {0}" )
-  void failedToParseValueForUrlRewrite( String value );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to write the rules descriptor: {0}" )
-  void failedToWriteRulesDescriptor( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.DEBUG, text = "Failed to filter attribute {0}: {1}" )
-  void failedToFilterAttribute( String attributeName, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to load rewrite rules descriptor: {0}" )
-  void failedToLoadRewriteRulesDescriptor( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to initialize rewrite rules: {0}" )
-  void failedToInitializeRewriteRules( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to initialize rewrite functions: {0}" )
-  void failedToInitializeRewriteFunctions( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to destroy rewrite rule processor: {0}" )
-  void failedToDestroyRewriteStepProcessor( @StackTrace(level = MessageLevel.DEBUG) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to destroy rewrite function processor: {0}" )
-  void failedToDestroyRewriteFunctionProcessor( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to filter value {0}, rule {1}" )
-  void failedToFilterValue( String value, String rule );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to filter value {0}, rule {1}: {2}" )
-  void failedToFilterValue( String value, String rule, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to filter field name {0}: {1}" )
-  void failedToFilterFieldName( String fieldName, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Rewrite function {0} failed: {1}" )
-  void failedToInvokeRewriteFunction( String functionName, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to find values by parameter name {0}: {1}" )
-  void failedToFindValuesByParameter( String parameterName, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.DEBUG, text = "Rewrote URL: {0}, direction: {1} via implicit rule: {2} to URL: {3}" )
-  void rewroteUrlViaImplicitRule( Template inputUri, UrlRewriter.Direction direction, String ruleName, Template outputUri );
-
-  @Message( level = MessageLevel.DEBUG, text = "Rewrote URL: {0}, direction: {1} via explicit rule: {2} to URL: {3}" )
-  void rewroteUrlViaExplicitRule( Template inputUri, UrlRewriter.Direction direction, String ruleName, Template outputUri );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to rewrite URL: {0}, direction: {1} via rule: {2}, status: {3}" )
-  void failedToRewriteUrl( Template inputUri, UrlRewriter.Direction direction, String ruleName, UrlRewriteStepStatus stepStatus );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to rewrite URL: {0}, direction: {1}, rule: {2}" )
-  void failedToRewriteUrlDueToException( Template inputUri, UrlRewriter.Direction direction, String ruleName, @StackTrace(level = MessageLevel.DEBUG) Exception exception );
-
-  @Message( level = MessageLevel.TRACE, text = "No rule matching URL: {0}, direction: {1}" )
-  void noRuleMatchingUrl( Template inputUri, UrlRewriter.Direction direction );
-
-  @Message( level = MessageLevel.TRACE, text = "Failed to decode query string: {0}" )
-  void failedToDecodeQueryString( String queryString, @StackTrace(level = MessageLevel.TRACE) Exception exception );
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/i18n/UrlRewriteResources.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/i18n/UrlRewriteResources.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/i18n/UrlRewriteResources.java
deleted file mode 100644
index e406902..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/i18n/UrlRewriteResources.java
+++ /dev/null
@@ -1,41 +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.hadoop.gateway.filter.rewrite.i18n;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
-import org.apache.hadoop.gateway.i18n.resources.Resource;
-import org.apache.hadoop.gateway.i18n.resources.Resources;
-
-@Resources
-public interface UrlRewriteResources {
-
-  @Resource( text="No importer for descriptor format {0}" )
-  String noImporterForFormat( String format );
-
-  @Resource( text="No exporter for descriptor format {0}" )
-  String noExporterForFormat( String format );
-
-  @Resource( text="Unexpected selector type {0}" )
-  String unexpectedRewritePathSelector( UrlRewriteFilterPathDescriptor selector );
-
-  @Resource( text="Unexpected selected node type {0}" )
-  String unexpectedSelectedNodeType( Object node );
-
-  @Resource( text="Invalid frontend rewrite function parameter {0}" )
-  String invalidFrontendFunctionParameter( String parameter );
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/CookieScopeResponseWrapper.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/CookieScopeResponseWrapper.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/CookieScopeResponseWrapper.java
deleted file mode 100644
index 6360f33..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/CookieScopeResponseWrapper.java
+++ /dev/null
@@ -1,59 +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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.GatewayResponseWrapper;
-
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.io.OutputStream;
-
-public class CookieScopeResponseWrapper extends GatewayResponseWrapper {
-
-    private static final String SET_COOKIE = "Set-Cookie";
-
-    private static final String COOKIE_PATH = "Path=/";
-
-    private final String scopePath;
-
-    public CookieScopeResponseWrapper(HttpServletResponse response, String gatewayPath) {
-        super(response);
-        this.scopePath = COOKIE_PATH + gatewayPath + "/";
-    }
-
-    @Override
-    public void addHeader(String name, String value) {
-        if (SET_COOKIE.equals(name)) {
-            String updatedCookie;
-            if (value.contains(COOKIE_PATH)) {
-                updatedCookie = value.replace(COOKIE_PATH, scopePath);
-            } else {
-                // append the scope path
-                updatedCookie = String.format("%s %s;", value, scopePath);
-            }
-            super.addHeader(name, updatedCookie);
-        } else {
-            super.addHeader(name, value);
-        }
-    }
-
-    @Override
-    public OutputStream getRawOutputStream() throws IOException {
-        return getResponse().getOutputStream();
-    }
-}


[11/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTFederationContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTFederationContributor.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTFederationContributor.java
new file mode 100644
index 0000000..47e8f0f
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTFederationContributor.java
@@ -0,0 +1,63 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.provider.federation.jwt.deploy;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class JWTFederationContributor extends
+    ProviderDeploymentContributorBase {
+
+  private static final String FILTER_CLASSNAME = "JWTFederationFilter";
+
+  @Override
+  public String getRole() {
+    return "federation";
+  }
+
+  @Override
+  public String getName() {
+    return "JWTProvider";
+  }
+
+  @Override
+  public void contributeProvider( DeploymentContext context, Provider provider ) {
+  }
+
+  @Override
+  public void contributeFilter( DeploymentContext context, Provider provider, Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
+    // blindly add all the provider params as filter init params
+    if (params == null) {
+      params = new ArrayList<FilterParamDescriptor>();
+    }
+    Map<String, String> providerParams = provider.getParams();
+    for(Entry<String, String> entry : providerParams.entrySet()) {
+      params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
+    }
+    resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/SSOCookieFederationContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/SSOCookieFederationContributor.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/SSOCookieFederationContributor.java
new file mode 100644
index 0000000..f798236
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/SSOCookieFederationContributor.java
@@ -0,0 +1,63 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.provider.federation.jwt.deploy;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class SSOCookieFederationContributor extends
+    ProviderDeploymentContributorBase {
+
+  private static final String FILTER_CLASSNAME = "SSOCookieFederationFilter";
+
+  @Override
+  public String getRole() {
+    return "federation";
+  }
+
+  @Override
+  public String getName() {
+    return "SSOCookieProvider";
+  }
+
+  @Override
+  public void contributeProvider( DeploymentContext context, Provider provider ) {
+  }
+
+  @Override
+  public void contributeFilter( DeploymentContext context, Provider provider, Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
+    // blindly add all the provider params as filter init params
+    if (params == null) {
+      params = new ArrayList<FilterParamDescriptor>();
+    }
+    Map<String, String> providerParams = provider.getParams();
+    for(Entry<String, String> entry : providerParams.entrySet()) {
+      params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
+    }
+    resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AbstractJWTFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AbstractJWTFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AbstractJWTFilter.java
new file mode 100644
index 0000000..ea64b45
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AbstractJWTFilter.java
@@ -0,0 +1,263 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.provider.federation.jwt.filter;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.security.interfaces.RSAPublicKey;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.audit.api.Action;
+import org.apache.knox.gateway.audit.api.ActionOutcome;
+import org.apache.knox.gateway.audit.api.AuditContext;
+import org.apache.knox.gateway.audit.api.AuditService;
+import org.apache.knox.gateway.audit.api.AuditServiceFactory;
+import org.apache.knox.gateway.audit.api.Auditor;
+import org.apache.knox.gateway.audit.api.ResourceType;
+import org.apache.knox.gateway.audit.log4j.audit.AuditConstants;
+import org.apache.knox.gateway.filter.AbstractGatewayFilter;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.provider.federation.jwt.JWTMessages;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.token.JWTokenAuthority;
+import org.apache.knox.gateway.services.security.token.TokenServiceException;
+import org.apache.knox.gateway.services.security.token.impl.JWTToken;
+
+/**
+ *
+ */
+public abstract class AbstractJWTFilter implements Filter {
+  static JWTMessages log = MessagesFactory.get( JWTMessages.class );
+  protected List<String> audiences;
+  protected JWTokenAuthority authority;
+  protected String verificationPEM = null;
+  protected RSAPublicKey publicKey = null;
+  private static AuditService auditService = AuditServiceFactory.getAuditService();
+  private static Auditor auditor = auditService.getAuditor(
+      AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
+      AuditConstants.KNOX_COMPONENT_NAME );
+
+  public abstract void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+      throws IOException, ServletException;
+
+  /**
+   * 
+   */
+  public AbstractJWTFilter() {
+    super();
+  }
+
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+    ServletContext context = filterConfig.getServletContext();
+    if (context != null) {
+      GatewayServices services = (GatewayServices) context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
+      if (services != null) {
+        authority = (JWTokenAuthority) services.getService(GatewayServices.TOKEN_SERVICE);
+      }
+    }
+  }
+
+  /**
+   * @param expectedAudiences
+   * @return
+   */
+  protected List<String> parseExpectedAudiences(String expectedAudiences) {
+    ArrayList<String> audList = null;
+    // setup the list of valid audiences for token validation
+    if (expectedAudiences != null) {
+      // parse into the list
+      String[] audArray = expectedAudiences.split(",");
+      audList = new ArrayList<String>();
+      for (String a : audArray) {
+        audList.add(a);
+      }
+    }
+    return audList;
+  }
+
+  protected boolean tokenIsStillValid(JWTToken jwtToken) {
+    // if there is no expiration date then the lifecycle is tied entirely to
+    // the cookie validity - otherwise ensure that the current time is before
+    // the designated expiration time
+    Date expires = jwtToken.getExpiresDate();
+    return (expires == null || expires != null && new Date().before(expires));
+  }
+
+  /**
+   * Validate whether any of the accepted audience claims is present in the
+   * issued token claims list for audience. Override this method in subclasses
+   * in order to customize the audience validation behavior.
+   *
+   * @param jwtToken
+   *          the JWT token where the allowed audiences will be found
+   * @return true if an expected audience is present, otherwise false
+   */
+  protected boolean validateAudiences(JWTToken jwtToken) {
+    boolean valid = false;
+    
+    String[] tokenAudienceList = jwtToken.getAudienceClaims();
+    // if there were no expected audiences configured then just
+    // consider any audience acceptable
+    if (audiences == null) {
+      valid = true;
+    } else {
+      // if any of the configured audiences is found then consider it
+      // acceptable
+      if (tokenAudienceList != null) {
+        for (String aud : tokenAudienceList) {
+          if (audiences.contains(aud)) {
+            log.jwtAudienceValidated();
+            valid = true;
+            break;
+          }
+        }
+      }
+    }
+    return valid;
+  }
+
+  protected void continueWithEstablishedSecurityContext(Subject subject, final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
+    Principal principal = (Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0];
+    AuditContext context = auditService.getContext();
+    if (context != null) {
+      context.setUsername( principal.getName() );
+      String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
+      if (sourceUri != null) {
+        auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
+      }
+    }
+
+    try {
+      Subject.doAs(
+        subject,
+        new PrivilegedExceptionAction<Object>() {
+          @Override
+          public Object run() throws Exception {
+            chain.doFilter(request, response);
+            return null;
+          }
+        }
+        );
+    }
+    catch (PrivilegedActionException e) {
+      Throwable t = e.getCause();
+      if (t instanceof IOException) {
+        throw (IOException) t;
+      }
+      else if (t instanceof ServletException) {
+        throw (ServletException) t;
+      }
+      else {
+        throw new ServletException(t);
+      }
+    }
+  }
+
+  protected Subject createSubjectFromToken(JWTToken token) {
+    final String principal = token.getSubject();
+
+    @SuppressWarnings("rawtypes")
+    HashSet emptySet = new HashSet();
+    Set<Principal> principals = new HashSet<>();
+    Principal p = new PrimaryPrincipal(principal);
+    principals.add(p);
+      
+    // The newly constructed Sets check whether this Subject has been set read-only 
+    // before permitting subsequent modifications. The newly created Sets also prevent 
+    // illegal modifications by ensuring that callers have sufficient permissions.
+    //
+    // To modify the Principals Set, the caller must have AuthPermission("modifyPrincipals"). 
+    // To modify the public credential Set, the caller must have AuthPermission("modifyPublicCredentials"). 
+    // To modify the private credential Set, the caller must have AuthPermission("modifyPrivateCredentials").
+    javax.security.auth.Subject subject = new javax.security.auth.Subject(true, principals, emptySet, emptySet);
+    return subject;
+  }
+  
+  protected boolean validateToken(HttpServletRequest request, HttpServletResponse response,
+      FilterChain chain, JWTToken token)
+      throws IOException, ServletException {
+    boolean verified = false;
+    try {
+      if (publicKey == null) {
+        verified = authority.verifyToken(token);
+      }
+      else {
+        verified = authority.verifyToken(token, publicKey);
+      }
+    } catch (TokenServiceException e) {
+      log.unableToVerifyToken(e);
+    }
+    
+    if (verified) {
+      // confirm that issue matches intended target - which for this filter must be KNOXSSO
+      if (token.getIssuer().equals("KNOXSSO")) {
+        // if there is no expiration data then the lifecycle is tied entirely to
+        // the cookie validity - otherwise ensure that the current time is before
+        // the designated expiration time
+        if (tokenIsStillValid(token)) {
+          boolean audValid = validateAudiences(token);
+          if (audValid) {
+            return true;
+          }
+          else {
+            log.failedToValidateAudience();
+            handleValidationError(request, response, HttpServletResponse.SC_BAD_REQUEST, 
+                                  "Bad request: missing required token audience");
+          }
+        }
+        else {
+          log.tokenHasExpired();
+          handleValidationError(request, response, HttpServletResponse.SC_BAD_REQUEST, 
+                                "Bad request: token has expired");
+        }
+      }
+      else {
+        handleValidationError(request, response, HttpServletResponse.SC_UNAUTHORIZED, null);
+      }
+    }
+    else {
+      log.failedToVerifyTokenSignature();
+      handleValidationError(request, response, HttpServletResponse.SC_UNAUTHORIZED, null);
+    }
+
+    return false;
+  }
+  
+  protected abstract void handleValidationError(HttpServletRequest request, HttpServletResponse response, int status, 
+                                                String error) throws IOException;
+  
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AccessTokenFederationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AccessTokenFederationFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AccessTokenFederationFilter.java
new file mode 100644
index 0000000..fcfee38
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AccessTokenFederationFilter.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.knox.gateway.provider.federation.jwt.filter;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.text.ParseException;
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.provider.federation.jwt.JWTMessages;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.token.JWTokenAuthority;
+import org.apache.knox.gateway.services.security.token.TokenServiceException;
+import org.apache.knox.gateway.services.security.token.impl.JWTToken;
+
+public class AccessTokenFederationFilter implements Filter {
+  private static JWTMessages log = MessagesFactory.get( JWTMessages.class );
+  private static final String BEARER = "Bearer ";
+  
+  private JWTokenAuthority authority;
+  
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+    GatewayServices services = (GatewayServices) filterConfig.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
+    authority = (JWTokenAuthority) services.getService(GatewayServices.TOKEN_SERVICE);
+  }
+
+  public void destroy() {
+  }
+
+  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
+      throws IOException, ServletException {
+    String header = ((HttpServletRequest) request).getHeader("Authorization");
+    if (header != null && header.startsWith(BEARER)) {
+      // what follows the bearer designator should be the JWT token being used to request or as an access token
+      String wireToken = header.substring(BEARER.length());
+      JWTToken token;
+      try {
+        token = JWTToken.parseToken(wireToken);
+      } catch (ParseException e) {
+        throw new ServletException("ParseException encountered while processing the JWT token: ", e);
+      }
+
+      boolean verified = false;
+      try {
+        verified = authority.verifyToken(token);
+      } catch (TokenServiceException e) {
+        log.unableToVerifyToken(e);
+      }
+      if (verified) {
+        long expires = Long.parseLong(token.getExpires());
+        if (expires > System.currentTimeMillis()) {
+          if (((HttpServletRequest) request).getRequestURL().indexOf(token.getAudience().toLowerCase()) != -1) {
+            Subject subject = createSubjectFromToken(token);
+            continueWithEstablishedSecurityContext(subject, (HttpServletRequest)request, (HttpServletResponse)response, chain);
+          }
+          else {
+            log.failedToValidateAudience();
+            sendUnauthorized(response);
+            return; // break the chain
+          }
+        }
+        else {
+          log.tokenHasExpired();
+          sendUnauthorized(response);
+          return; // break the chain
+        }
+      }
+      else {
+        log.failedToVerifyTokenSignature();
+        sendUnauthorized(response);
+        return; // break the chain
+      }
+    }
+    else {
+      log.missingBearerToken();
+      sendUnauthorized(response);
+      return; // break the chain
+    }
+  }
+
+  private void sendUnauthorized(ServletResponse response) throws IOException {
+    ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
+    return;
+  }
+  
+  private void continueWithEstablishedSecurityContext(Subject subject, final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
+    try {
+      Subject.doAs(
+        subject,
+        new PrivilegedExceptionAction<Object>() {
+          @Override
+          public Object run() throws Exception {
+            chain.doFilter(request, response);
+            return null;
+          }
+        }
+        );
+    }
+    catch (PrivilegedActionException e) {
+      Throwable t = e.getCause();
+      if (t instanceof IOException) {
+        throw (IOException) t;
+      }
+      else if (t instanceof ServletException) {
+        throw (ServletException) t;
+      }
+      else {
+        throw new ServletException(t);
+      }
+    }
+  }
+  
+  private Subject createSubjectFromToken(JWTToken token) {
+    final String principal = token.getPrincipal();
+
+    HashSet emptySet = new HashSet();
+    Set<Principal> principals = new HashSet<>();
+    Principal p = new PrimaryPrincipal(principal);
+    principals.add(p);
+    
+//        The newly constructed Sets check whether this Subject has been set read-only 
+//        before permitting subsequent modifications. The newly created Sets also prevent 
+//        illegal modifications by ensuring that callers have sufficient permissions.
+//
+//        To modify the Principals Set, the caller must have AuthPermission("modifyPrincipals"). 
+//        To modify the public credential Set, the caller must have AuthPermission("modifyPublicCredentials"). 
+//        To modify the private credential Set, the caller must have AuthPermission("modifyPrivateCredentials").
+    javax.security.auth.Subject subject = new javax.security.auth.Subject(true, principals, emptySet, emptySet);
+    return subject;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAccessTokenAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAccessTokenAssertionFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAccessTokenAssertionFilter.java
new file mode 100644
index 0000000..f7e3725
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAccessTokenAssertionFilter.java
@@ -0,0 +1,164 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.provider.federation.jwt.filter;
+
+import java.io.IOException;
+import java.security.AccessController;
+import java.security.Principal;
+import java.text.ParseException;
+import java.util.HashMap;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.filter.security.AbstractIdentityAssertionFilter;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.provider.federation.jwt.JWTMessages;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+import org.apache.knox.gateway.services.security.token.JWTokenAuthority;
+import org.apache.knox.gateway.services.security.token.TokenServiceException;
+import org.apache.knox.gateway.services.security.token.impl.JWTToken;
+import org.apache.knox.gateway.util.JsonUtils;
+
+public class JWTAccessTokenAssertionFilter extends AbstractIdentityAssertionFilter {
+  private static final String SVC_URL = "svc";
+  private static final String EXPIRES_IN = "expires_in";
+  private static final String TOKEN_TYPE = "token_type";
+  private static final String ACCESS_TOKEN = "access_token";
+  private static final String BEARER = "Bearer ";
+  private static JWTMessages log = MessagesFactory.get( JWTMessages.class );
+  private long validity;
+  private JWTokenAuthority authority = null;
+  private ServiceRegistry sr;
+
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+    super.init(filterConfig);
+    String validityStr = filterConfig.getInitParameter("validity");
+    if (validityStr == null) {
+      validityStr = "3600"; // 1 hr. in secs
+    }
+    validity = Long.parseLong(validityStr);
+
+    GatewayServices services = (GatewayServices) filterConfig.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
+    authority = (JWTokenAuthority) services.getService(GatewayServices.TOKEN_SERVICE);
+    sr = (ServiceRegistry) services.getService(GatewayServices.SERVICE_REGISTRY_SERVICE);
+  }
+  
+  @Override
+  public void doFilter(ServletRequest request, ServletResponse response,
+      FilterChain chain) throws IOException, ServletException {
+    String jsonResponse = null;
+    
+    String header = ((HttpServletRequest) request).getHeader("Authorization");
+    if (header != null && header.startsWith(BEARER)) {
+      // what follows the bearer designator should be the JWT token being used to request or as an access token
+      String wireToken = header.substring(BEARER.length());
+      JWTToken token;
+      try {
+        token = JWTToken.parseToken(wireToken);
+      } catch (ParseException e) {
+        throw new ServletException("ParseException encountered while processing the JWT token: ", e);
+      }
+      // ensure that there is a valid jwt token available and that there isn't a misconfiguration of filters
+      if (token != null) {
+        try {
+          authority.verifyToken(token);
+        }
+        catch (TokenServiceException e) {
+          log.unableToVerifyToken(e);
+        }
+      }
+      else {
+        throw new ServletException("Expected JWT Token not provided as Bearer token");
+      }
+      
+      // authorization of the user for the requested service (and resource?) should have been done by
+      // the JWTFederationFilter - once we get here we can assume that it is authorized and we just need
+      // to assert the identity via an access token
+
+      Subject subject = Subject.getSubject(AccessController.getContext());
+      String principalName = getPrincipalName(subject);
+      principalName = mapper.mapUserPrincipal(principalName);
+      
+      // calculate expiration timestamp: validity * 1000 + currentTimeInMillis
+      long expires = System.currentTimeMillis() + validity * 1000;
+      
+      String serviceName = request.getParameter("service-name");
+      String clusterName = request.getParameter("cluster-name");
+      String accessToken = getAccessToken(principalName, serviceName, expires);
+      
+      String serviceURL = sr.lookupServiceURL(clusterName, serviceName);
+      
+      HashMap<String, Object> map = new HashMap<>();
+      // TODO: populate map from JWT authorization code
+      map.put(ACCESS_TOKEN, accessToken);
+      map.put(TOKEN_TYPE, BEARER);
+      map.put(EXPIRES_IN, expires);
+      
+      // TODO: this url needs to be rewritten when in gateway deployments....
+      map.put(SVC_URL, serviceURL);
+      
+      jsonResponse = JsonUtils.renderAsJsonString(map);
+      
+      response.getWriter().write(jsonResponse);
+      //KNOX-685: response.getWriter().flush();
+      return; // break filter chain
+    }
+    else {
+      // no token provided in header
+      // something is really wrong since the JWTFederationFilter should have verified its existence already
+      // TODO: may have to check cookie and url as well before sending error
+      ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
+      return; //break filter chain
+    }
+  }
+
+  private String getAccessToken(final String principalName, String serviceName, long expires) {
+    String accessToken = null;
+
+    Principal p = new Principal() {
+
+      @Override
+      public String getName() {
+        // TODO Auto-generated method stub
+        return principalName;
+      }
+    };
+    JWTToken token = null;
+    try {
+      token = authority.issueToken(p, serviceName, "RS256", expires);
+      // Coverity CID 1327961
+      if( token != null ) {
+        accessToken = token.toString();
+      }
+    } catch (TokenServiceException e) {
+      log.unableToIssueToken(e);
+    }
+
+    return accessToken;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAuthCodeAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAuthCodeAssertionFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAuthCodeAssertionFilter.java
new file mode 100644
index 0000000..32d0e99
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAuthCodeAssertionFilter.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.knox.gateway.provider.federation.jwt.filter;
+
+import java.io.IOException;
+import java.security.AccessController;
+import java.util.HashMap;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+import org.apache.knox.gateway.filter.security.AbstractIdentityAssertionFilter;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+import org.apache.knox.gateway.services.security.token.JWTokenAuthority;
+import org.apache.knox.gateway.services.security.token.TokenServiceException;
+import org.apache.knox.gateway.services.security.token.impl.JWTToken;
+import org.apache.knox.gateway.util.JsonUtils;
+
+public class JWTAuthCodeAssertionFilter extends AbstractIdentityAssertionFilter {
+  private static final String BEARER = "Bearer ";
+  
+  private JWTokenAuthority authority = null;
+
+  private ServiceRegistry sr;
+
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+    super.init(filterConfig);
+    String validityStr = filterConfig.getInitParameter("validity");
+    if (validityStr == null) {
+      validityStr = "3600"; // 1 hr. in secs
+    }
+//    validity = Long.parseLong(validityStr);
+
+    GatewayServices services = (GatewayServices) filterConfig.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
+    authority = (JWTokenAuthority) services.getService(GatewayServices.TOKEN_SERVICE);
+    sr = (ServiceRegistry) services.getService(GatewayServices.SERVICE_REGISTRY_SERVICE);
+  }
+  
+  @Override
+  public void doFilter(ServletRequest request, ServletResponse response,
+      FilterChain chain) throws IOException, ServletException {
+
+      Subject subject = Subject.getSubject(AccessController.getContext());
+      String principalName = getPrincipalName(subject);
+      principalName = mapper.mapUserPrincipal(principalName);
+      JWTToken authCode;
+      try {
+        authCode = authority.issueToken(subject, "RS256");
+        // get the url for the token service
+        String url = null; 
+        if (sr != null) {
+          url = sr.lookupServiceURL("token", "TGS");
+        }
+        
+        HashMap<String, Object> map = new HashMap<>();
+        // TODO: populate map from JWT authorization code
+        // Coverity CID 1327960
+        if( authCode != null ) {
+          map.put( "iss", authCode.getIssuer() );
+          map.put( "sub", authCode.getPrincipal() );
+          map.put( "aud", authCode.getAudience() );
+          map.put( "exp", authCode.getExpires() );
+          map.put( "code", authCode.toString() );
+        }
+        if (url != null) {
+          map.put("tke", url);
+        }
+        
+        String jsonResponse = JsonUtils.renderAsJsonString(map);
+        
+        response.getWriter().write(jsonResponse);
+        //KNOX-685: response.getWriter().flush();
+      } catch (TokenServiceException e) {
+        // TODO Auto-generated catch block
+        e.printStackTrace();
+      }
+      return; // break filter chain
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTFederationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTFederationFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTFederationFilter.java
new file mode 100644
index 0000000..3850502
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTFederationFilter.java
@@ -0,0 +1,109 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.provider.federation.jwt.filter;
+
+import org.apache.knox.gateway.services.security.token.impl.JWTToken;
+import org.apache.knox.gateway.util.CertificateUtils;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import java.io.IOException;
+import java.text.ParseException;
+
+public class JWTFederationFilter extends AbstractJWTFilter {
+
+  public static final String KNOX_TOKEN_AUDIENCES = "knox.token.audiences";
+  public static final String TOKEN_VERIFICATION_PEM = "knox.token.verification.pem";
+  private static final String KNOX_TOKEN_QUERY_PARAM_NAME = "knox.token.query.param.name";
+  private static final String BEARER = "Bearer ";
+  private String paramName = "knoxtoken";
+
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+      super.init(filterConfig);
+
+    // expected audiences or null
+    String expectedAudiences = filterConfig.getInitParameter(KNOX_TOKEN_AUDIENCES);
+    if (expectedAudiences != null) {
+      audiences = parseExpectedAudiences(expectedAudiences);
+    }
+
+    // query param name for finding the provided knoxtoken
+    String queryParamName = filterConfig.getInitParameter(KNOX_TOKEN_QUERY_PARAM_NAME);
+    if (queryParamName != null) {
+      paramName = queryParamName;
+    }
+
+    // token verification pem
+    String verificationPEM = filterConfig.getInitParameter(TOKEN_VERIFICATION_PEM);
+    // setup the public key of the token issuer for verification
+    if (verificationPEM != null) {
+      publicKey = CertificateUtils.parseRSAPublicKey(verificationPEM);
+    }
+  }
+
+  public void destroy() {
+  }
+
+  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
+      throws IOException, ServletException {
+    String header = ((HttpServletRequest) request).getHeader("Authorization");
+    String wireToken = null;
+    if (header != null && header.startsWith(BEARER)) {
+      // what follows the bearer designator should be the JWT token being used to request or as an access token
+      wireToken = header.substring(BEARER.length());
+    }
+    else {
+      // check for query param
+      wireToken = ((HttpServletRequest) request).getParameter(paramName);
+    }
+    
+    if (wireToken != null) {
+      try {
+        JWTToken token = new JWTToken(wireToken);
+        if (validateToken((HttpServletRequest)request, (HttpServletResponse)response, chain, token)) {
+          Subject subject = createSubjectFromToken(token);
+          continueWithEstablishedSecurityContext(subject, (HttpServletRequest)request, (HttpServletResponse)response, chain);
+        }
+      } catch (ParseException ex) {
+        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
+      }
+    }
+    else {
+      // no token provided in header
+      ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
+    }
+  }
+
+  protected void handleValidationError(HttpServletRequest request, HttpServletResponse response, int status,
+                                       String error) throws IOException {
+    if (error != null) {
+      response.sendError(status, error);   
+    }
+    else {
+      response.sendError(status);
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/SSOCookieFederationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/SSOCookieFederationFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/SSOCookieFederationFilter.java
new file mode 100644
index 0000000..edfdc41
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/SSOCookieFederationFilter.java
@@ -0,0 +1,168 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.provider.federation.jwt.filter;
+
+import java.io.IOException;
+import java.text.ParseException;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.provider.federation.jwt.JWTMessages;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.apache.knox.gateway.services.security.token.impl.JWTToken;
+import org.apache.knox.gateway.util.CertificateUtils;
+
+public class SSOCookieFederationFilter extends AbstractJWTFilter {
+  public static final String SSO_COOKIE_NAME = "sso.cookie.name";
+  public static final String SSO_EXPECTED_AUDIENCES = "sso.expected.audiences";
+  public static final String SSO_AUTHENTICATION_PROVIDER_URL = "sso.authentication.provider.url";
+  public static final String SSO_VERIFICATION_PEM = "sso.token.verification.pem";
+  private static JWTMessages log = MessagesFactory.get( JWTMessages.class );
+  private static final String ORIGINAL_URL_QUERY_PARAM = "originalUrl=";
+  private static final String DEFAULT_SSO_COOKIE_NAME = "hadoop-jwt";
+
+  private String cookieName;
+  private String authenticationProviderUrl;
+
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+    super.init(filterConfig);
+    
+    // configured cookieName
+    cookieName = filterConfig.getInitParameter(SSO_COOKIE_NAME);
+    if (cookieName == null) {
+      cookieName = DEFAULT_SSO_COOKIE_NAME;
+    }
+
+    // expected audiences or null
+    String expectedAudiences = filterConfig.getInitParameter(SSO_EXPECTED_AUDIENCES);
+    if (expectedAudiences != null) {
+      audiences = parseExpectedAudiences(expectedAudiences);
+    }
+
+    // url to SSO authentication provider
+    authenticationProviderUrl = filterConfig.getInitParameter(SSO_AUTHENTICATION_PROVIDER_URL);
+    if (authenticationProviderUrl == null) {
+      log.missingAuthenticationProviderUrlConfiguration();
+      throw new ServletException("Required authentication provider URL is missing.");
+    }
+
+    // token verification pem
+    String verificationPEM = filterConfig.getInitParameter(SSO_VERIFICATION_PEM);
+    // setup the public key of the token issuer for verification
+    if (verificationPEM != null) {
+      publicKey = CertificateUtils.parseRSAPublicKey(verificationPEM);
+    }
+  }
+
+  public void destroy() {
+  }
+
+  @Override
+  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
+      throws IOException, ServletException {
+    String wireToken = null;
+    HttpServletRequest req = (HttpServletRequest) request;
+
+    String loginURL = constructLoginURL(req);
+    wireToken = getJWTFromCookie(req);
+    if (wireToken == null) {
+      if (req.getMethod().equals("OPTIONS")) {
+        // CORS preflight requests to determine allowed origins and related config
+        // must be able to continue without being redirected
+        Subject sub = new Subject();
+        sub.getPrincipals().add(new PrimaryPrincipal("anonymous"));
+        continueWithEstablishedSecurityContext(sub, req, (HttpServletResponse) response, chain);
+      }
+      log.sendRedirectToLoginURL(loginURL);
+      ((HttpServletResponse) response).sendRedirect(loginURL);
+    }
+    else {
+      try {
+        JWTToken token = new JWTToken(wireToken);
+        if (validateToken((HttpServletRequest)request, (HttpServletResponse)response, chain, token)) {
+          Subject subject = createSubjectFromToken(token);
+          continueWithEstablishedSecurityContext(subject, (HttpServletRequest)request, (HttpServletResponse)response, chain);
+        }
+      } catch (ParseException ex) {
+        ((HttpServletResponse) response).sendRedirect(loginURL);
+      }
+    }
+  }
+
+  protected void handleValidationError(HttpServletRequest request, HttpServletResponse response, int status,
+                                       String error) throws IOException {
+    String loginURL = constructLoginURL(request);
+    response.sendRedirect(loginURL);
+  }
+
+  /**
+   * Encapsulate the acquisition of the JWT token from HTTP cookies within the
+   * request.
+   *
+   * @param req servlet request to get the JWT token from
+   * @return serialized JWT token
+   */
+  protected String getJWTFromCookie(HttpServletRequest req) {
+    String serializedJWT = null;
+    Cookie[] cookies = req.getCookies();
+    if (cookies != null) {
+      for (Cookie cookie : cookies) {
+        if (cookieName.equals(cookie.getName())) {
+          log.cookieHasBeenFound(cookieName);
+          serializedJWT = cookie.getValue();
+          break;
+        }
+      }
+    }
+    return serializedJWT;
+  }
+
+  /**
+   * Create the URL to be used for authentication of the user in the absence of
+   * a JWT token within the incoming request.
+   *
+   * @param request for getting the original request URL
+   * @return url to use as login url for redirect
+   */
+  protected String constructLoginURL(HttpServletRequest request) {
+    String delimiter = "?";
+    if (authenticationProviderUrl.contains("?")) {
+      delimiter = "&";
+    }
+    String loginURL = authenticationProviderUrl + delimiter
+        + ORIGINAL_URL_QUERY_PARAM
+        + request.getRequestURL().append(getOriginalQueryString(request));
+    return loginURL;
+  }
+
+  private String getOriginalQueryString(HttpServletRequest request) {
+    String originalQueryString = request.getQueryString();
+    return (originalQueryString == null) ? "" : "?" + originalQueryString;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index cd69d46..0000000
--- a/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,23 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.provider.federation.jwt.deploy.JWTFederationContributor
-org.apache.hadoop.gateway.provider.federation.jwt.deploy.JWTAccessTokenAssertionContributor
-org.apache.hadoop.gateway.provider.federation.jwt.deploy.JWTAuthCodeAssertionContributor
-org.apache.hadoop.gateway.provider.federation.jwt.deploy.AccessTokenFederationContributor
-org.apache.hadoop.gateway.provider.federation.jwt.deploy.SSOCookieFederationContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..0176dd4
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,23 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.provider.federation.jwt.deploy.JWTFederationContributor
+org.apache.knox.gateway.provider.federation.jwt.deploy.JWTAccessTokenAssertionContributor
+org.apache.knox.gateway.provider.federation.jwt.deploy.JWTAuthCodeAssertionContributor
+org.apache.knox.gateway.provider.federation.jwt.deploy.AccessTokenFederationContributor
+org.apache.knox.gateway.provider.federation.jwt.deploy.SSOCookieFederationContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/AbstractJWTFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/AbstractJWTFilterTest.java b/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/AbstractJWTFilterTest.java
deleted file mode 100644
index 26d477f..0000000
--- a/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/AbstractJWTFilterTest.java
+++ /dev/null
@@ -1,490 +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.hadoop.gateway.provider.federation;
-
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.security.AccessController;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.NoSuchAlgorithmException;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import java.security.interfaces.RSAPrivateKey;
-import java.security.interfaces.RSAPublicKey;
-import java.text.MessageFormat;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.ArrayList;
-import java.util.Properties;
-import java.util.Date;
-import java.util.Set;
-
-import javax.security.auth.Subject;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.hadoop.gateway.provider.federation.jwt.filter.AbstractJWTFilter;
-import org.apache.hadoop.gateway.provider.federation.jwt.filter.SSOCookieFederationFilter;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.apache.hadoop.gateway.services.security.impl.X509CertificateUtil;
-import org.apache.hadoop.gateway.services.security.token.JWTokenAuthority;
-import org.apache.hadoop.gateway.services.security.token.TokenServiceException;
-import org.apache.hadoop.gateway.services.security.token.impl.JWT;
-import org.apache.hadoop.gateway.services.security.token.impl.JWTToken;
-import org.easymock.EasyMock;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import com.nimbusds.jose.*;
-import com.nimbusds.jwt.JWTClaimsSet;
-import com.nimbusds.jwt.SignedJWT;
-import com.nimbusds.jose.crypto.RSASSASigner;
-import com.nimbusds.jose.util.Base64URL;
-
-public abstract class AbstractJWTFilterTest  {
-  private static final String SERVICE_URL = "https://localhost:8888/resource";
-  private static final String dnTemplate = "CN={0},OU=Test,O=Hadoop,L=Test,ST=Test,C=US";
-
-  protected AbstractJWTFilter handler = null;
-  protected RSAPublicKey publicKey = null;
-  protected RSAPrivateKey privateKey = null;
-  protected String pem = null;
-
-  protected abstract void setTokenOnRequest(HttpServletRequest request, SignedJWT jwt);
-  protected abstract void setGarbledTokenOnRequest(HttpServletRequest request, SignedJWT jwt);
-  protected abstract String getAudienceProperty();
-  protected abstract String getVerificationPemProperty();
-
-  private String buildDistinguishedName(String hostname) {
-    MessageFormat headerFormatter = new MessageFormat(dnTemplate);
-    String[] paramArray = new String[1];
-    paramArray[0] = hostname;
-    String dn = headerFormatter.format(paramArray);
-    return dn;
-  }
-
-  @Before
-  public void setup() throws Exception, NoSuchAlgorithmException {
-    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
-    kpg.initialize(2048);
-    KeyPair KPair = kpg.generateKeyPair();
-    String dn = buildDistinguishedName(InetAddress.getLocalHost().getHostName());
-    Certificate cert = X509CertificateUtil.generateCertificate(dn, KPair, 365, "SHA1withRSA");
-    byte[] data = cert.getEncoded();
-    Base64 encoder = new Base64( 76, "\n".getBytes( "ASCII" ) );
-    pem = new String(encoder.encodeToString( data ).getBytes( "ASCII" )).trim();
-
-    publicKey = (RSAPublicKey) KPair.getPublic();
-    privateKey = (RSAPrivateKey) KPair.getPrivate();
-  }
-
-  @After
-  public void teardown() throws Exception {
-    handler.destroy();
-  }
-  
-  @Test
-  public void testValidJWT() throws Exception {
-    try {
-      Properties props = getProperties();
-      handler.init(new TestFilterConfig(props));
-
-      SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 5000), privateKey, props);
-
-      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
-      setTokenOnRequest(request, jwt);
-      
-      EasyMock.expect(request.getRequestURL()).andReturn(
-          new StringBuffer(SERVICE_URL)).anyTimes();
-      EasyMock.expect(request.getQueryString()).andReturn(null);
-      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
-      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
-          SERVICE_URL);
-      EasyMock.replay(request);
-
-      TestFilterChain chain = new TestFilterChain();
-      handler.doFilter(request, response, chain);
-      Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == true);
-      Set<PrimaryPrincipal> principals = chain.subject.getPrincipals(PrimaryPrincipal.class);
-      Assert.assertTrue("No PrimaryPrincipal", principals.size() > 0);
-      Assert.assertEquals("Not the expected principal", "alice", ((Principal)principals.toArray()[0]).getName());
-    } catch (ServletException se) {
-      fail("Should NOT have thrown a ServletException.");
-    }
-  }
-  
-  @Test
-  public void testValidAudienceJWT() throws Exception {
-    try {
-      Properties props = getProperties();
-      props.put(getAudienceProperty(), "bar");
-      handler.init(new TestFilterConfig(props));
-
-      SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 5000), privateKey, props);
-
-      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
-      setTokenOnRequest(request, jwt);
-      
-      EasyMock.expect(request.getRequestURL()).andReturn(
-          new StringBuffer(SERVICE_URL)).anyTimes();
-      EasyMock.expect(request.getQueryString()).andReturn(null);
-      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
-      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
-          SERVICE_URL);
-      EasyMock.replay(request);
-
-      TestFilterChain chain = new TestFilterChain();
-      handler.doFilter(request, response, chain);
-      Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == true);
-      Set<PrimaryPrincipal> principals = chain.subject.getPrincipals(PrimaryPrincipal.class);
-      Assert.assertTrue("No PrimaryPrincipal", principals.size() > 0);
-      Assert.assertEquals("Not the expected principal", "alice", ((Principal)principals.toArray()[0]).getName());
-    } catch (ServletException se) {
-      fail("Should NOT have thrown a ServletException.");
-    }
-  }
-
-  @Test
-  public void testInvalidAudienceJWT() throws Exception {
-    try {
-      Properties props = getProperties();
-      props.put(getAudienceProperty(), "foo");
-      props.put("sso.authentication.provider.url", "https://localhost:8443/gateway/knoxsso/api/v1/websso");
-
-      handler.init(new TestFilterConfig(props));
-
-      SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 5000), privateKey, props);
-
-      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
-      setTokenOnRequest(request, jwt);
-      
-      EasyMock.expect(request.getRequestURL()).andReturn(
-          new StringBuffer(SERVICE_URL)).anyTimes();
-      EasyMock.expect(request.getQueryString()).andReturn(null);
-      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
-      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
-          SERVICE_URL);
-      EasyMock.replay(request);
-
-      TestFilterChain chain = new TestFilterChain();
-      handler.doFilter(request, response, chain);
-      Assert.assertTrue("doFilterCalled should not be true.", chain.doFilterCalled == false);
-      Assert.assertTrue("No Subject should be returned.", chain.subject == null);
-    } catch (ServletException se) {
-      fail("Should NOT have thrown a ServletException.");
-    }
-  }
-
-  @Test
-  public void testValidVerificationPEM() throws Exception {
-    try {
-      Properties props = getProperties();
-      
-//      System.out.println("+" + pem + "+");
-
-      props.put(getAudienceProperty(), "bar");
-      props.put("sso.authentication.provider.url", "https://localhost:8443/gateway/knoxsso/api/v1/websso");
-      props.put(getVerificationPemProperty(), pem);
-      handler.init(new TestFilterConfig(props));
-
-      SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() + 50000), privateKey, props);
-
-      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
-      setTokenOnRequest(request, jwt);
-
-      EasyMock.expect(request.getRequestURL()).andReturn(
-          new StringBuffer(SERVICE_URL)).anyTimes();
-      EasyMock.expect(request.getQueryString()).andReturn(null);
-      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
-      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
-          SERVICE_URL);
-      EasyMock.replay(request);
-
-      TestFilterChain chain = new TestFilterChain();
-      handler.doFilter(request, response, chain);
-      Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == true);
-      Set<PrimaryPrincipal> principals = chain.subject.getPrincipals(PrimaryPrincipal.class);
-      Assert.assertTrue("No PrimaryPrincipal", principals.size() > 0);
-      Assert.assertEquals("Not the expected principal", "alice", ((Principal)principals.toArray()[0]).getName());
-    } catch (ServletException se) {
-      fail("Should NOT have thrown a ServletException.");
-    }
-  }
-
-  @Test
-  public void testExpiredJWT() throws Exception {
-    try {
-      Properties props = getProperties();
-      handler.init(new TestFilterConfig(props));
-
-      SignedJWT jwt = getJWT("alice", new Date(new Date().getTime() - 1000), privateKey, props);
-
-      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
-      setTokenOnRequest(request, jwt);
-      
-      EasyMock.expect(request.getRequestURL()).andReturn(
-          new StringBuffer(SERVICE_URL)).anyTimes();
-      EasyMock.expect(request.getQueryString()).andReturn(null);
-      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
-      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
-          SERVICE_URL);
-      EasyMock.replay(request);
-
-      TestFilterChain chain = new TestFilterChain();
-      handler.doFilter(request, response, chain);
-      Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == false);
-      Assert.assertTrue("No Subject should be returned.", chain.subject == null);
-    } catch (ServletException se) {
-      fail("Should NOT have thrown a ServletException.");
-    }
-  }
-  
-  @Test
-  public void testValidJWTNoExpiration() throws Exception {
-    try {
-      Properties props = getProperties();
-      handler.init(new TestFilterConfig(props));
-
-      SignedJWT jwt = getJWT("alice", null, privateKey, props);
-
-      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
-      setTokenOnRequest(request, jwt);
-      
-      EasyMock.expect(request.getRequestURL()).andReturn(
-          new StringBuffer(SERVICE_URL)).anyTimes();
-      EasyMock.expect(request.getQueryString()).andReturn(null);
-      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
-      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
-          SERVICE_URL).anyTimes();
-      EasyMock.replay(request);
-
-      TestFilterChain chain = new TestFilterChain();
-      handler.doFilter(request, response, chain);
-      Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == true);
-      Set<PrimaryPrincipal> principals = chain.subject.getPrincipals(PrimaryPrincipal.class);
-      Assert.assertTrue("No PrimaryPrincipal", principals.size() > 0);
-      Assert.assertEquals("Not the expected principal", "alice", ((Principal)principals.toArray()[0]).getName());
-    } catch (ServletException se) {
-      fail("Should NOT have thrown a ServletException.");
-    }
-  }
-  
-  @Test
-  public void testUnableToParseJWT() throws Exception {
-    try {
-      Properties props = getProperties();
-      handler.init(new TestFilterConfig(props));
-
-      SignedJWT jwt = getJWT("bob",new Date(new Date().getTime() + 5000), privateKey, props);
-
-      HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
-      setGarbledTokenOnRequest(request, jwt);
-
-      EasyMock.expect(request.getRequestURL()).andReturn(
-          new StringBuffer(SERVICE_URL)).anyTimes();
-      EasyMock.expect(request.getQueryString()).andReturn(null);
-      HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);
-      EasyMock.expect(response.encodeRedirectURL(SERVICE_URL)).andReturn(
-          SERVICE_URL).anyTimes();
-      EasyMock.replay(request);
-
-      TestFilterChain chain = new TestFilterChain();
-      handler.doFilter(request, response, chain);
-      Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled == false);
-      Assert.assertTrue("No Subject should be returned.", chain.subject == null);
-    } catch (ServletException se) {
-      fail("Should NOT have thrown a ServletException.");
-    }
-  }
-
-  protected Properties getProperties() {
-    Properties props = new Properties();
-    props.setProperty(
-        SSOCookieFederationFilter.SSO_AUTHENTICATION_PROVIDER_URL,
-        "https://localhost:8443/authserver");
-    return props;
-  }
-
-  protected SignedJWT getJWT(String sub, Date expires, RSAPrivateKey privateKey,
-      Properties props) throws Exception {
-    List<String> aud = new ArrayList<String>();
-    aud.add("bar");
-
-    JWTClaimsSet claims = new JWTClaimsSet.Builder()
-    .issuer("KNOXSSO")
-    .subject(sub)
-    .audience(aud)
-    .expirationTime(expires)
-    .claim("scope", "openid")
-    .build();
-
-    JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).build();
-
-    SignedJWT signedJWT = new SignedJWT(header, claims);
-    Base64URL sigInput = Base64URL.encode(signedJWT.getSigningInput());
-    JWSSigner signer = new RSASSASigner(privateKey);
-
-    signedJWT.sign(signer);
-
-    return signedJWT;
-  }
-
-  protected static class TestFilterConfig implements FilterConfig {
-    Properties props = null;
-
-    public TestFilterConfig(Properties props) {
-      this.props = props;
-    }
-
-    @Override
-    public String getFilterName() {
-      return null;
-    }
-
-    /* (non-Javadoc)
-     * @see javax.servlet.FilterConfig#getServletContext()
-     */
-    @Override
-    public ServletContext getServletContext() {
-//      JWTokenAuthority authority = EasyMock.createNiceMock(JWTokenAuthority.class);
-//      GatewayServices services = EasyMock.createNiceMock(GatewayServices.class);
-//      EasyMock.expect(services.getService("TokenService").andReturn(authority));
-//      ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-//      EasyMock.expect(context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE).andReturn(new DefaultGatewayServices()));
-      return null;
-    }
-
-    /* (non-Javadoc)
-     * @see javax.servlet.FilterConfig#getInitParameter(java.lang.String)
-     */
-    @Override
-    public String getInitParameter(String name) {
-      return props.getProperty(name, null);
-    }
-
-    /* (non-Javadoc)
-     * @see javax.servlet.FilterConfig#getInitParameterNames()
-     */
-    @Override
-    public Enumeration<String> getInitParameterNames() {
-      return null;
-    }
-    
-  }
-  
-  protected static class TestJWTokenAuthority implements JWTokenAuthority {
-
-    /* (non-Javadoc)
-     * @see org.apache.hadoop.gateway.services.security.token.JWTokenAuthority#issueToken(javax.security.auth.Subject, java.lang.String)
-     */
-    @Override
-    public JWTToken issueToken(Subject subject, String algorithm)
-        throws TokenServiceException {
-      // TODO Auto-generated method stub
-      return null;
-    }
-
-    /* (non-Javadoc)
-     * @see org.apache.hadoop.gateway.services.security.token.JWTokenAuthority#issueToken(java.security.Principal, java.lang.String)
-     */
-    @Override
-    public JWTToken issueToken(Principal p, String algorithm)
-        throws TokenServiceException {
-      // TODO Auto-generated method stub
-      return null;
-    }
-
-    /* (non-Javadoc)
-     * @see org.apache.hadoop.gateway.services.security.token.JWTokenAuthority#issueToken(java.security.Principal, java.lang.String, java.lang.String)
-     */
-    @Override
-    public JWTToken issueToken(Principal p, String audience, String algorithm)
-        throws TokenServiceException {
-      return null;
-    }
-
-    /* (non-Javadoc)
-     * @see org.apache.hadoop.gateway.services.security.token.JWTokenAuthority#verifyToken(org.apache.hadoop.gateway.services.security.token.impl.JWTToken)
-     */
-    @Override
-    public boolean verifyToken(JWTToken token) throws TokenServiceException {
-      return true;
-    }
-
-    /* (non-Javadoc)
-     * @see org.apache.hadoop.gateway.services.security.token.JWTokenAuthority#issueToken(java.security.Principal, java.lang.String, java.lang.String, long)
-     */
-    @Override
-    public JWTToken issueToken(Principal p, String audience, String algorithm,
-        long expires) throws TokenServiceException {
-      return null;
-    }
-
-    @Override
-    public JWTToken issueToken(Principal p, List<String> audiences, String algorithm,
-        long expires) throws TokenServiceException {
-      return null;
-    }
-
-    /* (non-Javadoc)
-     * @see org.apache.hadoop.gateway.services.security.token.JWTokenAuthority#issueToken(java.security.Principal, java.lang.String, long)
-     */
-    @Override
-    public JWT issueToken(Principal p, String audience, long l)
-        throws TokenServiceException {
-      // TODO Auto-generated method stub
-      return null;
-    }
-
-    @Override
-    public boolean verifyToken(JWTToken token, RSAPublicKey publicKey) throws TokenServiceException {
-      // TODO Auto-generated method stub
-      return true;
-    }
-    
-  }
-  
-  protected static class TestFilterChain implements FilterChain {
-    boolean doFilterCalled = false;
-    Subject subject = null;
-
-    /* (non-Javadoc)
-     * @see javax.servlet.FilterChain#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
-     */
-    @Override
-    public void doFilter(ServletRequest request, ServletResponse response)
-        throws IOException, ServletException {
-      doFilterCalled = true;
-      
-      subject = Subject.getSubject( AccessController.getContext() );
-    }
-    
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTFederationFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTFederationFilterTest.java b/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTFederationFilterTest.java
deleted file mode 100644
index 8d41423..0000000
--- a/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTFederationFilterTest.java
+++ /dev/null
@@ -1,67 +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.hadoop.gateway.provider.federation;
-
-import java.security.NoSuchAlgorithmException;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.hadoop.gateway.provider.federation.jwt.filter.JWTFederationFilter;
-import org.apache.hadoop.gateway.services.security.token.JWTokenAuthority;
-import org.easymock.EasyMock;
-import org.junit.Before;
-
-import com.nimbusds.jwt.SignedJWT;
-
-public class JWTFederationFilterTest extends AbstractJWTFilterTest {
-    
-    @Before
-    public void setup() throws Exception, NoSuchAlgorithmException {
-      super.setup();
-      handler = new TestJWTFederationFilter();
-      ((TestJWTFederationFilter) handler).setTokenService(new TestJWTokenAuthority());
-    }
-    
-    protected void setTokenOnRequest(HttpServletRequest request, SignedJWT jwt) {
-      String token = "Bearer " + jwt.serialize();
-      EasyMock.expect(request.getHeader("Authorization")).andReturn(token);
-    }
-    
-    protected void setGarbledTokenOnRequest(HttpServletRequest request, SignedJWT jwt) {
-      String token = "Bearer " + "ljm" + jwt.serialize();
-      EasyMock.expect(request.getHeader("Authorization")).andReturn(token);
-    }
-
-    protected String getAudienceProperty() {
-      return TestJWTFederationFilter.KNOX_TOKEN_AUDIENCES;
-    }
-    
-    private static class TestJWTFederationFilter extends JWTFederationFilter {
-
-      public void setTokenService(JWTokenAuthority ts) {
-        authority = ts;
-      }
-        
-    }
-
-    @Override
-    protected String getVerificationPemProperty() {
-      return TestJWTFederationFilter.TOKEN_VERIFICATION_PEM;
-    };
-    
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTTokenTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTTokenTest.java b/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTTokenTest.java
deleted file mode 100644
index 8d8bcab..0000000
--- a/gateway-provider-security-jwt/src/test/java/org/apache/hadoop/gateway/provider/federation/JWTTokenTest.java
+++ /dev/null
@@ -1,133 +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.hadoop.gateway.provider.federation;
-
-import java.util.ArrayList;
-import junit.framework.TestCase;
-
-import org.apache.hadoop.gateway.services.security.token.impl.JWTToken;
-import org.junit.Test;
-
-public class JWTTokenTest extends TestCase {
-  private static final String JWT_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0MTY5MjkxMDksImp0aSI6ImFhN2Y4ZDBhOTVjIiwic2NvcGVzIjpbInJlcG8iLCJwdWJsaWNfcmVwbyJdfQ.XCEwpBGvOLma4TCoh36FU7XhUbcskygS81HE1uHLf0E";
-  private static final String HEADER = "{\"alg\":\"RS256\", \"type\":\"JWT\"}";
-  private static final String CLAIMS = "{\"iss\": \"gateway\", \"prn\": \"john.doe@example.com\", \"aud\": \"https://login.example.com\", \"exp\": \"1363360913\"}";
-  
-//  public void testTokenParsing() throws Exception {
-//    try {
-//      JWTToken token = JWTToken.parseToken(JWT_TOKEN);
-//      assertEquals(token.getHeader(), HEADER);
-//      assertEquals(token.getClaims(), CLAIMS);
-//      
-//      assertEquals(token.getIssuer(), "gateway");
-//      assertEquals(token.getPrincipal(), "john.doe@example.com");
-//      assertEquals(token.getAudience(), "https://login.example.com");
-//      assertEquals(token.getExpires(), "1363360913");
-//    }
-//    catch (ParseException pe) {
-//      fail("ParseException encountered.");
-//    }
-//  }
-  
-  @Test
-  public void testTokenCreation() throws Exception {
-    String[] claims = new String[4];
-    claims[0] = "KNOXSSO";
-    claims[1] = "john.doe@example.com";
-    claims[2] = "https://login.example.com";
-    claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
-    JWTToken token = new JWTToken("RS256", claims);
-
-    assertEquals("KNOXSSO", token.getIssuer());
-    assertEquals("john.doe@example.com", token.getSubject());
-    assertEquals("https://login.example.com", token.getAudience());
-  }
-
-  @Test
-  public void testTokenCreationWithAudienceListSingle() throws Exception {
-    String[] claims = new String[4];
-    claims[0] = "KNOXSSO";
-    claims[1] = "john.doe@example.com";
-    claims[2] = null;
-    claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
-    ArrayList<String> audiences = new ArrayList<String>();
-    audiences.add("https://login.example.com");
-
-    JWTToken token = new JWTToken("RS256", claims, audiences);
-
-    assertEquals("KNOXSSO", token.getIssuer());
-    assertEquals("john.doe@example.com", token.getSubject());
-    assertEquals("https://login.example.com", token.getAudience());
-    assertEquals(1, token.getAudienceClaims().length);
-  }
-
-  @Test
-  public void testTokenCreationWithAudienceListMultiple() throws Exception {
-    String[] claims = new String[4];
-    claims[0] = "KNOXSSO";
-    claims[1] = "john.doe@example.com";
-    claims[2] = null;
-    claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
-    ArrayList<String> audiences = new ArrayList<String>();
-    audiences.add("https://login.example.com");
-    audiences.add("KNOXSSO");
-
-    JWTToken token = new JWTToken("RS256", claims, audiences);
-
-    assertEquals("KNOXSSO", token.getIssuer());
-    assertEquals("john.doe@example.com", token.getSubject());
-    assertEquals("https://login.example.com", token.getAudience());
-    assertEquals(2, token.getAudienceClaims().length);
-  }
-
-  @Test
-  public void testTokenCreationWithAudienceListCombined() throws Exception {
-    String[] claims = new String[4];
-    claims[0] = "KNOXSSO";
-    claims[1] = "john.doe@example.com";
-    claims[2] = "LJM";
-    claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
-    ArrayList<String> audiences = new ArrayList<String>();
-    audiences.add("https://login.example.com");
-    audiences.add("KNOXSSO");
-
-    JWTToken token = new JWTToken("RS256", claims, audiences);
-
-    assertEquals("KNOXSSO", token.getIssuer());
-    assertEquals("john.doe@example.com", token.getSubject());
-    assertEquals("https://login.example.com", token.getAudience());
-    assertEquals(3, token.getAudienceClaims().length);
-  }
-
-  @Test
-  public void testTokenCreationWithNullAudienceList() throws Exception {
-    String[] claims = new String[4];
-    claims[0] = "KNOXSSO";
-    claims[1] = "john.doe@example.com";
-    claims[2] = null;
-    claims[3] = Long.toString( ( System.currentTimeMillis()/1000 ) + 300);
-    ArrayList<String> audiences = null;
-
-    JWTToken token = new JWTToken("RS256", claims, audiences);
-
-    assertEquals("KNOXSSO", token.getIssuer());
-    assertEquals("john.doe@example.com", token.getSubject());
-    assertEquals(null, token.getAudience());
-    assertEquals(null, token.getAudienceClaims());
-  }
-}


[20/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletFilterTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletFilterTest.java
deleted file mode 100644
index 55ef322..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteServletFilterTest.java
+++ /dev/null
@@ -1,921 +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.hadoop.gateway.filter.rewrite.api;
-
-import com.jayway.jsonassert.JsonAssert;
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.test.TestUtils;
-import org.apache.hadoop.test.log.NoOpAppender;
-import org.apache.hadoop.test.mock.MockInteraction;
-import org.apache.hadoop.test.mock.MockServlet;
-import org.apache.log4j.Appender;
-import org.apache.log4j.Logger;
-import org.eclipse.jetty.http.HttpHeader;
-import org.eclipse.jetty.servlet.FilterHolder;
-import org.eclipse.jetty.servlet.ServletHolder;
-import org.eclipse.jetty.http.HttpTester;
-import org.eclipse.jetty.servlet.ServletTester;
-import org.eclipse.jetty.util.ArrayQueue;
-import org.junit.After;
-import org.junit.Ignore;
-import org.junit.Test;
-
-import javax.servlet.DispatcherType;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.nio.charset.Charset;
-import java.util.EnumSet;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.anyOf;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.fail;
-import static org.xmlmatchers.XmlMatchers.hasXPath;
-import static org.xmlmatchers.transform.XmlConverters.the;
-
-public class UrlRewriteServletFilterTest {
-
-  Logger LOG = Logger.getLogger(UrlRewriteServletFilterTest.class);
-
-  private ServletTester server;
-  private HttpTester.Request request;
-  private HttpTester.Response response;
-  private ArrayQueue<MockInteraction> interactions;
-  private MockInteraction interaction;
-
-  private static URL getTestResource( String name ) {
-    name = UrlRewriteServletFilterTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
-    URL url = ClassLoader.getSystemResource( name );
-    return url;
-  }
-
-  public void setUp( Map<String,String> initParams ) throws Exception {
-    String descriptorUrl = getTestResource( "rewrite.xml" ).toExternalForm();
-
-    server = new ServletTester();
-    server.setContextPath( "/" );
-    server.getContext().addEventListener( new UrlRewriteServletContextListener() );
-    server.getContext().setInitParameter(
-        UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );
-
-    FilterHolder setupFilter = server.addFilter( SetupFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
-    setupFilter.setFilter( new SetupFilter() );
-    FilterHolder rewriteFilter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
-    if( initParams != null ) {
-      for( Map.Entry<String,String> entry : initParams.entrySet() ) {
-        rewriteFilter.setInitParameter( entry.getKey(), entry.getValue() );
-      }
-    }
-    rewriteFilter.setFilter( new UrlRewriteServletFilter() );
-
-    interactions = new ArrayQueue<MockInteraction>();
-
-    ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
-    servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );
-
-    server.start();
-
-    interaction = new MockInteraction();
-    request = HttpTester.newRequest();
-    response = null;
-  }
-
-  @After
-  public void tearDown() throws Exception {
-    if( server != null ) {
-      server.stop();
-    }
-  }
-
-  @Test
-  public void testInboundRequestUrlRewrite() throws Exception {
-    setUp( null );
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "GET" )
-        .requestUrl( "http://mock-host:1/test-output-path-1" );
-    interaction.respond().status( 200 ).content( "test-response-content".getBytes() );
-    interactions.add( interaction );
-    // Create the client request.
-    request.setMethod( "GET" );
-    request.setURI( "/test-input-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "mock-host:1" );
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), is( 200 ) );
-    assertThat( response.getContent(), is( "test-response-content" ) );
-  }
-
-  @Test
-  public void testInboundHeaderRewrite() throws Exception {
-    setUp( null );
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "GET" )
-        .requestUrl( "http://mock-host:1/test-output-path-1" )
-        .header( "Location", "http://mock-host:1/test-output-path-1" );
-    interaction.respond()
-        .status( 200 );
-    interactions.add( interaction );
-    // Create the client request.
-    request.setMethod( "GET" );
-    request.setURI( "/test-input-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "mock-host:1" );
-    request.setHeader( "Location", "http://mock-host:1/test-input-path" );
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), is( 200 ) );
-  }
-
-  @Test
-  public void testOutboundHeaderRewrite() throws Exception {
-    setUp( null );
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "GET" )
-        .requestUrl( "http://mock-host:1/test-output-path-1" );
-    interaction.respond()
-        .status( 201 )
-        .header( "Location", "http://mock-host:1/test-input-path" );
-    interactions.add( interaction );
-    // Create the client request.
-    request.setMethod( "GET" );
-    request.setURI( "/test-input-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "mock-host:1" );
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), is( 201 ) );
-    assertThat( response.get( HttpHeader.LOCATION ), is( "http://mock-host:1/test-output-path-1" ) );
-  }
-
-//  @Ignore( "Need to figure out how to handle cookies since domain and path are separate." )
-//  @Test
-//  public void testRequestCookieRewrite() throws Exception {
-//    setUp( null );
-//    // Setup the server side request/response interaction.
-//    interaction.expect()
-//        .method( "GET" )
-//        .requestUrl( "http://mock-host:1/test-output-path-1" )
-//        .header( "Cookie", "cookie-name=cookie-value; Domain=docs.foo.com; Path=/accounts; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly" );
-//    interaction.respond()
-//        .status( 201 );
-//    interactions.add( interaction );
-//    // Create the client request.
-//    request.setMethod( "GET" );
-//    request.setURI( "/test-input-path" );
-//    //request.setVersion( "HTTP/1.1" );
-//    request.setHeader( "Host", "mock-host:1" );
-//    request.setHeader( "Cookie", "cookie-name=cookie-value; Domain=docs.foo.com; Path=/accounts; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly" );
-//
-//    // Execute the request.
-//    response = TestUtils.execute( server, request );
-//
-//    // Test the results.
-//    assertThat( response.getStatus(), is( 201 ) );
-//    fail( "TODO" );
-//  }
-
-//  @Ignore( "Need to figure out how to handle cookies since domain and path are separate." )
-//  @Test
-//  public void testResponseCookieRewrite() throws Exception {
-//    setUp( null );
-//    // Setup the server side request/response interaction.
-//    interaction.expect()
-//        .method( "GET" )
-//        .requestUrl( "http://mock-host:1/test-output-path-1" );
-//    interaction.respond()
-//        .status( 200 )
-//        .header( "Set-Cookie", "cookie-name=cookie-value; Domain=docs.foo.com; Path=/accounts; Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; HttpOnly" );
-//    interactions.add( interaction );
-//    // Create the client request.
-//    request.setMethod( "GET" );
-//    request.setURI( "/test-input-path" );
-//    //request.setVersion( "HTTP/1.1" );
-//    request.setHeader( "Host", "mock-host:1" );
-//
-//    // Execute the request.
-//    response = TestUtils.execute( server, request );
-//
-//    // Test the results.
-//    assertThat( response.getStatus(), is( 200 ) );
-//    assertThat( response.get( HttpHeader.SET_COOKIE ), is( "TODO" ) );
-//    fail( "TODO" );
-//  }
-
-  @Test
-  public void testInboundJsonBodyRewrite() throws Exception {
-    setUp( null );
-
-    String inputJson = "{\"url\":\"http://mock-host:1/test-input-path\"}";
-    String outputJson = "{\"url\":\"http://mock-host:1/test-output-path-1\"}";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "PUT" )
-        .requestUrl( "http://mock-host:1/test-output-path-1" )
-        .content( outputJson, Charset.forName( "UTF-8" ) );
-    interaction.respond()
-        .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "PUT" );
-    request.setURI( "/test-input-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "mock-host:1" );
-    request.setHeader( "Content-Type", "application/json; charset=UTF-8" );
-    request.setContent( inputJson );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), is( 200 ) );
-  }
-
-  @Test
-  public void testInboundXmlBodyRewrite() throws Exception {
-    setUp( null );
-    String input = "<root attribute=\"http://mock-host:1/test-input-path\">http://mock-host:1/test-input-path</root>";
-    String output = null;
-    if(System.getProperty("java.vendor").contains("IBM")){
-      output = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><root attribute=\"http://mock-host:1/test-output-path-1\">http://mock-host:1/test-output-path-1</root>";
-    }else {
-      output = "<?xml version=\"1.0\" standalone=\"no\"?><root attribute=\"http://mock-host:1/test-output-path-1\">http://mock-host:1/test-output-path-1</root>";
-    }
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "PUT" )
-        .requestUrl( "http://mock-host:1/test-output-path-1" )
-        .content( output, Charset.forName( "UTF-8" ) );
-    interaction.respond()
-        .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "PUT" );
-    request.setURI( "/test-input-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "mock-host:1" );
-    request.setHeader( "Content-Type", "application/xml; charset=UTF-8" );
-    request.setContent( input );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), is( 200 ) );
-  }
-
-  // MatcherAssert.assertThat( XmlConverters.the( outputHtml ), XmlMatchers.hasXPath( "/html" ) );
-  @Test
-  public void testOutboundJsonBodyRewrite() throws Exception {
-    setUp( null );
-
-    String input = "{\"url\":\"http://mock-host:1/test-input-path\"}";
-    String expect = "{\"url\":\"http://mock-host:1/test-output-path-1\"}";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "PUT" )
-        .requestUrl( "http://mock-host:1/test-output-path-1" );
-    interaction.respond()
-        .status( 200 )
-        .contentType( "application/json" )
-        .content( input, Charset.forName( "UTF-8" ) );
-    interactions.add( interaction );
-    request.setMethod( "PUT" );
-    request.setURI( "/test-input-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "mock-host:1" );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), is( 200 ) );
-    assertThat( response.getContent(), is( expect ) );
-  }
-
-  @Test
-  public void testOutboundHtmlBodyRewrite() throws Exception {
-    setUp( null );
-
-    String input = "<html><head></head><body><a href=\"http://mock-host:1/test-input-path\">link text</a></body></html>";
-    String output = "<html><head></head><body><a href=\"http://mock-host:1/test-output-path-1\">link text</a></body></html>";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "PUT" )
-        .requestUrl( "http://mock-host:1/test-output-path-1" )
-        .content( output, Charset.forName( "UTF-8" ) );
-    interaction.respond()
-        .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "PUT" );
-    request.setURI( "/test-input-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "mock-host:1" );
-    request.setHeader( "Content-Type", "application/html; charset=UTF-8" );
-    request.setContent( input );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), is( 200 ) );
-  }
-
-  @Test
-  public void testInboundHtmlFormRewrite() throws Exception {
-    setUp( null );
-
-    String input = "Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21&url=http%3A%2F%2Fmock-host%3A1%2Ftest-input-path";
-    String expect = "Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21&url=http%3A%2F%2Fmock-host%3A1%2Ftest-output-path-1";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "PUT" )
-        .requestUrl( "http://mock-host:1/test-output-path-1" )
-        .content( expect, Charset.forName( "UTF-8" ) );
-    interaction.respond()
-        .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "PUT" );
-    request.setURI( "/test-input-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "mock-host:1" );
-    request.setHeader( "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8" );
-    request.setContent( input );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), is( 200 ) );
-  }
-
-  @Test
-  public void testRequestUrlRewriteWithFilterInitParam() throws Exception {
-    Map<String,String> initParams = new HashMap<>();
-    initParams.put( "request.url", "test-rule-2" );
-    setUp( initParams );
-
-    String input = "<root/>";
-    String expect = "<root/>";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "PUT" )
-        .requestUrl( "http://mock-host:42/test-output-path-2" )
-        .contentType( "text/xml" )
-        .characterEncoding( "UTF-8" )
-        .content( expect, Charset.forName( "UTF-8" ) );
-    interaction.respond()
-        .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "PUT" );
-    request.setURI( "/test-input-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "mock-host:42" );
-    request.setHeader( "Content-Type", "text/xml; charset=UTF-8" );
-    request.setContent( input );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), is( 200 ) );
-  }
-
-  @Test
-  public void testRequestHeaderRewriteWithFilterInitParam() throws Exception {
-    Map<String,String> initParams = new HashMap<>();
-    initParams.put( "request.headers", "test-filter-2" );
-    setUp( initParams );
-
-    String input = "<root/>";
-    String expect = "<root/>";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "PUT" )
-        .requestUrl( "http://mock-host:42/test-output-path-1" )
-        .contentType( "text/xml" )
-        .characterEncoding( "UTF-8" )
-        .content( expect, Charset.forName( "UTF-8" ) )
-        .header( "Location", "http://mock-host:42/test-output-path-2" );
-    interaction.respond()
-        .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "PUT" );
-    request.setURI( "/test-input-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "mock-host:42" );
-    request.setHeader( "Location", "http://mock-host:42/test-input-path-1" );
-    request.setHeader( "Content-Type", "text/xml; charset=UTF-8" );
-    request.setContent( input );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), is( 200 ) );
-  }
-
-//  @Ignore( "Not Implemented Yet" )
-//  @Test
-//  public void testRequestCookieRewriteWithFilterInitParam() {
-//    fail( "TODO" );
-//  }
-
-  @Test
-  public void testRequestJsonBodyRewriteWithFilterInitParam() throws Exception {
-    Map<String,String> initParams = new HashMap<>();
-    //initParams.put( "url, "" );
-    initParams.put( "request.body", "test-filter-2" );
-    //initParams.put( "response", "" );
-    setUp( initParams );
-
-    String inputJson = "{\"url\":\"http://mock-host:42/test-input-path-1\"}";
-    String expectJson = "{\"url\":\"http://mock-host:42/test-output-path-2\"}";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "PUT" )
-        .requestUrl( "http://mock-host:42/test-output-path-1" )
-        .contentType( "application/json" )
-        .content( expectJson, Charset.forName( "UTF-8" ) );
-    interaction.respond()
-        .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "PUT" );
-    request.setURI( "/test-input-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "mock-host:42" );
-    request.setHeader( "Content-Type", "application/json; charset=UTF-8" );
-    request.setContent( inputJson );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), is( 200 ) );
-  }
-
-  @Test
-  public void testRequestXmlBodyRewriteWithFilterInitParam() throws Exception {
-    Map<String,String> initParams = new HashMap<>();
-    initParams.put( "request.body", "test-filter-2" );
-    setUp( initParams );
-
-    String input = "<root url='http://mock-host:42/test-input-path-1'><url>http://mock-host:42/test-input-path-1</url></root>";
-    String expect = "<root url='http://mock-host:42/test-output-path-2'><url>http://mock-host:42/test-output-path-2</url></root>";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "PUT" )
-        .requestUrl( "http://mock-host:42/test-output-path-1" )
-        .contentType( "text/xml" )
-        .characterEncoding( "UTF-8" )
-        .content( expect, Charset.forName( "UTF-8" ) );
-    interaction.respond()
-        .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "PUT" );
-    request.setURI( "/test-input-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "mock-host:42" );
-    request.setHeader( "Content-Type", "text/xml; charset=UTF-8" );
-    request.setContent( input );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), is( 200 ) );
-  }
-
-  @Test
-  public void testRequestXmlBodyRewriteWithFilterInitParamForInvalidFilterConfig() throws Exception {
-    Enumeration<Appender> realAppenders = NoOpAppender.setUp();
-    try {
-
-      Map<String,String> initParams = new HashMap<>();
-      initParams.put( "request.body", "test-filter-3" );
-      setUp( initParams );
-
-      String input = "<root url='http://mock-host:42/test-input-path-1'><url>http://mock-host:42/test-input-path-2</url></root>";
-      String expect = "<root url='http://mock-host:42/test-input-path-2'><url>http://mock-host:42/test-input-path-2</url></root>";
-
-      // Setup the server side request/response interaction.
-      interaction.expect()
-          .method( "PUT" )
-          .requestUrl( "http://mock-host:42/test-output-path-1" )
-          .contentType( "text/xml" )
-          .characterEncoding( "UTF-8" )
-          .content( expect, Charset.forName( "UTF-8" ) );
-      interaction.respond()
-          .status( 200 );
-      interactions.add( interaction );
-      request.setMethod( "PUT" );
-      request.setURI( "/test-input-path" );
-      //request.setVersion( "HTTP/1.1" );
-      request.setHeader( "Host", "mock-host:42" );
-      request.setHeader( "Content-Type", "text/xml; charset=UTF-8" );
-      request.setContent( input );
-
-      // Execute the request.
-      response = TestUtils.execute( server, request );
-
-      // Test the results.
-      assertThat( response.getStatus(), is( 500 ) );
-    } finally {
-      NoOpAppender.tearDown( realAppenders );
-    }
-  }
-
-  @Test
-  public void testRequestFormBodyRewriteWithFilterInitParam() throws Exception {
-    Map<String,String> initParams = new HashMap<>();
-    initParams.put( "request.body", "test-filter-2" );
-    setUp( initParams );
-
-    String input = "Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21&url=http%3A%2F%2Fmock-host%3A1%2Ftest-input-path";
-    String expect = "Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21&url=http%3A%2F%2Fmock-host%3A1%2Ftest-output-path-2";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "PUT" )
-        .requestUrl( "http://mock-host:1/test-output-path-1" )
-        .content( expect, Charset.forName( "UTF-8" ) )
-        .characterEncoding( "UTF-8" );
-    interaction.respond()
-        .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "PUT" );
-    request.setURI( "/test-input-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "mock-host:1" );
-    request.setHeader( "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8" );
-    request.setContent( input );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), is( 200 ) );
-  }
-
-  @Test
-  public void testResponseHeaderRewriteWithFilterInitParam() throws Exception {
-    Map<String,String> initParams = new HashMap<>();
-    initParams.put( "response.headers", "test-filter-2" );
-    setUp( initParams );
-
-    String output = "<root url='http://mock-host:42/test-input-path-2'><url>http://mock-host:42/test-input-path-3</url></root>";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "GET" )
-        .requestUrl( "http://mock-host:42/test-output-path-1" );
-    interaction.respond()
-        .content( output, Charset.forName( "UTF-8" ) )
-        .contentType( "text/xml" )
-        .header( "Location", "http://mock-host:42/test-input-path-4" )
-        .status( 307 );
-    interactions.add( interaction );
-    request.setMethod( "GET" );
-    request.setURI( "/test-input-path-1" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "mock-host:42" );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), is( 307 ) );
-    assertThat( response.get( HttpHeader.LOCATION ), is( "http://mock-host:42/test-output-path-2" ) );
-
-    String actual = response.getContent();
-
-    assertThat( the( actual ), hasXPath( "/root/@url", equalTo( "http://mock-host:42/test-output-path-1" ) ) );
-    assertThat( the( actual ), hasXPath( "/root/url/text()", equalTo( "http://mock-host:42/test-output-path-1" ) ) );
-  }
-
-//  @Ignore( "Not Implemented Yet" )
-//  @Test
-//  public void testResponseCookieRewriteWithFilterInitParam() {
-//    fail( "TODO" );
-//  }
-
-  @Test
-  public void testResponseJsonBodyRewriteWithFilterInitParam() throws Exception {
-    Map<String,String> initParams = new HashMap<>();
-    //initParams.put( "url, "" );
-    initParams.put( "response.body", "test-filter-2" );
-    //initParams.put( "response", "" );
-    setUp( initParams );
-
-    String responseJson = "{\"url\":\"http://mock-host:42/test-input-path-1\"}";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "GET" )
-        .requestUrl( "http://mock-host:42/test-output-path-1" );
-    interaction.respond()
-        .contentType( "application/json" )
-        .content( responseJson, Charset.forName( "UTF-8" ) )
-        .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "GET" );
-    request.setURI( "/test-input-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "mock-host:42" );
-    request.setHeader( "Content-Type", "application/json; charset=UTF-8" );
-    request.setContent( responseJson );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    assertThat( response.getStatus(), is( 200 ) );
-    JsonAssert.with( response.getContent() ).assertThat( "$.url", is( "http://mock-host:42/test-output-path-2" ) );
-  }
-
-  @Test
-  public void testResponseHtmlBodyRewriteWithFilterInitParam() throws Exception {
-    Map<String,String> initParams = new HashMap<>();
-    //initParams.put( "url, "" );
-    initParams.put( "response.body", "test-filter-4" );
-    //initParams.put( "response", "" );
-    setUp( initParams );
-
-    String responseHtml = "<!DOCTYPE html>\n" +
-        "<html>\n" +
-        "  <head>\n" +
-        "    <meta charset=\"UTF-8\">\n" +
-        "    <link rel=\"stylesheet\" href=\"pretty.css\">\n" +
-        "    <script src=\"script.js\"></script>\n" +
-        "  </head>\n" +
-        "  <body>\n" +
-        "  </body>\n" +
-        "</html>";
-    String rewrittenResponseHtml = "<!DOCTYPE html>\n" +
-        "<html>\n" +
-        "  <head>\n" +
-        "    <meta charset=\"UTF-8\">\n" +
-        "    <link rel=\"stylesheet\" href=\"http://someotherhost/stylesheets/pretty.css\">\n" +
-        "    <script src=\"script.js\"></script>\n" +
-        "  </head>\n" +
-        "  <body>\n" +
-        "  </body>\n" +
-        "</html>";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "GET" )
-        .requestUrl( "http://mock-host:42/test-output-path-1" );
-    interaction.respond()
-        .contentType( "application/html" )
-        .content( responseHtml, Charset.forName( "UTF-8" ) )
-        .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "GET" );
-    request.setURI( "/test-input-path" );
-    request.setHeader( "Host", "mock-host:42" );
-    request.setHeader( "Content-Type", "application/html" );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    assertThat( response.getStatus(), is( 200 ) );
-    String content = response.getContent();
-    assertThat(content, is(rewrittenResponseHtml));
-  }
-
-  @Test
-  public void testResponseXmlBodyRewriteWithFilterInitParam() throws Exception {
-    Map<String,String> initParams = new HashMap<>();
-    initParams.put( "response.body", "test-filter-2" );
-    setUp( initParams );
-
-    String output = "<root url='http://mock-host:42/test-input-path-1'><url>http://mock-host:42/test-input-path-1</url></root>";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "GET" )
-        .requestUrl( "http://mock-host:42/test-output-path-1" );
-    interaction.respond()
-        .content( output, Charset.forName( "UTF-8" ) )
-        .contentType( "text/xml" )
-        .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "GET" );
-    request.setURI( "/test-input-path" );
-    request.setVersion( "HTTP/1.0" );
-    request.setHeader( "Host", "mock-host:42" );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), is( 200 ) );
-
-    String actual = response.getContent();
-
-    assertThat( the( actual ), hasXPath( "/root/@url", equalTo( "http://mock-host:42/test-output-path-2" ) ) );
-    assertThat( the( actual ), hasXPath( "/root/url/text()", equalTo( "http://mock-host:42/test-output-path-2" ) ) );
-  }
-
-  @Test
-  public void testResponseHtmlBodyRewriteCSSImport() throws Exception {
-    Map<String,String> initParams = new HashMap<>();
-    //initParams.put( "url, "" );
-    initParams.put( "response.body", "test-filter-5" );
-    //initParams.put( "response", "" );
-    setUp( initParams );
-
-    String responseHtml = "<html>" +
-                          "  <head>" +
-                          "    <style type=\"text/css\">@import \"pretty.css\";</style>" +
-                          "  </head>" +
-                          "</html>";
-    String responseHtmlOne = "<html>" +
-                          "  <head>" +
-                          "    <style type=\"text/css\">@import \"http://0.0.0.0:0/stylesheets/pretty.css\";</style>" +
-                          "  </head>" +
-                          "</html>";
-    String responseHtmlTwo = "<html>" +
-                          "  <head>" +
-                          "    <style type=\"text/css\">@import \"http://localhost:0/stylesheets/pretty.css\";</style>" +
-                          "  </head>" +
-                          "</html>";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-               .method( "GET" )
-               .requestUrl( "http://mock-host:42/test-output-path-1" );
-    interaction.respond()
-               .contentType( "application/html" )
-               .content( responseHtml, Charset.forName( "UTF-8" ) )
-               .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "GET" );
-    request.setURI( "/test-input-path" );
-    request.setHeader( "Host", "mock-host:42" );
-    request.setHeader( "Content-Type", "application/html" );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    assertThat( response.getStatus(), is( 200 ) );
-    String content = response.getContent();
-//    assertThat( the( content ), hasXPath( "//style/text()", equalTo( "@import \\\"http://0.0.0.0:0/stylesheets/pretty.css\\\";" ) ) );
-    assertThat(content, anyOf( is(responseHtmlOne), is(responseHtmlTwo)));
-  }
-
-  /**
-   * Test the prefix function
-   * @see KNOX-994
-   * @since 0.14.0
-   */
-  @Test
-  public void testResponseHtmlBodyRewritePrefixFunctionTestPrefix() throws Exception {
-
-    Map<String,String> initParams = new HashMap<>();
-    initParams.put( "response.body", "test-filter-6" );
-    setUp( initParams );
-
-    String responseHtml = "<html><div src=\"'components/navbar/navbar.html?v=1496201914075\"></div></html>";
-    String responseHtmlOne = "<html><div src=\"'http://0.0.0.0:0/zeppelin/components/navbar/navbar.html?v=1496201914075\"></div></html>";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "GET" )
-        .requestUrl( "http://mock-host:42/test-output-path-1" );
-    interaction.respond()
-        .contentType( "application/html" )
-        .content( responseHtml, Charset.forName( "UTF-8" ) )
-        .status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "GET" );
-    request.setURI( "/test-input-path" );
-    request.setHeader( "Host", "mock-host:42" );
-    request.setHeader( "Content-Type", "application/html" );
-
-    // Execute the request.
-    response = TestUtils.execute( server, request );
-
-    assertThat( response.getStatus(), is( 200 ) );
-    String content = response.getContent();
-
-    assertThat(content,  is(responseHtmlOne));
-
-  }
-
-
-  /**
-   * See KNOX-791
-   * @since 0.11.0
-   * @throws Exception
-   */
-  @Test
-  public void testResponseHtmlAttributeEscaping() throws Exception {
-    final Map<String, String> initParams = new HashMap<>();
-    initParams.put("response.body", "test-filter-4");
-    setUp(initParams);
-
-    final String responseHtml = "<!DOCTYPE html>\n" + "<html>\n" + "  <head>\n"
-        + "    <meta charset=\"UTF-8\">\n"
-        + "    <link rel=\"stylesheet\" href=\"pretty.css\">\n"
-        + "    <script escaped-data=\"&lt;&gt;\" src=\"script.js\"></script>\n"
-        + "  </head>\n" + "  <body>\n" + "  </body>\n" + "</html>";
-    final String rewrittenResponseHtml = "<!DOCTYPE html>\n" + "<html>\n"
-        + "  <head>\n" + "    <meta charset=\"UTF-8\">\n"
-        + "    <link rel=\"stylesheet\" href=\"http://someotherhost/stylesheets/pretty.css\">\n"
-        + "    <script escaped-data=\"&lt;&gt;\" src=\"script.js\"></script>\n"
-        + "  </head>\n" + "  <body>\n" + "  </body>\n" + "</html>";
-
-    // Setup the server side request/response interaction.
-    interaction.expect().method("GET")
-        .requestUrl("http://mock-host:42/test-output-path-1");
-    interaction.respond().contentType("application/html")
-        .content(responseHtml, Charset.forName("UTF-8")).status(200);
-    interactions.add(interaction);
-    request.setMethod("GET");
-    request.setURI("/test-input-path");
-    request.setHeader("Host", "mock-host:42");
-    request.setHeader("Content-Type", "application/html");
-
-    // Execute the request.
-    response = TestUtils.execute(server, request);
-
-    assertThat(response.getStatus(), is(200));
-    String content = response.getContent();
-    assertThat(content, is(rewrittenResponseHtml));
-  }
-  
-
-  private static class SetupFilter implements Filter {
-    @Override
-    public void init( FilterConfig filterConfig ) throws ServletException {
-    }
-
-    @Override
-    public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException {
-      HttpServletRequest httpRequest = ((HttpServletRequest)request);
-      StringBuffer sourceUrl = httpRequest.getRequestURL();
-      String queryString = httpRequest.getQueryString();
-      if( queryString != null ) {
-        sourceUrl.append( "?" );
-        sourceUrl.append( queryString );
-      }
-      try {
-        request.setAttribute(
-            AbstractGatewayFilter.SOURCE_REQUEST_URL_ATTRIBUTE_NAME,
-            Parser.parseLiteral( sourceUrl.toString() ) );
-      } catch( URISyntaxException e ) {
-        throw new ServletException( e );
-      }
-      chain.doFilter( request, response );
-    }
-
-    @Override
-    public void destroy() {
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/CookieScopeResponseWrapperTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/CookieScopeResponseWrapperTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/CookieScopeResponseWrapperTest.java
deleted file mode 100644
index c03f057..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/CookieScopeResponseWrapperTest.java
+++ /dev/null
@@ -1,91 +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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.filter.rewrite.impl;
-
-import org.easymock.Capture;
-import org.easymock.EasyMock;
-import org.easymock.EasyMockSupport;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.servlet.http.HttpServletResponse;
-
-public class CookieScopeResponseWrapperTest extends EasyMockSupport {
-
-  private HttpServletResponse mock;
-
-  private Capture<String> captureKey;
-
-  private Capture<String> captureValue;
-
-  @Before
-  public void init(){
-    mock = EasyMock.createNiceMock(HttpServletResponse.class);
-    captureKey = new Capture<>();
-    captureValue = new Capture<>();
-    mock.addHeader( EasyMock.capture(captureKey), EasyMock.capture(captureValue));
-    EasyMock.replay(mock);
-  }
-
-  @Test
-  public void testNoPath() {
-    CookieScopeResponseWrapper underTest = new CookieScopeResponseWrapper(mock, "gw");
-    underTest.addHeader("Set-Cookie", "SESSIONID=jn0zexg59r1jo1n66hd7tg5anl;HttpOnly;");
-
-    Assert.assertEquals("Set-Cookie", captureKey.getValue());
-    Assert.assertEquals("SESSIONID=jn0zexg59r1jo1n66hd7tg5anl;HttpOnly; Path=/gw/;", captureValue.getValue());
-  }
-
-  @Test
-  public void testRootPath() {
-    CookieScopeResponseWrapper underTest = new CookieScopeResponseWrapper(mock, "gw");
-    underTest.addHeader("Set-Cookie", "SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/; HttpOnly;");
-
-    Assert.assertEquals("Set-Cookie", captureKey.getValue());
-    Assert.assertEquals("SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/gw/; HttpOnly;", captureValue.getValue());
-  }
-
-  @Test
-  public void testMultiSegmentPath() {
-    CookieScopeResponseWrapper underTest = new CookieScopeResponseWrapper(mock, "some/path");
-    underTest.addHeader("Set-Cookie", "SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/; HttpOnly;");
-
-    Assert.assertEquals("Set-Cookie", captureKey.getValue());
-    Assert.assertEquals("SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/some/path/; HttpOnly;", captureValue.getValue());
-  }
-
-  @Test
-  public void testAlreadyScopedPath() {
-    CookieScopeResponseWrapper underTest = new CookieScopeResponseWrapper(mock, "some/path");
-    underTest.addHeader("Set-Cookie", "SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/already-scoped/; HttpOnly;");
-
-    Assert.assertEquals("Set-Cookie", captureKey.getValue());
-    Assert.assertEquals("SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/some/path/already-scoped/; HttpOnly;", captureValue.getValue());
-  }
-
-  @Test
-  public void testCaseSensitive() {
-    CookieScopeResponseWrapper underTest = new CookieScopeResponseWrapper(mock, "some/path");
-    underTest.addHeader("set-cookie", "SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/not-touched/; HttpOnly;");
-
-    Assert.assertEquals("set-cookie", captureKey.getValue());
-    Assert.assertEquals("SESSIONID=jn0zexg59r1jo1n66hd7tg5anl; Path=/not-touched/; HttpOnly;", captureValue.getValue());
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest.java
deleted file mode 100644
index e28f692..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest.java
+++ /dev/null
@@ -1,303 +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.hadoop.gateway.filter.rewrite.impl;
-
-import com.jayway.jsonassert.JsonAssert;
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.filter.rewrite.api.FrontendFunctionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletFilter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.test.TestUtils;
-import org.apache.hadoop.test.log.NoOpLogger;
-import org.apache.hadoop.test.mock.MockInteraction;
-import org.apache.hadoop.test.mock.MockServlet;
-import org.apache.http.auth.BasicUserPrincipal;
-import org.easymock.EasyMock;
-import org.eclipse.jetty.http.HttpTester;
-import org.eclipse.jetty.servlet.FilterHolder;
-import org.eclipse.jetty.servlet.ServletHolder;
-import org.eclipse.jetty.servlet.ServletTester;
-import org.eclipse.jetty.util.ArrayQueue;
-import org.eclipse.jetty.util.Attributes;
-import org.eclipse.jetty.util.AttributesMap;
-import org.eclipse.jetty.util.log.Log;
-import org.hamcrest.core.Is;
-import org.junit.Test;
-
-import javax.security.auth.Subject;
-import javax.servlet.DispatcherType;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.nio.charset.Charset;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.anyOf;
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.fail;
-
-public class FrontendFunctionProcessorTest {
-
-  private ServletTester server;
-  private HttpTester.Request request;
-  private HttpTester.Response response;
-  private ArrayQueue<MockInteraction> interactions;
-  private MockInteraction interaction;
-
-  @SuppressWarnings("rawtypes")
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof FrontendFunctionProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + FrontendFunctionProcessor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    FrontendFunctionProcessor processor = new FrontendFunctionProcessor();
-    assertThat( processor.name(), is( "frontend" ) );
-  }
-
-  @Test
-  public void testNullHandling() throws Exception {
-    UrlRewriteEnvironment badEnv = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    UrlRewriteEnvironment goodEnv = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( goodEnv.getAttribute(FrontendFunctionDescriptor.FRONTEND_URI_ATTRIBUTE) ).andReturn( new URI( "http://mock-host:80/mock-root/mock-topo" ) ).anyTimes();
-    EasyMock.replay( badEnv,goodEnv );
-
-    FrontendFunctionProcessor processor = new FrontendFunctionProcessor();
-    try {
-      processor.initialize( null, null );
-    } catch ( IllegalArgumentException e ) {
-      assertThat( e.getMessage(), containsString( "environment" ) );
-    }
-    try {
-      processor.initialize( badEnv, null );
-    } catch ( IllegalArgumentException e ) {
-      assertThat( e.getMessage(), containsString( "org.apache.hadoop.knox.frontend.context.uri" ) );
-    }
-    processor.initialize( goodEnv, null );
-    processor.resolve( null, null );
-  }
-
-  public void setUp( String username, Map<String, String> initParams, Attributes attributes ) throws Exception {
-    ServiceRegistry mockServiceRegistry = EasyMock.createNiceMock( ServiceRegistry.class );
-    EasyMock.expect( mockServiceRegistry.lookupServiceURL( "test-cluster", "NAMENODE" ) ).andReturn( "test-nn-scheme://test-nn-host:411" ).anyTimes();
-    EasyMock.expect( mockServiceRegistry.lookupServiceURL( "test-cluster", "JOBTRACKER" ) ).andReturn( "test-jt-scheme://test-jt-host:511" ).anyTimes();
-
-    GatewayServices mockGatewayServices = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( mockGatewayServices.getService(GatewayServices.SERVICE_REGISTRY_SERVICE) ).andReturn( mockServiceRegistry ).anyTimes();
-
-    EasyMock.replay( mockServiceRegistry, mockGatewayServices );
-
-    String descriptorUrl = TestUtils.getResourceUrl( FrontendFunctionProcessorTest.class, "rewrite.xml" ).toExternalForm();
-
-    Log.setLog( new NoOpLogger() );
-
-    server = new ServletTester();
-    server.setContextPath( "/" );
-    server.getContext().addEventListener( new UrlRewriteServletContextListener() );
-    server.getContext().setInitParameter(
-        UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );
-
-    if( attributes != null ) {
-      server.getContext().setAttributes( attributes );
-    }
-    server.getContext().setAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE, "test-cluster" );
-    server.getContext().setAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE, mockGatewayServices );
-
-    FilterHolder setupFilter = server.addFilter( SetupFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
-    setupFilter.setFilter( new SetupFilter( username ) );
-    FilterHolder rewriteFilter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
-    if( initParams != null ) {
-      for( Map.Entry<String,String> entry : initParams.entrySet() ) {
-        rewriteFilter.setInitParameter( entry.getKey(), entry.getValue() );
-      }
-    }
-    rewriteFilter.setFilter( new UrlRewriteServletFilter() );
-
-    interactions = new ArrayQueue<MockInteraction>();
-
-    ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
-    servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );
-
-    server.start();
-
-    interaction = new MockInteraction();
-    request = HttpTester.newRequest();
-    response = null;
-  }
-
-  @Test
-  public void testFrontendFunctionsOnJsonRequestBody() throws Exception {
-    Map<String,String> initParams = new HashMap<>();
-    initParams.put( "response.body", "test-filter" );
-    setUp( "test-user", initParams, null );
-
-    String input = TestUtils.getResourceString( FrontendFunctionProcessorTest.class, "test-input-body.json", "UTF-8" );
-
-    interaction.expect()
-        .method( "GET" )
-        .requestUrl( "http://test-host:42/test-path" );
-    interaction.respond()
-        .status( 200 )
-        .contentType( "application/json" )
-        .characterEncoding( "UTF-8" )
-        .content( input, Charset.forName( "UTF-8" ) );
-    interactions.add( interaction );
-    request.setMethod( "GET" );
-    request.setURI( "/test-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "test-host:42" );
-
-    response = TestUtils.execute( server, request );
-
-    assertThat( response.getStatus(), Is.is( 200 ) );
-
-    String json = response.getContent();
-
-    // Note: The Jetty ServletTester/HttpTester doesn't return very good values.
-    JsonAssert.with( json ).assertThat( "$.url", anyOf( is( "http://localhost:0" ), is( "http://0.0.0.0:0" ) ) );
-    JsonAssert.with( json ).assertThat( "$.scheme", is( "http" ) );
-    JsonAssert.with( json ).assertThat( "$.host", anyOf( is( "localhost" ), is( "0.0.0.0" ) ) );
-    JsonAssert.with( json ).assertThat( "$.port", is( "0" ) );
-    JsonAssert.with( json ).assertThat( "$.addr", anyOf( is( "localhost:0" ), is( "0.0.0.0:0" ) ) );
-    JsonAssert.with( json ).assertThat( "$.address", anyOf( is( "localhost:0" ), is( "0.0.0.0:0" ) ) );
-    JsonAssert.with( json ).assertThat( "$.path", is( "" ) );
-    JsonAssert.with( json ).assertThat( "$.topology", is( "test-cluster" ) );
-  }
-
-  @Test
-  public void testFrontendFunctionsWithFrontendUriConfigOnJsonRequestBody() throws Exception {
-
-    // This hooks up the filter in rewrite.xml in this class' test resource directory.
-    Map<String,String> initParams = new HashMap<>();
-    initParams.put( "response.body", "test-filter" );
-
-    // This simulates having gateway.frontend.uri in gateway-site.xml
-    Attributes attributes = new AttributesMap(  );
-    attributes.setAttribute( FrontendFunctionDescriptor.FRONTEND_URI_ATTRIBUTE, new URI( "mock-frontend-scheme://mock-frontend-host:777/mock-frontend-path" ) );
-
-    setUp( "test-user", initParams, attributes );
-
-    String input = TestUtils.getResourceString( FrontendFunctionProcessorTest.class, "test-input-body.json", "UTF-8" );
-
-    interaction.expect()
-        .method( "GET" )
-        .requestUrl( "http://test-host:42/test-path" );
-    interaction.respond()
-        .status( 200 )
-        .contentType( "application/json" )
-        .characterEncoding( "UTF-8" )
-        .content( input, Charset.forName( "UTF-8" ) );
-    interactions.add( interaction );
-    request.setMethod( "GET" );
-    request.setURI( "/test-path" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "test-host:42" );
-
-    response = TestUtils.execute( server, request );
-
-    assertThat( response.getStatus(), Is.is( 200 ) );
-
-    String json = response.getContent();
-
-    // Note: The Jetty ServletTester/HttpTester doesn't return very good values.
-    JsonAssert.with( json ).assertThat( "$.url", is( "mock-frontend-scheme://mock-frontend-host:777/mock-frontend-path" ) );
-    JsonAssert.with( json ).assertThat( "$.scheme", is( "mock-frontend-scheme" ) );
-    JsonAssert.with( json ).assertThat( "$.host", is( "mock-frontend-host" ) );
-    JsonAssert.with( json ).assertThat( "$.port", is( "777" ) );
-    JsonAssert.with( json ).assertThat( "$.addr", is( "mock-frontend-host:777" ) );
-    JsonAssert.with( json ).assertThat( "$.address", is( "mock-frontend-host:777" ) );
-    JsonAssert.with( json ).assertThat( "$.path", is( "/mock-frontend-path" ) );
-  }
-
-  private static class SetupFilter implements Filter {
-    private Subject subject;
-
-    public SetupFilter( String userName ) {
-      subject = new Subject();
-      subject.getPrincipals().add( new BasicUserPrincipal( userName ) );
-    }
-
-    @Override
-    public void init( FilterConfig filterConfig ) throws ServletException {
-    }
-
-    @Override
-    public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException {
-      HttpServletRequest httpRequest = ((HttpServletRequest)request);
-      StringBuffer sourceUrl = httpRequest.getRequestURL();
-      String queryString = httpRequest.getQueryString();
-      if( queryString != null ) {
-        sourceUrl.append( "?" );
-        sourceUrl.append( queryString );
-      }
-      try {
-        request.setAttribute(
-            AbstractGatewayFilter.SOURCE_REQUEST_URL_ATTRIBUTE_NAME,
-            Parser.parseLiteral( sourceUrl.toString() ) );
-      } catch( URISyntaxException e ) {
-        throw new ServletException( e );
-      }
-      try {
-        Subject.doAs( subject, new PrivilegedExceptionAction<Void>() {
-          @Override
-          public Void run() throws Exception {
-            chain.doFilter( request, response );
-            return null;
-          }
-        } );
-      } catch( PrivilegedActionException e ) {
-        throw new ServletException( e );
-      }
-    }
-
-    @Override
-    public void destroy() {
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteContextImplTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteContextImplTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteContextImplTest.java
deleted file mode 100644
index cb9b347..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteContextImplTest.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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.util.urltemplate.Params;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-public class UrlRewriteContextImplTest {
-
-  @Test
-  public void testResolve() throws Exception {
-
-    UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( environment.resolve( "test-env-param-name" ) ).andReturn( Arrays.asList( "test-env-param-value" ) ).anyTimes();
-
-    Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "test-ctx-param-name" ) ).andReturn( Arrays.asList( "test-ctx-param-value" ) );
-
-    EasyMock.replay( environment, resolver );
-
-    Map<String,UrlRewriteFunctionProcessor> functions = new HashMap<>();
-
-    UrlRewriter.Direction direction = UrlRewriter.Direction.OUT;
-    Template template = Parser.parseLiteral( "scheme://host:port/dir/file" );
-
-    UrlRewriteContextImpl context = new UrlRewriteContextImpl( environment, resolver, functions, direction, template );
-
-    Params params = context.getParameters();
-    List<String> values = params.resolve( "test-env-param-name" );
-    assertThat( values, notNullValue() );
-    assertThat( values.size(), is( 1 ) );
-    assertThat( values.get( 0 ), is( "test-env-param-value" ) );
-
-    values = params.resolve( "test-ctx-param-name" );
-    assertThat( values, notNullValue() );
-    assertThat( values.size(), is( 1 ) );
-    assertThat( values.get( 0 ), is( "test-ctx-param-value" ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteResponseTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteResponseTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteResponseTest.java
deleted file mode 100644
index 3bd9e10..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteResponseTest.java
+++ /dev/null
@@ -1,171 +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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletFilter;
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-import javax.activation.MimeTypeParseException;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.List;
-import java.util.zip.GZIPInputStream;
-import java.util.zip.GZIPOutputStream;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.IsCollectionContaining.hasItems;
-
-public class UrlRewriteResponseTest {
-
-  @Test
-  public void testResolve() throws Exception {
-
-    UrlRewriteProcessor rewriter = EasyMock.createNiceMock( UrlRewriteProcessor.class );
-
-    ServletContext context = EasyMock.createNiceMock( ServletContext.class );
-    EasyMock.expect( context.getServletContextName() ).andReturn( "test-cluster-name" ).anyTimes();
-    EasyMock.expect( context.getInitParameter( "test-init-param-name" ) ).andReturn( "test-init-param-value" ).anyTimes();
-    EasyMock.expect( context.getAttribute( UrlRewriteServletContextListener.PROCESSOR_ATTRIBUTE_NAME ) ).andReturn( rewriter ).anyTimes();
-
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect( config.getInitParameter( "test-filter-init-param-name" ) ).andReturn( "test-filter-init-param-value" ).anyTimes();
-    EasyMock.expect( config.getServletContext() ).andReturn( context ).anyTimes();
-
-    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
-    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
-
-    EasyMock.replay( rewriter, context, config, request, response );
-
-    UrlRewriteResponse rewriteResponse = new UrlRewriteResponse( config, request, response );
-
-    List<String> names = rewriteResponse.resolve( "test-filter-init-param-name" );
-    assertThat( names.size(), is( 1 ) );
-    assertThat( names.get( 0 ), is( "test-filter-init-param-value" ) );
-  }
-
-  @Test
-  public void testResolveGatewayParams() throws Exception {
-
-    UrlRewriteProcessor rewriter = EasyMock.createNiceMock( UrlRewriteProcessor.class );
-
-    ServletContext context = EasyMock.createNiceMock( ServletContext.class );
-    EasyMock.expect( context.getAttribute( UrlRewriteServletContextListener.PROCESSOR_ATTRIBUTE_NAME ) ).andReturn( rewriter ).anyTimes();
-
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect( config.getServletContext() ).andReturn( context ).anyTimes();
-
-    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
-    EasyMock.expect( request.getScheme() ).andReturn( "mock-scheme" ).anyTimes();
-    EasyMock.expect( request.getLocalName() ).andReturn( "mock-host" ).anyTimes();
-    EasyMock.expect( request.getLocalPort() ).andReturn( 42 ).anyTimes();
-    EasyMock.expect( request.getContextPath() ).andReturn( "/mock-path" ).anyTimes();
-    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
-
-    EasyMock.replay( rewriter, context, config, request, response );
-
-    UrlRewriteResponse rewriteResponse = new UrlRewriteResponse( config, request, response );
-
-    List<String> url = rewriteResponse.resolve( "gateway.url" );
-    assertThat( url, hasItems( new String[]{ "mock-scheme://mock-host:42/mock-path" } ) );
-
-    List<String> scheme = rewriteResponse.resolve( "gateway.scheme" );
-    assertThat( scheme, hasItems( new String[]{ "mock-scheme" } ) );
-
-    List<String> host = rewriteResponse.resolve( "gateway.host" );
-    assertThat( host, hasItems( new String[]{ "mock-host" } ) );
-
-    List<String> port = rewriteResponse.resolve( "gateway.port" );
-    assertThat( port, hasItems( new String[]{ "42" } ) );
-
-    List<String> addr = rewriteResponse.resolve( "gateway.addr" );
-    assertThat( addr, hasItems( new String[]{ "mock-host:42" } ) );
-
-    List<String> address = rewriteResponse.resolve( "gateway.addr" );
-    assertThat( address, hasItems( new String[]{ "mock-host:42" } ) );
-
-    List<String> path = rewriteResponse.resolve( "gateway.path" );
-    assertThat( path, hasItems( new String[]{ "/mock-path" } ) );
-  }
-
-  @Test
-  public void testStreamResponse() throws IOException, MimeTypeParseException {
-    UrlRewriteProcessor rewriter = EasyMock.createNiceMock( UrlRewriteProcessor.class );
-    EasyMock.expect( rewriter.getConfig() ).andReturn( null ).anyTimes();
-
-    ServletContext context = EasyMock.createNiceMock( ServletContext.class );
-    EasyMock.expect( context.getAttribute( UrlRewriteServletContextListener.PROCESSOR_ATTRIBUTE_NAME ) ).andReturn( rewriter ).anyTimes();
-
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect( config.getInitParameter( UrlRewriteServletFilter.RESPONSE_BODY_FILTER_PARAM ) ).andReturn( "test-filter" ).anyTimes();
-    EasyMock.expect( config.getServletContext() ).andReturn( context ).anyTimes();
-
-    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
-    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
-
-    EasyMock.replay( rewriter, context, config, request, response );
-
-    UrlRewriteResponse rewriteResponse = new UrlRewriteResponse( config, request, response );
-
-    String content = "content to test gzip streaming";
-    testStreamResponseGzip ( content, rewriteResponse, false );
-    testStreamResponseGzip ( content, rewriteResponse, true );
-  }
-
-  private void testStreamResponseGzip( String content, UrlRewriteResponse rewriteResponse , boolean isGzip ) throws IOException {
-    File targetDir = new File( System.getProperty( "user.dir" ), "target" );
-    File inputFile = new File( targetDir, "input.test" );
-    File outputFile = new File( targetDir, "output.test" );
-    OutputStream outStream = null, output = null;
-    InputStream inStream = null, input = null;
-    try {
-      outStream = isGzip ? new GZIPOutputStream( new FileOutputStream( inputFile ) ) : new FileOutputStream( inputFile );
-      outStream.write( content.getBytes() );
-      outStream.close();
-
-      input = new FileInputStream( inputFile );
-      output = new FileOutputStream( outputFile );
-      rewriteResponse.streamResponse( input, output );
-
-      inStream = isGzip ? new GZIPInputStream( new FileInputStream( outputFile ) ) : new FileInputStream( outputFile );
-      assertThat( String.valueOf( IOUtils.toCharArray( inStream ) ), is( content ) );
-    } finally {
-      if ( inStream != null ) {
-        inStream.close();
-      }
-      if ( input != null ) {
-        input.close();
-      }
-      inputFile.delete();
-      outputFile.delete();
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorStateTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorStateTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorStateTest.java
deleted file mode 100644
index dd103fa..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorStateTest.java
+++ /dev/null
@@ -1,251 +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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFlowDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepFlow;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-import org.junit.Test;
-
-import java.io.IOException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-public class UrlRewriteStepProcessorStateTest {
-
-  @Test
-  public void testEmpty() {
-    List<UrlRewriteStepProcessorHolder> steps = new ArrayList<UrlRewriteStepProcessorHolder>();
-    UrlRewriteStepProcessorState state = new UrlRewriteStepProcessorState( steps.iterator() );
-
-    assertThat( state.status(), is( UrlRewriteStepStatus.SUCCESS ) );
-    assertThat( state.hasNext(), is( false ) );
-    assertThat( state.hasNextAction(), is( false ) );
-    assertThat( state.hasNextCondition(), is( false ) );
-    assertThat( state.nextAction( UrlRewriteStepStatus.SUCCESS ), nullValue() );
-    assertThat( state.nextCondition( UrlRewriteStepStatus.SUCCESS ), nullValue() );
-  }
-
-  @Test
-  public void testNextAction() throws Exception {
-    UrlRewriteStepProcessorHolder holder;
-    List<UrlRewriteStepProcessorHolder> steps = new ArrayList<UrlRewriteStepProcessorHolder>();
-    holder = new UrlRewriteStepProcessorHolder();
-    holder.initialize( new FakeEnvironment(), new FakeActionDescriptor( "one" ), new FakeActionProcessor( "one" ) );
-    steps.add( holder );
-    holder = new UrlRewriteStepProcessorHolder();
-    holder.initialize( new FakeEnvironment(), new FakeActionDescriptor( "two" ), new FakeActionProcessor( "two" ) );
-    steps.add( holder );
-    UrlRewriteStepProcessorState state = new UrlRewriteStepProcessorState( steps.iterator() );
-    assertThat( state.hasNext(), is( true ) );
-    assertThat( state.hasNextAction(), is( true ) );
-    assertThat( state.hasNextCondition(), is( false ) );
-    assertThat( state.nextCondition( UrlRewriteStepStatus.SUCCESS ), nullValue() );
-
-    holder = state.nextAction( UrlRewriteStepStatus.SUCCESS );
-    assertThat( ((FakeActionDescriptor)holder.getDescriptor()).name, is( "one" ) );
-
-    assertThat( state.hasNext(), is( true ) );
-    assertThat( state.hasNextAction(), is( true ) );
-    assertThat( state.hasNextCondition(), is( false ) );
-    assertThat( state.nextCondition( UrlRewriteStepStatus.SUCCESS ), nullValue() );
-
-    holder = state.nextAction( UrlRewriteStepStatus.SUCCESS );
-    assertThat( ((FakeActionDescriptor)holder.getDescriptor()).name, is( "two" ) );
-
-    assertThat( state.hasNext(), is( false ) );
-    assertThat( state.hasNextAction(), is( false ) );
-    assertThat( state.hasNextCondition(), is( false ) );
-    assertThat( state.nextAction( UrlRewriteStepStatus.SUCCESS ), nullValue() );
-    assertThat( state.nextCondition( UrlRewriteStepStatus.SUCCESS ), nullValue() );
-  }
-
-  @Test
-  public void testNextCondition() throws Exception {
-    UrlRewriteStepProcessorHolder holder;
-    List<UrlRewriteStepProcessorHolder> steps = new ArrayList<UrlRewriteStepProcessorHolder>();
-    holder = new UrlRewriteStepProcessorHolder();
-    holder.initialize( new FakeEnvironment(), new FakeConditionDescriptor( "one" ), new FakeConditionProcessor( "one" ) );
-    steps.add( holder );
-    holder = new UrlRewriteStepProcessorHolder();
-    holder.initialize( new FakeEnvironment(), new FakeConditionDescriptor( "two" ), new FakeConditionProcessor( "two" ) );
-    steps.add( holder );
-    UrlRewriteStepProcessorState state = new UrlRewriteStepProcessorState( steps.iterator() );
-    assertThat( state.hasNext(), is( true ) );
-    assertThat( state.hasNextAction(), is( false ) );
-    assertThat( state.hasNextCondition(), is( true ) );
-    assertThat( state.nextAction( UrlRewriteStepStatus.SUCCESS ), nullValue() );
-
-    holder = state.nextCondition( UrlRewriteStepStatus.SUCCESS );
-    assertThat( ((FakeConditionDescriptor)holder.getDescriptor()).name, is( "one" ) );
-
-    assertThat( state.hasNext(), is( true ) );
-    assertThat( state.hasNextAction(), is( false ) );
-    assertThat( state.hasNextCondition(), is( true ) );
-    assertThat( state.nextAction( UrlRewriteStepStatus.SUCCESS ), nullValue() );
-
-    holder = state.nextCondition( UrlRewriteStepStatus.SUCCESS );
-    assertThat( ((FakeConditionDescriptor)holder.getDescriptor()).name, is( "two" ) );
-
-    assertThat( state.hasNext(), is( false ) );
-    assertThat( state.hasNextAction(), is( false ) );
-    assertThat( state.hasNextCondition(), is( false ) );
-    assertThat( state.nextAction( UrlRewriteStepStatus.SUCCESS ), nullValue() );
-    assertThat( state.nextCondition( UrlRewriteStepStatus.SUCCESS ), nullValue() );
-  }
-
-  public class FakeActionDescriptor implements UrlRewriteStepDescriptor<FakeActionDescriptor> {
-    public String name;
-
-    public FakeActionDescriptor( String name ) {
-      this.name = name;
-    }
-
-    @Override
-    public String type() {
-      return "fake-action";
-    }
-
-    @Override
-    public FakeActionDescriptor type( String type ) {
-      return null;
-    }
-
-  }
-
-  public class FakeActionProcessor implements UrlRewriteStepProcessor<UrlRewriteStepDescriptor<FakeActionDescriptor>> {
-    public String name;
-
-    public FakeActionProcessor( String name ) {
-      this.name = name;
-    }
-
-    @Override
-    public String getType() {
-      return "fake-action";
-    }
-
-    @Override
-    public void initialize( UrlRewriteEnvironment environment, UrlRewriteStepDescriptor<FakeActionDescriptor> descriptor ) throws Exception {
-    }
-
-    @Override
-    public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
-      return null;
-    }
-
-    @Override
-    public void destroy() throws Exception {
-    }
-  }
-
-  public class FakeConditionDescriptor implements UrlRewriteFlowDescriptor<FakeConditionDescriptor> {
-    public String name;
-
-    public FakeConditionDescriptor( String name ) {
-      this.name = name;
-    }
-
-    @Override
-    public UrlRewriteStepFlow flow() {
-      return null;
-    }
-
-    @Override
-    public FakeConditionDescriptor flow( String flow ) {
-      return null;
-    }
-
-    @Override
-    public FakeConditionDescriptor flow( UrlRewriteStepFlow flow ) {
-      return null;
-    }
-
-    @Override
-    public List<UrlRewriteStepDescriptor> steps() {
-      return null;
-    }
-
-    @Override
-    public <T extends UrlRewriteStepDescriptor<?>> T addStep( String type ) {
-      return null;
-    }
-
-    @Override
-    public String type() {
-      return "fake-condition";
-    }
-
-    @Override
-    public FakeConditionDescriptor type( String type ) {
-      return null;
-    }
-  }
-
-  public class FakeConditionProcessor implements UrlRewriteStepProcessor<FakeConditionDescriptor> {
-    public String name;
-
-    public FakeConditionProcessor( String name ) {
-      this.name = name;
-    }
-
-    @Override
-    public String getType() {
-      return "fake-condition";
-    }
-
-    @Override
-    public void initialize( UrlRewriteEnvironment environment, FakeConditionDescriptor descriptor ) throws Exception {
-    }
-
-    @Override
-    public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
-      return null;
-    }
-
-    @Override
-    public void destroy() throws Exception {
-    }
-  }
-
-  private class FakeEnvironment implements UrlRewriteEnvironment {
-    @Override
-    public URL getResource( String name ) throws IOException {
-      return null;
-    }
-
-    @Override
-    public <T> T getAttribute( String name ) {
-      return null;
-    }
-
-    @Override
-    public List<String> resolve( String name ) {
-      return null;
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/gateway.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/gateway.xml b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/gateway.xml
deleted file mode 100644
index cf0a491..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/gateway.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<!--
-   Licensed to the Apache Software Foundation (ASF) under one or more
-   contributor license agreements.  See the NOTICE file distributed with
-   this work for additional information regarding copyright ownership.
-   The ASF licenses this file to You under the Apache License, Version 2.0
-   (the "License"); you may not use this file except in compliance with
-   the License.  You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
--->
-<gateway>
-    <resource>
-        <role>WEBHDFS</role>
-        <pattern>/webhdfs/v1/?**</pattern>
-        ...
-        <filter>
-            <role>rewrite</role>
-            <name>url-rewrite</name>
-            <class>org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletFilter</class>
-            <param><name>request.url</name><value>???????????????</value></param>
-            <param><name>request.header</name><value>???????????????</value></param>
-            <param><name>request.body</name><value>???????????????</value></param>
-        </filter>
-        ...
-    </resource>
-</gateway>
\ No newline at end of file


[16/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorStateTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorStateTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorStateTest.java
new file mode 100644
index 0000000..bf64905
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorStateTest.java
@@ -0,0 +1,255 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFlowDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepFlow;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+import org.hamcrest.CoreMatchers;
+import org.hamcrest.MatcherAssert;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public class UrlRewriteStepProcessorStateTest {
+
+  @Test
+  public void testEmpty() {
+    List<UrlRewriteStepProcessorHolder> steps = new ArrayList<UrlRewriteStepProcessorHolder>();
+    UrlRewriteStepProcessorState state = new UrlRewriteStepProcessorState( steps.iterator() );
+
+    MatcherAssert
+        .assertThat( state.status(), CoreMatchers.is( UrlRewriteStepStatus.SUCCESS ) );
+    assertThat( state.hasNext(), is( false ) );
+    assertThat( state.hasNextAction(), is( false ) );
+    assertThat( state.hasNextCondition(), is( false ) );
+    assertThat( state.nextAction( UrlRewriteStepStatus.SUCCESS ), nullValue() );
+    assertThat( state.nextCondition( UrlRewriteStepStatus.SUCCESS ), nullValue() );
+  }
+
+  @Test
+  public void testNextAction() throws Exception {
+    UrlRewriteStepProcessorHolder holder;
+    List<UrlRewriteStepProcessorHolder> steps = new ArrayList<UrlRewriteStepProcessorHolder>();
+    holder = new UrlRewriteStepProcessorHolder();
+    holder.initialize( new FakeEnvironment(), new FakeActionDescriptor( "one" ), new FakeActionProcessor( "one" ) );
+    steps.add( holder );
+    holder = new UrlRewriteStepProcessorHolder();
+    holder.initialize( new FakeEnvironment(), new FakeActionDescriptor( "two" ), new FakeActionProcessor( "two" ) );
+    steps.add( holder );
+    UrlRewriteStepProcessorState state = new UrlRewriteStepProcessorState( steps.iterator() );
+    assertThat( state.hasNext(), is( true ) );
+    assertThat( state.hasNextAction(), is( true ) );
+    assertThat( state.hasNextCondition(), is( false ) );
+    assertThat( state.nextCondition( UrlRewriteStepStatus.SUCCESS ), nullValue() );
+
+    holder = state.nextAction( UrlRewriteStepStatus.SUCCESS );
+    assertThat( ((FakeActionDescriptor)holder.getDescriptor()).name, is( "one" ) );
+
+    assertThat( state.hasNext(), is( true ) );
+    assertThat( state.hasNextAction(), is( true ) );
+    assertThat( state.hasNextCondition(), is( false ) );
+    assertThat( state.nextCondition( UrlRewriteStepStatus.SUCCESS ), nullValue() );
+
+    holder = state.nextAction( UrlRewriteStepStatus.SUCCESS );
+    assertThat( ((FakeActionDescriptor)holder.getDescriptor()).name, is( "two" ) );
+
+    assertThat( state.hasNext(), is( false ) );
+    assertThat( state.hasNextAction(), is( false ) );
+    assertThat( state.hasNextCondition(), is( false ) );
+    assertThat( state.nextAction( UrlRewriteStepStatus.SUCCESS ), nullValue() );
+    assertThat( state.nextCondition( UrlRewriteStepStatus.SUCCESS ), nullValue() );
+  }
+
+  @Test
+  public void testNextCondition() throws Exception {
+    UrlRewriteStepProcessorHolder holder;
+    List<UrlRewriteStepProcessorHolder> steps = new ArrayList<UrlRewriteStepProcessorHolder>();
+    holder = new UrlRewriteStepProcessorHolder();
+    holder.initialize( new FakeEnvironment(), new FakeConditionDescriptor( "one" ), new FakeConditionProcessor( "one" ) );
+    steps.add( holder );
+    holder = new UrlRewriteStepProcessorHolder();
+    holder.initialize( new FakeEnvironment(), new FakeConditionDescriptor( "two" ), new FakeConditionProcessor( "two" ) );
+    steps.add( holder );
+    UrlRewriteStepProcessorState state = new UrlRewriteStepProcessorState( steps.iterator() );
+    assertThat( state.hasNext(), is( true ) );
+    assertThat( state.hasNextAction(), is( false ) );
+    assertThat( state.hasNextCondition(), is( true ) );
+    assertThat( state.nextAction( UrlRewriteStepStatus.SUCCESS ), nullValue() );
+
+    holder = state.nextCondition( UrlRewriteStepStatus.SUCCESS );
+    assertThat( ((FakeConditionDescriptor)holder.getDescriptor()).name, is( "one" ) );
+
+    assertThat( state.hasNext(), is( true ) );
+    assertThat( state.hasNextAction(), is( false ) );
+    assertThat( state.hasNextCondition(), is( true ) );
+    assertThat( state.nextAction( UrlRewriteStepStatus.SUCCESS ), nullValue() );
+
+    holder = state.nextCondition( UrlRewriteStepStatus.SUCCESS );
+    assertThat( ((FakeConditionDescriptor)holder.getDescriptor()).name, is( "two" ) );
+
+    assertThat( state.hasNext(), is( false ) );
+    assertThat( state.hasNextAction(), is( false ) );
+    assertThat( state.hasNextCondition(), is( false ) );
+    assertThat( state.nextAction( UrlRewriteStepStatus.SUCCESS ), nullValue() );
+    assertThat( state.nextCondition( UrlRewriteStepStatus.SUCCESS ), nullValue() );
+  }
+
+  public class FakeActionDescriptor implements UrlRewriteStepDescriptor<FakeActionDescriptor> {
+    public String name;
+
+    public FakeActionDescriptor( String name ) {
+      this.name = name;
+    }
+
+    @Override
+    public String type() {
+      return "fake-action";
+    }
+
+    @Override
+    public FakeActionDescriptor type( String type ) {
+      return null;
+    }
+
+  }
+
+  public class FakeActionProcessor implements
+      UrlRewriteStepProcessor<UrlRewriteStepDescriptor<FakeActionDescriptor>> {
+    public String name;
+
+    public FakeActionProcessor( String name ) {
+      this.name = name;
+    }
+
+    @Override
+    public String getType() {
+      return "fake-action";
+    }
+
+    @Override
+    public void initialize( UrlRewriteEnvironment environment, UrlRewriteStepDescriptor<FakeActionDescriptor> descriptor ) throws Exception {
+    }
+
+    @Override
+    public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
+      return null;
+    }
+
+    @Override
+    public void destroy() throws Exception {
+    }
+  }
+
+  public class FakeConditionDescriptor implements UrlRewriteFlowDescriptor<FakeConditionDescriptor> {
+    public String name;
+
+    public FakeConditionDescriptor( String name ) {
+      this.name = name;
+    }
+
+    @Override
+    public UrlRewriteStepFlow flow() {
+      return null;
+    }
+
+    @Override
+    public FakeConditionDescriptor flow( String flow ) {
+      return null;
+    }
+
+    @Override
+    public FakeConditionDescriptor flow( UrlRewriteStepFlow flow ) {
+      return null;
+    }
+
+    @Override
+    public List<UrlRewriteStepDescriptor> steps() {
+      return null;
+    }
+
+    @Override
+    public <T extends UrlRewriteStepDescriptor<?>> T addStep( String type ) {
+      return null;
+    }
+
+    @Override
+    public String type() {
+      return "fake-condition";
+    }
+
+    @Override
+    public FakeConditionDescriptor type( String type ) {
+      return null;
+    }
+  }
+
+  public class FakeConditionProcessor implements UrlRewriteStepProcessor<FakeConditionDescriptor> {
+    public String name;
+
+    public FakeConditionProcessor( String name ) {
+      this.name = name;
+    }
+
+    @Override
+    public String getType() {
+      return "fake-condition";
+    }
+
+    @Override
+    public void initialize( UrlRewriteEnvironment environment, FakeConditionDescriptor descriptor ) throws Exception {
+    }
+
+    @Override
+    public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
+      return null;
+    }
+
+    @Override
+    public void destroy() throws Exception {
+    }
+  }
+
+  private class FakeEnvironment implements UrlRewriteEnvironment {
+    @Override
+    public URL getResource( String name ) throws IOException {
+      return null;
+    }
+
+    @Override
+    public <T> T getAttribute( String name ) {
+      return null;
+    }
+
+    @Override
+    public List<String> resolve( String name ) {
+      return null;
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/gateway.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/gateway.xml b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/gateway.xml
new file mode 100644
index 0000000..b95b90a
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/gateway.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!--
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+-->
+<gateway>
+    <resource>
+        <role>WEBHDFS</role>
+        <pattern>/webhdfs/v1/?**</pattern>
+        ...
+        <filter>
+            <role>rewrite</role>
+            <name>url-rewrite</name>
+            <class>org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletFilter</class>
+            <param><name>request.url</name><value>???????????????</value></param>
+            <param><name>request.header</name><value>???????????????</value></param>
+            <param><name>request.body</name><value>???????????????</value></param>
+        </filter>
+        ...
+    </resource>
+</gateway>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlFilterReaderBaseTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlFilterReaderBaseTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlFilterReaderBaseTest.java
new file mode 100644
index 0000000..d146472
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlFilterReaderBaseTest.java
@@ -0,0 +1,765 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.html;
+
+import org.apache.commons.digester3.Digester;
+import org.apache.commons.digester3.ExtendedBaseRules;
+import org.apache.commons.digester3.binder.DigesterLoader;
+import org.apache.commons.io.IOUtils;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepFlow;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteCheckDescriptorExt;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteControlDescriptor;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptor;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptorExt;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteFilterContentDescriptorImpl;
+import org.apache.knox.gateway.filter.rewrite.impl.xml.XmlRewriteRulesDigester;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
+import org.hamcrest.Matchers;
+import org.junit.Before;
+import org.junit.Test;
+import org.xml.sax.SAXException;
+import org.xmlmatchers.namespace.SimpleNamespaceContext;
+
+import javax.xml.namespace.QName;
+import javax.xml.parsers.ParserConfigurationException;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+import static org.hamcrest.CoreMatchers.hasItem;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertEquals;
+import static org.xmlmatchers.XmlMatchers.hasXPath;
+import static org.xmlmatchers.transform.XmlConverters.the;
+
+public class HtmlFilterReaderBaseTest {
+
+  public static class NoopXmlFilterReader extends HtmlFilterReaderBase {
+    public NoopXmlFilterReader( Reader reader ) throws IOException, ParserConfigurationException {
+      super( reader );
+    }
+
+    @Override
+    protected String filterText( QName elementName, String text, String ruleName ) {
+      return text;
+    }
+
+    @Override
+    protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
+      return attributeValue;
+    }
+
+    @Override
+    public String filterValueString( String name, String value, String ruleName ) {
+      return value;
+    }
+  }
+
+  public static class MapXmlFilterReader extends HtmlFilterReaderBase {
+    private Map<String,String> map;
+
+    public MapXmlFilterReader( Reader reader, Map<String,String> map ) throws IOException, ParserConfigurationException {
+      super( reader );
+      this.map = map;
+    }
+
+    @Override
+    protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
+      return map.get( attributeValue.trim() );
+    }
+
+    @Override
+    protected String filterText( QName elementName, String text, String ruleName ) {
+      return map.get( text.trim() );
+    }
+
+    @Override
+    public String filterValueString( String name, String value, String ruleName ) {
+      return map.get( value );
+    }
+  }
+
+  public static class MatchRuleXmlFilterReader extends HtmlFilterReaderBase {
+    private Map<String, Map<String,String>> rules;
+    public MatchRuleXmlFilterReader( Reader reader, Map<String, Map<String,String>> rules, UrlRewriteFilterContentDescriptor config ) throws IOException, ParserConfigurationException {
+      super( reader, config );
+      this.rules = rules;
+    }
+
+    @Override
+    protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
+      return filterValueString( attributeName.getLocalPart(), attributeValue, ruleName );
+    }
+
+    @Override
+    protected String filterText( QName elementName, String text, String ruleName ) {
+      return filterValueString( elementName.getLocalPart(), text, ruleName );
+    }
+
+    @Override
+    public String filterValueString( String name, String value, String ruleName ) {
+      Map<String, String> rule = rules.get( ruleName );
+      if ( rule == null ){
+        return value;
+      }
+      for ( Map.Entry<String, String> entry : rule.entrySet() ) {
+        if ( Pattern.compile( entry.getKey() ).matcher( value ).matches() ) {
+          return entry.getValue();
+        }
+      }
+      return value;
+    }
+  }
+
+  @Test
+  public void testSimple() throws IOException, ParserConfigurationException {
+    String inputXml = "<root/>";
+    StringReader inputReader = new StringReader( inputXml );
+    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
+    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+    assertThat( the( outputHtml ), hasXPath( "/root" ) );
+  }
+
+  @Test
+  public void testSimpleNested() throws IOException, ParserConfigurationException {
+    String inputXml = "<root><child1><child11/><child12/></child1><child2><child21/><child22/></child2></root>";
+    StringReader inputReader = new StringReader( inputXml );
+    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
+    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+    assertThat( the( outputHtml ), hasXPath( "/root" ) );
+    assertThat( the( outputHtml ), hasXPath( "/root/child1" ) );
+    assertThat( the( outputHtml ), hasXPath( "/root/child1/child11" ) );
+    assertThat( the( outputHtml ), hasXPath( "/root/child1/child12" ) );
+    assertThat( the( outputHtml ), hasXPath( "/root/child2" ) );
+    assertThat( the( outputHtml ), hasXPath( "/root/child2/child21" ) );
+    assertThat( the( outputHtml ), hasXPath( "/root/child2/child22" ) );
+  }
+
+  @Test
+  public void testSimpleWithNamespace() throws IOException, ParserConfigurationException {
+    String inputXml = "<ns:root xmlns:ns='http://hortonworks.com/xml/ns'></ns:root>";
+    StringReader inputReader = new StringReader( inputXml );
+    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
+    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+
+    //System.out.println( outputHtml );
+    SimpleNamespaceContext ns = new SimpleNamespaceContext();
+    ns.bind( "ns", "http://hortonworks.com/xml/ns" );
+    assertThat( the( outputHtml ), hasXPath( "/ns:root", ns ) );
+  }
+
+  @Test
+  public void testSimpleTextNode() throws IOException, ParserConfigurationException {
+    String inputXml = "<root>text</root>";
+    StringReader inputReader = new StringReader( inputXml );
+    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
+    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( outputHtml );
+    assertThat( the( outputHtml ), hasXPath( "/root/text()", equalTo( "text" ) ) );
+  }
+
+  @Test
+  public void testSimpleAttribute() throws IOException, ParserConfigurationException {
+    String inputXml = "<root name='value'/>";
+    StringReader inputReader = new StringReader( inputXml );
+    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
+    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( outputHtml );
+    assertThat( the( outputHtml ), hasXPath( "/root/@name", equalTo( "value" ) ) );
+  }
+
+  @Test
+  public void testSimpleBooleanAttribute() throws IOException, ParserConfigurationException {
+    String inputXml = "<root name/>";
+    StringReader inputReader = new StringReader(inputXml);
+    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader(inputReader);
+    String outputHtml = new String(IOUtils.toCharArray(filterReader));
+    assertEquals(inputXml, outputHtml);
+  }
+
+  @Test
+  public void testComplexBooleanAttribute() throws IOException, ParserConfigurationException {
+    String inputXml = "<root boolean non-boolean='value' empty=''/>";
+    StringReader inputReader = new StringReader(inputXml);
+    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader(inputReader);
+    String outputHtml = new String(IOUtils.toCharArray(filterReader));
+    assertEquals(inputXml, outputHtml);
+  }
+
+  @Test
+  public void testMappedText() throws IOException, ParserConfigurationException {
+    Map<String,String> map = new HashMap<>();
+    map.put( "input-text", "output-text" );
+    String inputXml = "<root>input-text</root>";
+    StringReader inputReader = new StringReader( inputXml );
+    HtmlFilterReaderBase filterReader = new MapXmlFilterReader( inputReader, map );
+    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( outputHtml );
+    assertThat( the( outputHtml ), hasXPath( "/root/text()", equalTo( "output-text" ) ) );
+  }
+
+  @Test
+  public void testMappedAttribute() throws IOException, ParserConfigurationException {
+    Map<String,String> map = new HashMap<>();
+    map.put( "input-text", "output-text" );
+    String inputXml = "<root attribute='input-text'/>";
+    StringReader inputReader = new StringReader( inputXml );
+    HtmlFilterReaderBase filterReader = new MapXmlFilterReader( inputReader, map );
+    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( outputHtml );
+    assertThat( the( outputHtml ), hasXPath( "/root/@attribute", equalTo( "output-text" ) ) );
+  }
+
+  @Test
+  public void testCombined() throws IOException, ParserConfigurationException {
+    Map<String,String> map = new HashMap<>();
+    map.put( "attr1-input", "attr1-output" );
+    map.put( "attr2-input", "attr2-output" );
+    map.put( "attr3-input", "attr3-output" );
+    map.put( "attr4-input", "attr4-output" );
+    map.put( "attr5-input", "attr5-output" );
+    map.put( "attr6-input", "attr6-output" );
+    map.put( "attr7-input", "attr7-output" );
+    map.put( "root-input1", "root-output1" );
+    map.put( "root-input2", "root-output2" );
+    map.put( "root-input3", "root-output3" );
+    map.put( "child1-input", "child1-output" );
+    map.put( "child2-input", "child2-output" );
+
+    String inputXml =
+          "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
+            "<!-- Comment -->\n" +
+            "<ns1:root xmlns:ns1='http://hortonworks.com/xml/ns1' attr1='attr1-input' ns1:attr2='attr2-input'>\n" +
+            "  root-input1\n" +
+            "  <child1 attr3='attr3-input' ns1:attr4='attr4-input'>\n" +
+            "    child1-input\n" +
+            "  </child1>\n" +
+            "  root-input2\n" +
+            "  <ns2:child2 xmlns:ns2='http://hortonworks.com/xml/ns2' attr5='attr5-input' ns1:attr6='attr6-input' ns2:attr7='attr7-input'>\n" +
+            "    child2-input\n" +
+            "  </ns2:child2>\n" +
+            "  root-input3\n" +
+            "</ns1:root>";
+    //System.out.println( inputXml );
+
+    StringReader inputReader = new StringReader( inputXml );
+    HtmlFilterReaderBase filterReader = new MapXmlFilterReader( inputReader, map );
+    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( outputXml );
+    //System.out.flush();
+
+    SimpleNamespaceContext ns = new SimpleNamespaceContext();
+    ns.bind( "n1", "http://hortonworks.com/xml/ns1" );
+    ns.bind( "n2", "http://hortonworks.com/xml/ns2" );
+
+    assertThat( the( outputXml ), hasXPath( "/n1:root", ns ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/@attr1", ns, equalTo( "attr1-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/@n1:attr2", ns, equalTo( "attr2-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/text()[1]", ns, equalTo( "root-output1" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/text()[2]", ns, equalTo( "root-output2" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/text()[3]", ns, equalTo( "root-output3" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/child1", ns ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/child1/@attr3", ns, equalTo( "attr3-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/child1/@n1:attr4", ns, equalTo( "attr4-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/child1/text()", ns, equalTo( "child1-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2", ns ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/@attr5", ns, equalTo( "attr5-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/@n1:attr6", ns, equalTo( "attr6-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/@n2:attr7", ns, equalTo( "attr7-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/text()", ns, equalTo( "child2-output" ) ) );
+  }
+
+  @Test
+  public void testSimpleJavaScriptText() throws IOException, ParserConfigurationException {
+    String inputXml = "<root><script type=\"text/javascript\">input-js-text</script></root>";
+    StringReader inputReader = new StringReader( inputXml );
+    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
+    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
+    assertThat( the( outputXml ), hasXPath( "/root/script/text()", equalTo( "input-js-text" ) ) );
+  }
+
+  @Test
+  public void testMatchedJavaScriptText() throws IOException, ParserConfigurationException {
+    Map<String, Map<String, String>> rules = new HashMap<>();
+    Map<String, String> map = new HashMap<>();
+    map.put( "(https?://[^/':,]+:[\\d]+)?/cluster/app", "https://knoxhost:8443/cluster/app" );
+    rules.put( "test-rule", map );
+    String inputXml =
+        "<root>\n" +
+        "  <script type=\"text/javascript\">\n" +
+        "    var appsTableData=[\n" +
+        "      [\"<a href='/cluster/app/application_1436831599487_0008'>application_1436831599487_0008</a>\",\"hdfs\",\"Spark Pi\",\"SPARK\",\"<a href='http://testhost:8088/cluster/app/application_1436831599487_0008'>History</a>\"],\n" +
+        "      [\"<a href='/cluster/app/application_1436831599487_0006'>application_1436831599487_0006</a>\",\"hdfs\",\"Spark Pi\",\"SPARK\",\"<a href='http://testhost:8088/cluster/app/application_1436831599487_0006'>History</a>\"],\n" +
+        "      [\"<a href='/cluster/app/application_1436831599487_0007'>application_1436831599487_0007</a>\",\"hdfs\",\"Spark Pi\",\"SPARK\",\"<a href='http://testhost:8088/cluster/app/application_1436831599487_0007'>History</a>\"]\n" +
+        "    ]\n" +
+        "  </script>\n" +
+        "</root>\n";
+    StringReader inputReader = new StringReader( inputXml );
+    UrlRewriteFilterContentDescriptor config = new UrlRewriteFilterContentDescriptorImpl();
+    config.addApply( "(https?://[^/':,]+:[\\d]+)?/cluster/app", "test-rule" );
+    HtmlFilterReaderBase filterReader = new MatchRuleXmlFilterReader( inputReader, rules, config );
+    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
+    String expectedOutput =
+        "<root>\n" +
+        "  <script type=\"text/javascript\">\n" +
+        "    var appsTableData=[\n" +
+        "      [\"<a href='https://knoxhost:8443/cluster/app/application_1436831599487_0008'>application_1436831599487_0008</a>\",\"hdfs\",\"Spark Pi\",\"SPARK\",\"<a href='https://knoxhost:8443/cluster/app/application_1436831599487_0008'>History</a>\"],\n" +
+        "      [\"<a href='https://knoxhost:8443/cluster/app/application_1436831599487_0006'>application_1436831599487_0006</a>\",\"hdfs\",\"Spark Pi\",\"SPARK\",\"<a href='https://knoxhost:8443/cluster/app/application_1436831599487_0006'>History</a>\"],\n" +
+        "      [\"<a href='https://knoxhost:8443/cluster/app/application_1436831599487_0007'>application_1436831599487_0007</a>\",\"hdfs\",\"Spark Pi\",\"SPARK\",\"<a href='https://knoxhost:8443/cluster/app/application_1436831599487_0007'>History</a>\"]\n" +
+        "    ]\n" +
+        "  </script>\n" +
+        "</root>\n";
+    assertThat( outputXml, is( expectedOutput ) );
+  }
+
+  @Test
+  public void testMRJobHistoryUIJavaScriptText() throws IOException, ParserConfigurationException {
+    Map<String, Map<String, String>> rules = new HashMap<>();
+    Map<String, String> map = new HashMap<>();
+    map.put( "https?://[^/':,]+:[\\d]+", "https://knoxhost:8443/gateway/nodemanagerui/node?host=knoxhost" );
+    rules.put( "test-rule", map );
+    String inputXml =
+        "<root>\n" +
+        "  <script type=\"text/javascript\">\n" +
+        "    var appsTableData=[\n" +
+        "      [\"<a href='http://testhost:8042'>/default-rack/node</a>\",\"<a href='http://testhost:8042'>testhost:8042</a>\"],\n" +
+        "    ]\n" +
+        "  </script>\n" +
+        "</root>\n";
+    StringReader inputReader = new StringReader( inputXml );
+    UrlRewriteFilterContentDescriptor config = new UrlRewriteFilterContentDescriptorImpl();
+    config.addApply("https?://[^/':,]+:[\\d]+", "test-rule");
+    HtmlFilterReaderBase filterReader = new MatchRuleXmlFilterReader( inputReader, rules, config );
+    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
+    String expectedOutput =
+        "<root>\n" +
+        "  <script type=\"text/javascript\">\n" +
+        "    var appsTableData=[\n" +
+        "      [\"<a href='https://knoxhost:8443/gateway/nodemanagerui/node?host=knoxhost'>/default-rack/node</a>\",\"<a href='https://knoxhost:8443/gateway/nodemanagerui/node?host=knoxhost'>testhost:8042</a>\"],\n" +
+        "    ]\n" +
+        "  </script>\n" +
+        "</root>\n";
+    assertThat( outputXml, is( expectedOutput ) );
+  }
+
+  public static class XmlRewriteRulesDescriptorDigesterTest {
+
+    private static DigesterLoader loader = DigesterLoader.newLoader( new XmlRewriteRulesDigester() );
+    private static Digester digester = loader.newDigester( new ExtendedBaseRules() );
+
+    @Before
+    public void setupTest() {
+      digester.setValidating( false );
+    }
+
+    @Test
+    public void testRuleParsing() throws IOException, SAXException {
+      Reader reader = new StringReader( "<rules/>" );
+      UrlRewriteRulesDescriptor config = digester.parse( reader );
+      assertThat( config.getRules().isEmpty(), is( true ) );
+
+      reader = new StringReader( "<rules><rule></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().size(), is( 1 ) );
+      UrlRewriteRuleDescriptor rule = config.getRules().get( 0 );
+      assertThat( rule, notNullValue() );
+      assertThat( rule.name(), nullValue() );
+      assertThat( rule.pattern(), nullValue() );
+      assertThat( rule.directions(), nullValue() );
+      assertThat( rule.flow(), nullValue() );
+
+      reader = new StringReader( "<rules><rule name=\"test-name\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule, notNullValue() );
+      assertThat( rule.name(), is( "test-name" ) );
+      assertThat( rule.pattern(), nullValue() );
+      assertThat( rule.directions(), nullValue() );
+      assertThat( rule.flow(), nullValue() );
+
+      reader = new StringReader( "<rules><rule pattern=\"test-pattern\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule, notNullValue() );
+      assertThat( rule.name(), nullValue() );
+      assertThat( rule.pattern(), is( "test-pattern" ) );
+      assertThat( rule.directions(), nullValue() );
+      assertThat( rule.flow(), nullValue() );
+
+      reader = new StringReader( "<rules><rule dir=\"request\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule, notNullValue() );
+      assertThat( rule.name(), nullValue() );
+      assertThat( rule.pattern(), nullValue() );
+      assertThat( rule.directions().size(), is( 1 ) );
+      assertThat( rule.directions(), Matchers.contains( UrlRewriter.Direction.IN ) );
+      assertThat( rule.flow(), nullValue() );
+
+      reader = new StringReader( "<rules><rule flow=\"all\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule, notNullValue() );
+      assertThat( rule.name(), nullValue() );
+      assertThat( rule.pattern(), nullValue() );
+      assertThat( rule.directions(), nullValue() );
+      assertThat( rule.flow(), Matchers.is( UrlRewriteStepFlow.ALL ) );
+    }
+
+    @Test
+    public void testDirectionParsing() throws IOException, SAXException {
+      Reader reader;
+      UrlRewriteRulesDescriptor config;
+
+      reader = new StringReader( "<rules><rule dir=\"request\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"Request\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"in\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"req\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"Req\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"REQ\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"inbound\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"Inbound\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"INBOUND\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"in\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"In\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"IN\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"i\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"I\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+
+      reader = new StringReader( "<rules><rule dir=\"response\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"Response\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"out\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"res\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"Res\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"RES\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"outbound\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"Outbound\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"OUTBOUND\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"out\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"Out\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"OUT\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"o\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"O\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+
+      reader = new StringReader( "<rules><rule dir=\"request,response\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), hasItem( UrlRewriter.Direction.IN ) );
+      assertThat( config.getRules().get( 0 ).directions(), hasItem( UrlRewriter.Direction.OUT ) );
+    }
+
+    @Test
+    public void testFlowParsing() throws IOException, SAXException {
+      Reader reader;
+      UrlRewriteRulesDescriptor config;
+
+      reader = new StringReader( "<rules><rule dir=\"request\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+    }
+
+    @Test
+    public void testMatchParsing() throws IOException, SAXException {
+      Reader reader;
+      UrlRewriteRulesDescriptor config;
+      UrlRewriteRuleDescriptor rule;
+      UrlRewriteMatchDescriptorExt match;
+      List<? extends UrlRewriteStepDescriptor> steps;
+
+      reader = new StringReader( "<rules><rule><match></match></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config, notNullValue() );
+      assertThat( config.getRules(), notNullValue() );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule.steps(), notNullValue() );
+      assertThat( rule.steps().size(), is( 1 ) );
+      match = (UrlRewriteMatchDescriptorExt)rule.steps().get( 0 );
+      assertThat( match, notNullValue() );
+      //assertThat( match.type(), nullValue() );
+      assertThat( match.operation(), nullValue() );
+      assertThat( match.pattern(), nullValue() );
+
+      reader = new StringReader( "<rules><rule><match type=\"test-type\" op=\"test-op\" pattern=\"test-pattern\"></match></rule></rules>" );
+      config = digester.parse( reader );
+      match = (UrlRewriteMatchDescriptorExt)config.getRules().get( 0 ).steps().get( 0 );
+      //assertThat( match.type(), is("test-type") );
+      assertThat( match.operation(), is( "test-op" ) );
+      assertThat( match.pattern(), is( "test-pattern" ) );
+
+      reader = new StringReader( "<rules><rule name=\"test\"><match><match pattern=\"test-pattern\"></match></match></rule></rules>" );
+      config = digester.parse( reader );
+      steps = ((UrlRewriteMatchDescriptor)config.getRule( "test" ).steps().get( 0 )).steps();
+      assertThat( steps, notNullValue() );
+      assertThat( steps.size(), is( 1 ) );
+      assertThat( steps.get( 0 ), notNullValue() );
+      match = (UrlRewriteMatchDescriptorExt)steps.get( 0 );
+      assertThat( match.pattern(), is( "test-pattern" ) );
+    }
+
+    @Test
+    public void testCheckParsing() throws IOException, SAXException {
+      Reader reader;
+      UrlRewriteRulesDescriptor config;
+      UrlRewriteRuleDescriptor rule;
+      List<UrlRewriteStepDescriptor> steps;
+      UrlRewriteCheckDescriptorExt step;
+
+      reader = new StringReader( "<rules><rule><check></check></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config, notNullValue() );
+      assertThat( config.getRules(), notNullValue() );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule.steps(), notNullValue() );
+      assertThat( rule.steps().size(), is( 1 ) );
+      step = (UrlRewriteCheckDescriptorExt)rule.steps().get( 0 );
+      assertThat( step, notNullValue() );
+      //assertThat( step.type(), nullValue() );
+      assertThat( step.operation(), nullValue() );
+      assertThat( step.input(), nullValue() );
+      assertThat( step.value(), nullValue() );
+
+      reader = new StringReader( "<rules><rule><check type=\"test-type\" op=\"test-op\" input=\"test-input\" value=\"test-value\"></check></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config, notNullValue() );
+      assertThat( config.getRules(), notNullValue() );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule.steps(), notNullValue() );
+      assertThat( rule.steps().size(), is( 1 ) );
+      step = (UrlRewriteCheckDescriptorExt)rule.steps().get( 0 );
+      assertThat( step, notNullValue() );
+      //assertThat( step.type(), is( "test-type" ) );
+      assertThat( step.operation(), is( "test-op" ) );
+      assertThat( step.input(), is( "test-input" ) );
+      assertThat( step.value(), is( "test-value" ) );
+    }
+
+    @Test
+    public void testActionParsing() throws IOException, SAXException {
+      Reader reader;
+      UrlRewriteRulesDescriptor config;
+      UrlRewriteRuleDescriptor rule;
+      UrlRewriteActionDescriptorBase step;
+
+      reader = new StringReader( "<rules><rule><action></action></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config, notNullValue() );
+      assertThat( config.getRules(), notNullValue() );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule.steps(), notNullValue() );
+      assertThat( rule.steps().size(), is( 1 ) );
+      step = (UrlRewriteActionDescriptorBase)rule.steps().get( 0 );
+      assertThat( step, notNullValue() );
+      //assertThat( step.type(), nullValue() );
+      assertThat( step.parameter(), nullValue() );
+
+      reader = new StringReader( "<rules><rule><action type=\"test-type\" param=\"test-param\"></action></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config, notNullValue() );
+      assertThat( config.getRules(), notNullValue() );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule.steps(), notNullValue() );
+      assertThat( rule.steps().size(), is( 1 ) );
+      step = (UrlRewriteActionDescriptorBase)rule.steps().get( 0 );
+      assertThat( step, notNullValue() );
+      //assertThat( step.type(), is( "test-type" ) );
+      assertThat( step.parameter(), is( "test-param" ) );
+    }
+
+    @Test
+    public void testControlParsing() throws IOException, SAXException {
+      Reader reader;
+      UrlRewriteRulesDescriptor config;
+      UrlRewriteRuleDescriptor rule;
+      List<UrlRewriteStepDescriptor> steps;
+
+      reader = new StringReader( "<rules><rule><control></control></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config, notNullValue() );
+      assertThat( config.getRules(), notNullValue() );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule.steps(), notNullValue() );
+      assertThat( rule.steps().size(), is( 1 ) );
+      UrlRewriteControlDescriptor step = (UrlRewriteControlDescriptor)rule.steps().get( 0 );
+      assertThat( step, notNullValue() );
+      assertThat(  step.flow(), nullValue() );
+
+      reader = new StringReader( "<rules><rule><control flow=\"or\"></control></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config, notNullValue() );
+      assertThat( config.getRules(), notNullValue() );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule.steps(), notNullValue() );
+      assertThat( rule.steps().size(), is( 1 ) );
+      step = (UrlRewriteControlDescriptor)rule.steps().get( 0 );
+      assertThat( step, notNullValue() );
+      assertThat( step.flow(), is( UrlRewriteStepFlow.OR ) );
+    }
+  }
+  
+  @Test
+  public void testTagNameLetterCase() throws Exception {
+    String inputXml = "<Root/>";
+    StringReader inputReader = new StringReader( inputXml );
+    
+    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
+    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
+    assertThat( the( outputXml ), hasXPath( "/Root" ) );
+  }
+  
+  @Test
+  public void testXmlWithHtmlTagNames() throws Exception {
+    String inputXml = "<root><br><table name=\"table1\"></table><table name=\"table2\"></table></br></root>";
+    StringReader inputReader = new StringReader( inputXml );
+    
+    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
+    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
+    assertThat( the( outputXml ), hasXPath( "/root/br/table[1]/@name", equalTo( "table1" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/root/br/table[2]/@name", equalTo( "table2" ) ) );
+  }
+
+  private class TestXmlFilterReader extends HtmlFilterReaderBase {
+
+    protected TestXmlFilterReader( Reader reader, UrlRewriteFilterContentDescriptor contentConfig ) throws IOException, ParserConfigurationException {
+      super( reader );
+    }
+
+    @Override
+    protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
+      return "attr:" + ruleName + "{" + attributeValue + "}";
+    }
+
+    @Override
+    protected String filterText( QName elementName, String text, String ruleName ) {
+      return "text:" + ruleName + "{" + text + "}";
+    }
+
+    @Override
+    public String filterValueString( String name, String value, String ruleName ) {
+      return value;
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessorTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessorTest.java
new file mode 100644
index 0000000..e49581b
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessorTest.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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.html;
+
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.fail;
+
+public class HtmlImportFunctionProcessorTest {
+
+  @SuppressWarnings("rawtypes")
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof HtmlImportFunctionProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + HtmlImportFunctionProcessor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    HtmlImportFunctionProcessor processor = new HtmlImportFunctionProcessor();
+    assertThat( processor.name(), is( "import" ) );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlPrefixProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlPrefixProcessorTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlPrefixProcessorTest.java
new file mode 100644
index 0000000..8098719
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlPrefixProcessorTest.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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * 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.knox.gateway.filter.rewrite.impl.html;
+
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.fail;
+
+public class HtmlPrefixProcessorTest {
+
+  public HtmlPrefixProcessorTest() {
+    super();
+  }
+
+  @SuppressWarnings("rawtypes")
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof HtmlPrefixProcessor) {
+        return;
+      }
+    }
+    fail( "Failed to find " + HtmlPrefixProcessor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    HtmlPrefixProcessor processor = new HtmlPrefixProcessor();
+    assertThat( processor.name(), is( "prefix" ) );
+  }
+
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReaderTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReaderTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReaderTest.java
new file mode 100644
index 0000000..1cca640
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReaderTest.java
@@ -0,0 +1,118 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.javascript;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteFilterContentDescriptorImpl;
+
+import org.junit.Test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public class JavaScriptFilterReaderTest {
+  public static class NoopJsFilterReader extends JavaScriptFilterReader {
+    public NoopJsFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException {
+      super( reader, config );
+    }
+
+    @Override
+    public String filterValueString( String name, String value, String ruleName ) {
+      return value;
+    }
+  }
+
+  public static class MatchRuleJsFilterReader extends JavaScriptFilterReader {
+    private Map<String, Map<String,String>> rules;
+    public MatchRuleJsFilterReader( Reader reader, Map<String, Map<String,String>> rules, UrlRewriteFilterContentDescriptor config ) throws IOException {
+      super( reader, config );
+      this.rules = rules;
+    }
+
+    @Override
+    public String filterValueString( String name, String value, String ruleName ) {
+      Map<String, String> rule = rules.get( ruleName );
+      if ( rule == null ) {
+        return value;
+      }
+      for ( Map.Entry<String, String> entry : rule.entrySet() ) {
+        if ( Pattern.compile( entry.getKey() ).matcher( value ).matches() ) {
+          return entry.getValue();
+        }
+      }
+      return value;
+    }
+  }
+
+  @Test
+  public void testSimple() throws IOException {
+    String inputJs = "function load_page() {}\n";
+    StringReader inputReader = new StringReader( inputJs );
+    UrlRewriteFilterContentDescriptor config = new UrlRewriteFilterContentDescriptorImpl();
+    JavaScriptFilterReader filterReader = new NoopJsFilterReader( inputReader, config );
+    String outputJs = new String( IOUtils.toCharArray( filterReader ) );
+    assertThat( outputJs, is ( inputJs ) );
+  }
+
+  @Test
+  public void testSimpleMultipleLines() throws IOException {
+    String inputJs =
+        "var url = '/webhdfs/v1' + abs_path + '?op=GET_BLOCK_LOCATIONS';\n" +
+        "$.ajax({\"url\": url, \"crossDomain\": true}).done(function(data) {}).error(network_error_handler(url));\n";
+    StringReader inputReader = new StringReader( inputJs );
+    UrlRewriteFilterContentDescriptor config = new UrlRewriteFilterContentDescriptorImpl();
+    config.addApply( "/webhdfs/v1", "test-rule" );
+    JavaScriptFilterReader filterReader = new NoopJsFilterReader( inputReader, config );
+    String outputJs = new String( IOUtils.toCharArray( filterReader ) );
+    assertThat( outputJs, is ( inputJs ) );
+  }
+
+  @Test
+  public void testMatchedJsContent() throws IOException {
+    Map<String, Map<String, String>> rules = new HashMap<>();
+    Map<String, String> map = new HashMap<>();
+    map.put( "(https?://[^/':,]+:[\\d]+)?/cluster/app", "https://knoxhost:8443/cluster/app" );
+    map.put( "/webhdfs/v1", "https://knoxhost:8443/webhdfs/v1" );
+    rules.put( "test-rule", map );
+    String inputJs =
+        "var url = '/webhdfs/v1' + abs_path + '?op=GET_BLOCK_LOCATIONS';\n" +
+        "$.ajax({\"url\": url, \"crossDomain\": true}).done(function(data) {\n" +
+        "  var url = http://testhost:8088/cluster/app/application_1436831599487_0001;\n" +
+        "}).error(network_error_handler(url));\n";
+    StringReader inputReader = new StringReader( inputJs );
+    UrlRewriteFilterContentDescriptor config = new UrlRewriteFilterContentDescriptorImpl();
+    config.addApply( "(https?://[^/':,]+:[\\d]+)?/cluster/app", "test-rule" );
+    config.addApply( "/webhdfs/v1", "test-rule" );
+    JavaScriptFilterReader filterReader = new MatchRuleJsFilterReader( inputReader, rules, config );
+    String outputJs = new String( IOUtils.toCharArray( filterReader ) );
+    String expectedOutputJs =
+        "var url = 'https://knoxhost:8443/webhdfs/v1' + abs_path + '?op=GET_BLOCK_LOCATIONS';\n" +
+        "$.ajax({\"url\": url, \"crossDomain\": true}).done(function(data) {\n" +
+        "  var url = https://knoxhost:8443/cluster/app/application_1436831599487_0001;\n" +
+        "}).error(network_error_handler(url));\n";
+    assertThat( outputJs, is ( expectedOutputJs ) );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest.java
new file mode 100644
index 0000000..1378fef
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest.java
@@ -0,0 +1,363 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.json;
+
+import com.jayway.jsonassert.JsonAssert;
+import org.apache.commons.io.IOUtils;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterBufferDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterDetectDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptorFactory;
+import org.apache.hadoop.test.TestUtils;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringReader;
+import java.nio.charset.Charset;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.containsString;
+import static org.junit.Assert.fail;
+
+public class JsonFilterReaderTest {
+
+  @Test
+  public void testValueNumberWithBuffering() throws Exception {
+    String input = "{ \"apps\" : {\"app\":[{\"id\":\"one\", \"progress\":100.0, \"startedTime\":1399975176760}]} }";
+
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
+    UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "$.apps.app[*]" );
+    UrlRewriteFilterApplyDescriptor applyConfig = bufferConfig.addApply( "$.id", "test-rule" );
+
+    JsonFilterReader filter = new JsonFilterReader( new StringReader( input ), contentConfig );
+    String output = IOUtils.toString( filter );
+    assertThat( output, containsString( "\"startedTime\":1399975176760}" ) );
+  }
+
+
+  @Test
+  public void testSimple() throws IOException {
+    String inputJson = "{ \"test-name\" : \"test-value\" }";
+    StringReader inputReader = new StringReader( inputJson );
+    JsonFilterReader filterReader = new TestJsonFilterReader( inputReader, null );
+    String outputJson = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( "JSON=" + outputJson );
+
+    JsonAssert.with( outputJson ).assertThat( "name<test-name>", is( "value:null<test-value>" ) );
+  }
+
+  @Test
+  public void testRootArray() throws Exception {
+    String inputJson = "[\"test-value-1\",\"test-value-2\",\"test-value-3\"]";
+    StringReader inputReader = new StringReader( inputJson );
+    JsonFilterReader filterReader = new TestJsonFilterReader( inputReader, null );
+    String outputJson = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( "JSON=" + outputJson );
+    JsonAssert.with( outputJson ).assertThat( "$.[0]", is( "value:null<test-value-1>" ) );
+    JsonAssert.with( outputJson ).assertThat( "$.[1]", is( "value:null<test-value-2>" ) );
+    JsonAssert.with( outputJson ).assertThat( "$.[2]", is( "value:null<test-value-3>" ) );
+
+    inputJson = "[777,42]";
+    inputReader = new StringReader( inputJson );
+    filterReader = new TestJsonFilterReader( inputReader, null );
+    outputJson = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( "JSON=" + outputJson );
+    JsonAssert.with( outputJson ).assertThat( "$.[0]", is( 777 ) );
+    JsonAssert.with( outputJson ).assertThat( "$.[1]", is( 42 ) );
+  }
+
+  @Test
+  public void testEmptyObject() throws IOException {
+    String inputJson = "{}";
+    StringReader inputReader = new StringReader( inputJson );
+    JsonFilterReader filterReader = new TestJsonFilterReader( inputReader, null );
+    String outputJson = new String( IOUtils.toCharArray( filterReader ) );
+
+    assertThat( outputJson, is( "{}" ) );
+  }
+
+  @Test
+  public void testEmptyArray() throws IOException {
+    String inputJson = "[]";
+    StringReader inputReader = new StringReader( inputJson );
+    JsonFilterReader filterReader = new TestJsonFilterReader( inputReader, null );
+    String outputJson = new String( IOUtils.toCharArray( filterReader ) );
+
+    assertThat( outputJson, is( "[]" ) );
+  }
+
+  @Test
+  public void testUnscopedStreaming() throws IOException {
+    InputStream stream = TestUtils.getResourceStream( this.getClass(), "simple-values.json" );
+    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
+
+    //System.out.println( "INPUT=" + input );
+
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter=1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
+    UrlRewriteFilterApplyDescriptor applyConfig = contentConfig.addApply( "$['test-str']", "test-rule" );
+
+    JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
+    String output = IOUtils.toString( filter );
+
+    //System.out.println( "OUTPUT=" + output );
+
+    JsonAssert.with( output ).assertThat( "name<test-str>", is( "value:null<text>" ) );
+  }
+
+  @Test
+  public void testNamesWithDots() throws IOException {
+    InputStream stream = TestUtils.getResourceStream( this.getClass(), "dotted-field-name.json" );
+    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
+
+    //System.out.println( "INPUT=" + input );
+
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "test-filter" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "application/json" );
+    //NOTE: The field names are rewritten first so the values rules need to match the rewritten name.
+    contentConfig.addApply( "$.name<testField>", "test-rule" );
+    contentConfig.addApply( "$.name<test_field>", "test-rule" );
+    contentConfig.addApply( "$.name<test-field>", "test-rule" );
+    contentConfig.addApply( "$['name<test.field>']", "test-rule" );
+
+    JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
+    String output = IOUtils.toString( filter );
+
+    //System.out.println( "OUTPUT=" + output );
+
+    JsonAssert.with( output ).assertThat( "$['name<testField>']", is( "value:test-rule<testField value>" ) );
+    JsonAssert.with( output ).assertThat( "$['name<test_field>']", is( "value:test-rule<test_field value>" ) );
+    JsonAssert.with( output ).assertThat( "$['name<test-field>']", is( "value:test-rule<test-field value>" ) );
+    JsonAssert.with( output ).assertThat( "$['name<test.field>']", is( "value:test-rule<test.field value>" ) );
+  }
+
+//  @Test
+//  public void testJsonPathObject() throws IOException {
+//    InputStream stream = TestUtils.getResourceStream( this.getClass(), "complex.json" );
+//    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
+//
+//    Object o;
+//
+//    o = JsonPath.read( "$", input, JsonNode.class );
+//    assertThat( o, instanceOf( ObjectNode.class ) );
+//    assertThat( o.toString(), startsWith( "{" ) );
+//    System.out.println( o.getClass() + "=" + o );
+//
+//    o = JsonPath.read( "$['test-str']", input, JsonNode.class );
+//    System.out.println( o.getClass() + "=" + o );
+//
+//    o = JsonPath.read( "$['test-obj-multi']", input, JsonNode.class );
+//    System.out.println( o.getClass() + "=" + o );
+//
+//    o = JsonPath.read( "$['val']", (JsonNode)o, JsonNode.class );
+//    System.out.println( o.getClass() + "=" + o );
+//
+//    JsonPath p = JsonPath.compile( "$['test-obj-multi']['val']" );
+//    o = JsonPath.read( "$['test-obj-multi']['val']", input, JsonNode.class );
+//    JsonNode pp = ((JsonNode)o).findParent("val");
+//    System.out.println( "$['test-obj-multi']['val']=" + o.getClass() + "=" + o );
+//
+//  }
+//
+//  @Test
+//  public void testJsonPathArray() throws IOException {
+//    InputStream stream = TestUtils.getResourceStream( this.getClass(), "array.json" );
+//    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
+//
+//    Object o;
+//
+//    o = JsonPath.read( "$", input, JsonNode.class );
+//    System.out.println( o.getClass() + "=" + o );
+//
+//    o = JsonPath.read( "$[0]", input, JsonNode.class );
+//    System.out.println( o.getClass() + "=" + o );
+//
+//    o = JsonPath.read( "$[*]", input, JsonNode.class );
+//    System.out.println( "$[*]=" + o.getClass() + "=" + o );
+//
+//    o = JsonPath.read( "$['obj1-fld1']", (JsonNode)o, JsonNode.class );
+//    System.out.println( o.getClass() + "=" + o );
+//
+//    o = JsonPath.read( "$[0]['obj1-fld1']", input, JsonNode.class );
+//    System.out.println( o.getClass() + "=" + o );
+//
+//  }
+
+  @Test
+  public void testBuffered() throws IOException {
+    InputStream stream = TestUtils.getResourceStream( this.getClass(), "simple-values.json" );
+    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
+
+    //System.out.println( "INPUT=" + input );
+
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
+    UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "$" );
+    UrlRewriteFilterApplyDescriptor applyConfig = bufferConfig.addApply( "$['name<test-str>']", "test-rule" );
+    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
+
+    JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
+    String output = IOUtils.toString( filter );
+
+    //System.out.println( "OUTPUT=" + output );
+
+    JsonAssert.with( output ).assertThat( "name<test-str>", is( "value:test-rule<text>" ) );
+  }
+
+  @Test
+  public void testBufferedDetectApply() throws IOException {
+    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties.json" );
+    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
+
+    //System.out.println( "INPUT=" + input );
+
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
+    UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "$.name<properties>.*.name<property>" );
+    UrlRewriteFilterDetectDescriptor detectConfig = bufferConfig.addDetect( "$.name<property-name>", "test-name-2" );
+    UrlRewriteFilterApplyDescriptor applyConfig = detectConfig.addApply( "$.name<property-value>", "test-rule-2" );
+
+    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
+
+    JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
+    String output = IOUtils.toString( filter );
+
+    //System.out.println( "OUTPUT=" + output );
+
+    JsonAssert.with( output ).assertThat( "name<properties>[0].name<property>.name<property-name>", is( "test-name-1" ) );
+    JsonAssert.with( output ).assertThat( "name<properties>[0].name<property>.name<property-value>", is( "test-value-1" ) );
+    JsonAssert.with( output ).assertThat( "name<properties>[1].name<property>.name<property-name>", is( "test-name-2" ) );
+    JsonAssert.with( output ).assertThat( "name<properties>[1].name<property>.name<property-value>", is( "value:test-rule-2<test-value-2>" ) );
+    JsonAssert.with( output ).assertThat( "name<properties>[2].name<property>.name<property-name>", is( "test-name-3" ) );
+    JsonAssert.with( output ).assertThat( "name<properties>[2].name<property>.name<property-value>", is( "test-value-3" ) );
+  }
+
+  @Test
+  public void testBufferedApply() throws IOException {
+    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties.json" );
+    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
+
+    //System.out.println( "INPUT=" + input );
+
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
+    UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "$.name<properties>.*.name<property>" );
+    UrlRewriteFilterApplyDescriptor applyConfig = bufferConfig.addApply( "$.name<property-value>", "test-rule" );
+
+    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
+
+    JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
+    String output = IOUtils.toString( filter );
+
+    //System.out.println( "OUTPUT=" + output );
+
+    JsonAssert.with( output ).assertThat( "name<properties>[0].name<property>.name<property-name>", is( "test-name-1" ) );
+    JsonAssert.with( output ).assertThat( "name<properties>[0].name<property>.name<property-value>", is( "value:test-rule<test-value-1>" ) );
+    JsonAssert.with( output ).assertThat( "name<properties>[1].name<property>.name<property-name>", is( "test-name-2" ) );
+    JsonAssert.with( output ).assertThat( "name<properties>[1].name<property>.name<property-value>", is( "value:test-rule<test-value-2>" ) );
+    JsonAssert.with( output ).assertThat( "name<properties>[2].name<property>.name<property-name>", is( "test-name-3" ) );
+    JsonAssert.with( output ).assertThat( "name<properties>[2].name<property>.name<property-value>", is( "value:test-rule<test-value-3>" ) );
+  }
+
+  @Test
+  public void testBufferedMultiApply() throws IOException {
+    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties.json" );
+    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
+
+    //System.out.println( "INPUT=" + input );
+
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
+    UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "$.name<properties>" );
+    UrlRewriteFilterApplyDescriptor applyConfig = bufferConfig.addApply( "$.*.name<property>.name<property-value>", "test-rule" );
+
+    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
+
+    JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
+    String output = IOUtils.toString( filter );
+
+    //System.out.println( "OUTPUT=" + output );
+
+    JsonAssert.with( output ).assertThat( "name<properties>[0].name<property>.name<property-name>", is( "test-name-1" ) );
+    JsonAssert.with( output ).assertThat( "name<properties>[0].name<property>.name<property-value>", is( "value:test-rule<test-value-1>" ) );
+    JsonAssert.with( output ).assertThat( "name<properties>[1].name<property>.name<property-name>", is( "test-name-2" ) );
+    JsonAssert.with( output ).assertThat( "name<properties>[1].name<property>.name<property-value>", is( "value:test-rule<test-value-2>" ) );
+    JsonAssert.with( output ).assertThat( "name<properties>[2].name<property>.name<property-name>", is( "test-name-3" ) );
+    JsonAssert.with( output ).assertThat( "name<properties>[2].name<property>.name<property-value>", is( "value:test-rule<test-value-3>" ) );
+  }
+
+  @Test
+  public void testInvalidConfigShouldThrowException() throws Exception {
+    String input = "{\"test-name\":\"test-value\"}";
+
+    //System.out.println( "INPUT=" + input );
+
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "*/json" );
+    contentConfig.addApply( "/root/@url", "test-rule" );
+
+    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
+
+    try {
+      JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
+      IOUtils.toString( filter );
+      fail( "Should have thrown an IllegalArgumentException." );
+    } catch ( IOException e ) {
+      fail( "Should have thrown an IllegalArgumentException." );
+    } catch ( IllegalArgumentException e ) {
+      assertThat( e.getMessage(), containsString( "/root/@url" ) );
+    }
+  }
+
+  @Test
+  public void testEscapeCharactersBugKnox616() throws Exception {
+    String input, output;
+    JsonFilterReader filter;
+
+    input = "{ \"test-name\" : \"\\\"\" }";
+    filter = new NoopJsonFilterReader( new StringReader( input ), null );
+    output = IOUtils.toString( filter );
+    assertThat( output, is( "{\"test-name\":\"\\\"\"}" ) );
+
+    input = "{\"test-name\":\"\\b\"}";
+    filter = new NoopJsonFilterReader( new StringReader( input ), null );
+    output = IOUtils.toString( filter );
+    assertThat( output, is( "{\"test-name\":\"\\b\"}" ) );
+  }
+
+//  private void dump( ObjectMapper mapper, JsonGenerator generator, JsonNode node ) throws IOException {
+//    mapper.writeTree( generator, node );
+//    System.out.println();
+//  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/json/NoopJsonFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/json/NoopJsonFilterReader.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/json/NoopJsonFilterReader.java
new file mode 100644
index 0000000..bb5c6ca
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/json/NoopJsonFilterReader.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.knox.gateway.filter.rewrite.impl.json;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+
+import java.io.IOException;
+import java.io.Reader;
+
+public class NoopJsonFilterReader extends JsonFilterReader {
+
+  public NoopJsonFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException {
+    super( reader, config );
+  }
+
+  protected String filterFieldName( String name ) {
+    return name;
+  }
+
+  protected String filterValueString( String name, String value, String rule ) {
+    return value;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/json/TestJsonFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/json/TestJsonFilterReader.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/json/TestJsonFilterReader.java
new file mode 100644
index 0000000..197c5ec
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/json/TestJsonFilterReader.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.knox.gateway.filter.rewrite.impl.json;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+
+import java.io.IOException;
+import java.io.Reader;
+
+public class TestJsonFilterReader extends JsonFilterReader {
+
+  public TestJsonFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException {
+    super( reader, config );
+  }
+
+  protected String filterFieldName( String name ) {
+    return "name<" + name + ">";
+  }
+
+  protected String filterValueString( String name, String value, String rule ) {
+    return "value:" + rule + "<" + value + ">";
+  }
+
+}


[44/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaProviderTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaProviderTest.java b/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaProviderTest.java
deleted file mode 100644
index 87a63f4..0000000
--- a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultHaProviderTest.java
+++ /dev/null
@@ -1,85 +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.hadoop.gateway.ha.provider.impl;
-
-import org.apache.hadoop.gateway.ha.provider.HaDescriptor;
-import org.apache.hadoop.gateway.ha.provider.HaProvider;
-import org.junit.Test;
-
-import java.util.ArrayList;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.isIn;
-import static org.junit.Assert.*;
-
-public class DefaultHaProviderTest {
-
-   @Test
-   public void testDescriptor() {
-      try {
-         new DefaultHaProvider(null);
-         fail("provider construction should have failed with null descriptor");
-      } catch (IllegalArgumentException e) {
-      }
-      HaDescriptor descriptor = new DefaultHaDescriptor();
-      HaProvider provider = new DefaultHaProvider(descriptor);
-      assertNotNull(provider.getHaDescriptor());
-      descriptor.addServiceConfig(new DefaultHaServiceConfig("foo"));
-      assertTrue(provider.isHaEnabled("foo"));
-   }
-
-   @Test
-   public void testAddingService() {
-      HaDescriptor descriptor = new DefaultHaDescriptor();
-      HaProvider provider = new DefaultHaProvider(descriptor);
-      ArrayList<String> urls = new ArrayList<String>();
-      urls.add("http://host1");
-      urls.add("http://host2");
-      provider.addHaService("foo", urls);
-      assertNull(provider.getActiveURL("bar"));
-      String url = provider.getActiveURL("foo");
-      assertNotNull(url);
-      assertThat(url, isIn(urls));
-   }
-
-   @Test
-   public void testActiveUrl() {
-      HaDescriptor descriptor = new DefaultHaDescriptor();
-      HaProvider provider = new DefaultHaProvider(descriptor);
-      ArrayList<String> urls = new ArrayList<String>();
-      String url1 = "http://host1";
-      urls.add(url1);
-      String url2 = "http://host2";
-      urls.add(url2);
-      String url3 = "http://host3";
-      urls.add(url3);
-      String serviceName = "foo";
-      provider.addHaService(serviceName, urls);
-      assertEquals(url1, provider.getActiveURL(serviceName));
-      provider.markFailedURL(serviceName, url1);
-      assertEquals(url2, provider.getActiveURL(serviceName));
-      provider.markFailedURL(serviceName, url2);
-      assertEquals(url3, provider.getActiveURL(serviceName));
-      provider.markFailedURL(serviceName, url3);
-      assertEquals(url1, provider.getActiveURL(serviceName));
-      provider.setActiveURL(serviceName, url3);
-      assertEquals(url3, provider.getActiveURL(serviceName));
-      provider.setActiveURL(serviceName, url2);
-      assertEquals(url2, provider.getActiveURL(serviceName));
-   }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultURLManagerTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultURLManagerTest.java b/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultURLManagerTest.java
deleted file mode 100644
index 6c07d23..0000000
--- a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/DefaultURLManagerTest.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.hadoop.gateway.ha.provider.impl;
-
-import org.junit.Test;
-
-import java.util.ArrayList;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-public class DefaultURLManagerTest {
-
-   @Test
-   public void testActiveURLManagement() {
-      ArrayList<String> urls = new ArrayList<>();
-      String url1 = "http://host1";
-      urls.add(url1);
-      String url2 = "http://host2";
-      urls.add(url2);
-      DefaultURLManager manager = new DefaultURLManager();
-      manager.setURLs(urls);
-      assertTrue(manager.getURLs().containsAll(urls));
-      assertEquals(url1, manager.getActiveURL());
-      manager.markFailed(url1);
-      assertEquals(url2, manager.getActiveURL());
-      manager.markFailed(url2);
-      assertEquals(url1, manager.getActiveURL());
-   }
-
-   @Test
-   public void testMarkingFailedURL() {
-      ArrayList<String> urls = new ArrayList<>();
-      String url1 = "http://host1:4555";
-      urls.add(url1);
-      String url2 = "http://host2:1234";
-      urls.add(url2);
-      String url3 = "http://host1:1234";
-      urls.add(url3);
-      String url4 = "http://host2:4555";
-      urls.add(url4);
-      DefaultURLManager manager = new DefaultURLManager();
-      manager.setURLs(urls);
-      assertTrue(manager.getURLs().containsAll(urls));
-      assertEquals(url1, manager.getActiveURL());
-      manager.markFailed(url1);
-      assertEquals(url2, manager.getActiveURL());
-      manager.markFailed(url1);
-      assertEquals(url2, manager.getActiveURL());
-      manager.markFailed(url3);
-      assertEquals(url2, manager.getActiveURL());
-      manager.markFailed(url4);
-      assertEquals(url2, manager.getActiveURL());
-      manager.markFailed(url2);
-      assertEquals(url3, manager.getActiveURL());
-   }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/HS2ZookeeperURLManagerTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/HS2ZookeeperURLManagerTest.java b/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/HS2ZookeeperURLManagerTest.java
deleted file mode 100644
index 05c31b6..0000000
--- a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/HS2ZookeeperURLManagerTest.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.hadoop.gateway.ha.provider.impl;
-
-import org.apache.curator.framework.CuratorFramework;
-import org.apache.curator.framework.CuratorFrameworkFactory;
-import org.apache.curator.retry.ExponentialBackoffRetry;
-import org.apache.curator.test.TestingCluster;
-import org.apache.hadoop.gateway.ha.provider.HaServiceConfig;
-import org.apache.hadoop.gateway.ha.provider.URLManager;
-import org.apache.hadoop.gateway.ha.provider.URLManagerLoader;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-public class HS2ZookeeperURLManagerTest {
-
-  private TestingCluster cluster;
-  private HS2ZookeeperURLManager manager;
-
-  @Before
-  public void setup() throws Exception {
-    cluster = new TestingCluster(3);
-    cluster.start();
-
-    CuratorFramework zooKeeperClient =
-        CuratorFrameworkFactory.builder().connectString(cluster.getConnectString())
-            .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
-
-    String host1 = "hive.server2.authentication=NONE;hive.server2.transport.mode=http;hive.server2.thrift.http.path=cliservice;" +
-        "hive.server2.thrift.http.port=10001;hive.server2.thrift.bind.host=host1;hive.server2.use.SSL=true";
-    String host2 = "hive.server2.authentication=NONE;hive.server2.transport.mode=http;hive.server2.thrift.http.path=foobar;" +
-        "hive.server2.thrift.http.port=10002;hive.server2.thrift.bind.host=host2;hive.server2.use.SSL=false";
-    String host3 = "hive.server2.authentication=NONE;hive.server2.transport.mode=http;hive.server2.thrift.http.path=cliservice;" +
-        "hive.server2.thrift.http.port=10003;hive.server2.thrift.bind.host=host3;hive.server2.use.SSL=false";
-    String host4 = "hive.server2.authentication=NONE;hive.server2.transport.mode=http;hive.server2.thrift.http.path=cliservice;" +
-        "hive.server2.thrift.http.port=10004;hive.server2.thrift.bind.host=host4;hive.server2.use.SSL=true";
-    zooKeeperClient.start();
-    zooKeeperClient.create().forPath("/hiveServer2");
-    zooKeeperClient.create().forPath("/hiveServer2/host1", host1.getBytes());
-    zooKeeperClient.create().forPath("/hiveServer2/host2", host2.getBytes());
-    zooKeeperClient.create().forPath("/hiveServer2/host3", host3.getBytes());
-    zooKeeperClient.create().forPath("/hiveServer2/host4", host4.getBytes());
-    zooKeeperClient.close();
-    manager = new HS2ZookeeperURLManager();
-    HaServiceConfig config = new DefaultHaServiceConfig("HIVE");
-    config.setEnabled(true);
-    config.setZookeeperEnsemble(cluster.getConnectString());
-    config.setZookeeperNamespace("hiveServer2");
-    manager.setConfig(config);
-
-  }
-
-  @After
-  public void teardown() throws IOException {
-    cluster.stop();
-  }
-
-  @Test
-  public void testActiveURLManagement() throws Exception {
-    List<String> urls = manager.getURLs();
-    Assert.assertNotNull(urls);
-    String url1 = urls.get( 0 ); //"https://host4:10004/cliservice";
-    String url2 = urls.get( 1 ); //"http://host3:10003/cliservice";
-    String url3 = urls.get( 2 ); //"http://host2:10002/foobar";
-    assertEquals(url1, urls.get(0));
-    assertEquals(url1, manager.getActiveURL());
-    manager.markFailed(url1);
-    assertEquals(url2, manager.getActiveURL());
-    manager.markFailed(url2);
-    assertEquals(url3, manager.getActiveURL());
-  }
-
-  @Test
-  public void testMarkingFailedURL() {
-    List<String> urls = manager.getURLs();
-    String url1 = urls.get(0); //"https://host4:10004/cliservice";
-    urls.add(url1);
-    String url2 = urls.get(1); //"http://host3:10003/cliservice";
-    urls.add(url2);
-    String url3 = urls.get(2); //"http://host2:10002/foobar";
-    urls.add(url3);
-    String url4 = urls.get(3); //"https://host1:10001/cliservice";
-    urls.add(url4);
-    assertEquals(url1, manager.getActiveURL());
-    manager.markFailed(url1);
-    assertEquals(url2, manager.getActiveURL());
-    manager.markFailed(url1);
-    assertEquals(url2, manager.getActiveURL());
-    manager.markFailed(url3);
-    assertEquals(url2, manager.getActiveURL());
-    manager.markFailed(url4);
-    assertEquals(url2, manager.getActiveURL());
-    manager.markFailed(url2);
-    //now the urls should get re-looked up
-    assertEquals(url1, manager.getActiveURL());
-  }
-
-  @Test
-  public void testHS2URLManagerLoading() {
-    HaServiceConfig config = new DefaultHaServiceConfig("HIVE");
-    config.setEnabled(true);
-    config.setZookeeperEnsemble(cluster.getConnectString());
-    config.setZookeeperNamespace("hiveServer2");
-    URLManager manager = URLManagerLoader.loadURLManager(config);
-    Assert.assertNotNull(manager);
-    Assert.assertTrue(manager instanceof HS2ZookeeperURLManager);
-  }
-
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorFactoryTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorFactoryTest.java b/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorFactoryTest.java
deleted file mode 100644
index 55622c1..0000000
--- a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorFactoryTest.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.hadoop.gateway.ha.provider.impl;
-
-import org.apache.hadoop.gateway.ha.provider.HaServiceConfig;
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-
-public class HaDescriptorFactoryTest {
-
-   @Test
-   public void testCreateDescriptor() {
-      assertNotNull(HaDescriptorFactory.createDescriptor());
-   }
-
-   @Test
-   public void testCreateServiceConfig() {
-      HaServiceConfig serviceConfig = HaDescriptorFactory.createServiceConfig("foo", "enabled=true;maxFailoverAttempts=42;failoverSleep=50;maxRetryAttempts=1;retrySleep=1000");
-      assertNotNull(serviceConfig);
-      assertTrue(serviceConfig.isEnabled());
-      assertEquals("foo", serviceConfig.getServiceName());
-      assertEquals(42, serviceConfig.getMaxFailoverAttempts());
-      assertEquals(50, serviceConfig.getFailoverSleep());
-      assertEquals(1, serviceConfig.getMaxRetryAttempts());
-      assertEquals(1000, serviceConfig.getRetrySleep());
-
-      serviceConfig = HaDescriptorFactory.createServiceConfig("bar", "false", "3", "1000", "5", "3000", null, null);
-      assertNotNull(serviceConfig);
-      assertFalse(serviceConfig.isEnabled());
-      assertEquals("bar", serviceConfig.getServiceName());
-      assertEquals(3, serviceConfig.getMaxFailoverAttempts());
-      assertEquals(1000, serviceConfig.getFailoverSleep());
-      assertEquals(5, serviceConfig.getMaxRetryAttempts());
-      assertEquals(3000, serviceConfig.getRetrySleep());
-
-   }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorManagerTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorManagerTest.java b/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorManagerTest.java
deleted file mode 100644
index a2f423e..0000000
--- a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/HaDescriptorManagerTest.java
+++ /dev/null
@@ -1,89 +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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.ha.provider.impl;
-
-import org.apache.hadoop.gateway.ha.provider.HaDescriptor;
-import org.apache.hadoop.gateway.ha.provider.HaServiceConfig;
-import org.junit.Test;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.StringWriter;
-
-import static org.junit.Assert.*;
-import static org.xmlmatchers.XmlMatchers.hasXPath;
-import static org.xmlmatchers.transform.XmlConverters.the;
-
-public class HaDescriptorManagerTest {
-
-   @Test
-   public void testDescriptorLoad() throws IOException {
-      String xml = "<ha><service name='foo' maxFailoverAttempts='42' failoverSleep='4000' maxRetryAttempts='2' retrySleep='2213' enabled='false'/>" +
-            "<service name='bar' failoverLimit='3' enabled='true'/></ha>";
-      ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
-      HaDescriptor descriptor = HaDescriptorManager.load(inputStream);
-      assertNotNull(descriptor);
-      assertEquals(1, descriptor.getEnabledServiceNames().size());
-      HaServiceConfig config = descriptor.getServiceConfig("foo");
-      assertNotNull(config);
-      assertEquals("foo", config.getServiceName());
-      assertEquals(42, config.getMaxFailoverAttempts());
-      assertEquals(4000, config.getFailoverSleep());
-      assertEquals(2, config.getMaxRetryAttempts());
-      assertEquals(2213, config.getRetrySleep());
-      assertFalse(config.isEnabled());
-      config = descriptor.getServiceConfig("bar");
-      assertTrue(config.isEnabled());
-   }
-
-   @Test
-   public void testDescriptorDefaults() throws IOException {
-      String xml = "<ha><service name='foo'/></ha>";
-      ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
-      HaDescriptor descriptor = HaDescriptorManager.load(inputStream);
-      assertNotNull(descriptor);
-      assertEquals(1, descriptor.getEnabledServiceNames().size());
-      HaServiceConfig config = descriptor.getServiceConfig("foo");
-      assertNotNull(config);
-      assertEquals("foo", config.getServiceName());
-      assertEquals(HaServiceConfigConstants.DEFAULT_MAX_FAILOVER_ATTEMPTS, config.getMaxFailoverAttempts());
-      assertEquals(HaServiceConfigConstants.DEFAULT_FAILOVER_SLEEP, config.getFailoverSleep());
-      assertEquals(HaServiceConfigConstants.DEFAULT_MAX_RETRY_ATTEMPTS, config.getMaxRetryAttempts());
-      assertEquals(HaServiceConfigConstants.DEFAULT_RETRY_SLEEP, config.getRetrySleep());
-      assertEquals(HaServiceConfigConstants.DEFAULT_ENABLED, config.isEnabled());
-   }
-
-   @Test
-   public void testDescriptorStoring() throws IOException {
-      HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
-      descriptor.addServiceConfig(HaDescriptorFactory.createServiceConfig("foo", "false", "42", "1000", "3", "3000", "foo:2181,bar:2181", "hiveserver2"));
-      descriptor.addServiceConfig(HaDescriptorFactory.createServiceConfig("bar", "true", "3", "5000", "5", "8000", null, null));
-      StringWriter writer = new StringWriter();
-      HaDescriptorManager.store(descriptor, writer);
-      String descriptorXml = writer.toString();
-      String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
-            "<ha>\n" +
-            "  <service enabled=\"false\" failoverSleep=\"1000\" maxFailoverAttempts=\"42\" maxRetryAttempts=\"3\" name=\"foo\" retrySleep=\"3000\" zookeeperEnsemble=\"foo:2181,bar:2181\" zookeeperNamespace=\"hiveserver2\"/>\n" +
-            "  <service enabled=\"true\" failoverSleep=\"5000\" maxFailoverAttempts=\"3\" maxRetryAttempts=\"5\" name=\"bar\" retrySleep=\"8000\"/>\n" +
-            "</ha>\n";
-      assertThat( the( xml ), hasXPath( "/ha/service[@enabled='false' and @failoverSleep='1000' and @maxFailoverAttempts='42' and @maxRetryAttempts='3' and @name='foo' and @retrySleep='3000' and @zookeeperEnsemble='foo:2181,bar:2181' and @zookeeperNamespace='hiveserver2']" ) );
-      assertThat( the( xml ), hasXPath( "/ha/service[@enabled='true' and @failoverSleep='5000' and @maxFailoverAttempts='3' and @maxRetryAttempts='5' and @name='bar' and @retrySleep='8000']" ) );
-   }
-
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/MockURLManager.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/MockURLManager.java b/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/MockURLManager.java
deleted file mode 100644
index f11785f..0000000
--- a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/MockURLManager.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.hadoop.gateway.ha.provider.impl;
-
-import org.apache.hadoop.gateway.ha.provider.HaServiceConfig;
-
-public class MockURLManager extends DefaultURLManager {
-
-  HaServiceConfig config;
-
-  @Override
-  public boolean supportsConfig(HaServiceConfig config) {
-    return config.getServiceName().equalsIgnoreCase("mock-test");
-  }
-
-  @Override
-  public void setConfig(HaServiceConfig config) {
-    this.config = config;
-    super.setConfig(config);
-  }
-
-  public HaServiceConfig getConfig() {
-    return config;
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/URLManagerLoaderTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/URLManagerLoaderTest.java b/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/URLManagerLoaderTest.java
deleted file mode 100644
index 6aadfec..0000000
--- a/gateway-provider-ha/src/test/java/org/apache/hadoop/gateway/ha/provider/impl/URLManagerLoaderTest.java
+++ /dev/null
@@ -1,48 +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.hadoop.gateway.ha.provider.impl;
-
-import org.apache.hadoop.gateway.ha.provider.URLManager;
-import org.apache.hadoop.gateway.ha.provider.URLManagerLoader;
-import org.junit.Assert;
-import org.junit.Test;
-
-public class URLManagerLoaderTest {
-
-  @Test
-  public void testURLManagerLoader() {
-    DefaultHaServiceConfig serviceConfig = new DefaultHaServiceConfig("mock-test");
-    URLManager manager = URLManagerLoader.loadURLManager(serviceConfig);
-    Assert.assertNotNull(manager);
-    Assert.assertTrue(manager instanceof MockURLManager);
-    Assert.assertNotNull(((MockURLManager) manager).getConfig());
-    Assert.assertEquals("mock-test", ((MockURLManager) manager).getConfig().getServiceName());
-  }
-
-  @Test
-  public void testDefaultURLManager() {
-    DefaultHaServiceConfig serviceConfig = new DefaultHaServiceConfig("nothing like this exists");
-    URLManager manager = URLManagerLoader.loadURLManager(serviceConfig);
-    Assert.assertNotNull(manager);
-    Assert.assertTrue(manager instanceof DefaultURLManager);
-    manager = URLManagerLoader.loadURLManager(null);
-    Assert.assertNotNull(manager);
-    Assert.assertTrue(manager instanceof DefaultURLManager);
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/deploy/HaProviderDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/deploy/HaProviderDeploymentContributorTest.java b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/deploy/HaProviderDeploymentContributorTest.java
new file mode 100644
index 0000000..f28baaf
--- /dev/null
+++ b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/deploy/HaProviderDeploymentContributorTest.java
@@ -0,0 +1,46 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.deploy;
+
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributor;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+
+public class HaProviderDeploymentContributorTest {
+
+   @Test
+   public void testServiceLoader() throws Exception {
+      ServiceLoader loader = ServiceLoader.load( ProviderDeploymentContributor.class );
+      Iterator iterator = loader.iterator();
+      assertThat( "Service iterator empty.", iterator.hasNext() );
+      while( iterator.hasNext() ) {
+         Object object = iterator.next();
+         if( object instanceof HaProviderDeploymentContributor ) {
+            return;
+         }
+      }
+      fail( "Failed to find " + HaProviderDeploymentContributor.class.getName() + " via service loader." );
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/dispatch/DefaultHaDispatchTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/dispatch/DefaultHaDispatchTest.java b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/dispatch/DefaultHaDispatchTest.java
new file mode 100644
index 0000000..0f19e79
--- /dev/null
+++ b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/dispatch/DefaultHaDispatchTest.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.knox.gateway.ha.dispatch;
+
+import org.apache.knox.gateway.ha.provider.HaDescriptor;
+import org.apache.knox.gateway.ha.provider.HaProvider;
+import org.apache.knox.gateway.ha.provider.HaServletContextListener;
+import org.apache.knox.gateway.ha.provider.impl.DefaultHaProvider;
+import org.apache.knox.gateway.ha.provider.impl.HaDescriptorFactory;
+import org.apache.knox.gateway.servlet.SynchronousServletOutputStreamAdapter;
+import org.apache.http.client.methods.HttpRequestBase;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.params.BasicHttpParams;
+import org.easymock.EasyMock;
+import org.easymock.IAnswer;
+import org.junit.Assert;
+import org.junit.Test;
+
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class DefaultHaDispatchTest {
+
+  @Test
+  public void testConnectivityFailover() throws Exception {
+    String serviceName = "OOZIE";
+    HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
+    descriptor.addServiceConfig(HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null));
+    HaProvider provider = new DefaultHaProvider(descriptor);
+    URI uri1 = new URI( "http://unreachable-host" );
+    URI uri2 = new URI( "http://reachable-host" );
+    ArrayList<String> urlList = new ArrayList<String>();
+    urlList.add(uri1.toString());
+    urlList.add(uri2.toString());
+    provider.addHaService(serviceName, urlList);
+    FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class);
+    ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);
+
+    EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes();
+    EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(provider).anyTimes();
+
+    BasicHttpParams params = new BasicHttpParams();
+
+    HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class);
+    EasyMock.expect(outboundRequest.getMethod()).andReturn( "GET" ).anyTimes();
+    EasyMock.expect(outboundRequest.getURI()).andReturn( uri1  ).anyTimes();
+    EasyMock.expect(outboundRequest.getParams()).andReturn( params ).anyTimes();
+
+    HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
+    EasyMock.expect(inboundRequest.getRequestURL()).andReturn( new StringBuffer(uri2.toString()) ).once();
+    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0)).once();
+    EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1)).once();
+
+    HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class);
+    EasyMock.expect(outboundResponse.getOutputStream()).andAnswer( new IAnswer<SynchronousServletOutputStreamAdapter>() {
+      @Override
+      public SynchronousServletOutputStreamAdapter answer() throws Throwable {
+        return new SynchronousServletOutputStreamAdapter() {
+          @Override
+          public void write( int b ) throws IOException {
+            throw new IOException( "unreachable-host" );
+          }
+        };
+      }
+    }).once();
+    EasyMock.replay(filterConfig, servletContext, outboundRequest, inboundRequest, outboundResponse);
+    Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
+    DefaultHaDispatch dispatch = new DefaultHaDispatch();
+    dispatch.setHttpClient(new DefaultHttpClient());
+    dispatch.setHaProvider(provider);
+    dispatch.setServiceRole(serviceName);
+    dispatch.init();
+    long startTime = System.currentTimeMillis();
+    try {
+      dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
+    } catch (IOException e) {
+      //this is expected after the failover limit is reached
+    }
+    long elapsedTime = System.currentTimeMillis() - startTime;
+    Assert.assertEquals(uri2.toString(), provider.getActiveURL(serviceName));
+    //test to make sure the sleep took place
+    Assert.assertTrue(elapsedTime > 1000);
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaProviderTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaProviderTest.java b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaProviderTest.java
new file mode 100644
index 0000000..90c03e5
--- /dev/null
+++ b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaProviderTest.java
@@ -0,0 +1,85 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider.impl;
+
+import org.apache.knox.gateway.ha.provider.HaDescriptor;
+import org.apache.knox.gateway.ha.provider.HaProvider;
+import org.junit.Test;
+
+import java.util.ArrayList;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.isIn;
+import static org.junit.Assert.*;
+
+public class DefaultHaProviderTest {
+
+   @Test
+   public void testDescriptor() {
+      try {
+         new DefaultHaProvider(null);
+         fail("provider construction should have failed with null descriptor");
+      } catch (IllegalArgumentException e) {
+      }
+      HaDescriptor descriptor = new DefaultHaDescriptor();
+      HaProvider provider = new DefaultHaProvider(descriptor);
+      assertNotNull(provider.getHaDescriptor());
+      descriptor.addServiceConfig(new DefaultHaServiceConfig("foo"));
+      assertTrue(provider.isHaEnabled("foo"));
+   }
+
+   @Test
+   public void testAddingService() {
+      HaDescriptor descriptor = new DefaultHaDescriptor();
+      HaProvider provider = new DefaultHaProvider(descriptor);
+      ArrayList<String> urls = new ArrayList<String>();
+      urls.add("http://host1");
+      urls.add("http://host2");
+      provider.addHaService("foo", urls);
+      assertNull(provider.getActiveURL("bar"));
+      String url = provider.getActiveURL("foo");
+      assertNotNull(url);
+      assertThat(url, isIn(urls));
+   }
+
+   @Test
+   public void testActiveUrl() {
+      HaDescriptor descriptor = new DefaultHaDescriptor();
+      HaProvider provider = new DefaultHaProvider(descriptor);
+      ArrayList<String> urls = new ArrayList<String>();
+      String url1 = "http://host1";
+      urls.add(url1);
+      String url2 = "http://host2";
+      urls.add(url2);
+      String url3 = "http://host3";
+      urls.add(url3);
+      String serviceName = "foo";
+      provider.addHaService(serviceName, urls);
+      assertEquals(url1, provider.getActiveURL(serviceName));
+      provider.markFailedURL(serviceName, url1);
+      assertEquals(url2, provider.getActiveURL(serviceName));
+      provider.markFailedURL(serviceName, url2);
+      assertEquals(url3, provider.getActiveURL(serviceName));
+      provider.markFailedURL(serviceName, url3);
+      assertEquals(url1, provider.getActiveURL(serviceName));
+      provider.setActiveURL(serviceName, url3);
+      assertEquals(url3, provider.getActiveURL(serviceName));
+      provider.setActiveURL(serviceName, url2);
+      assertEquals(url2, provider.getActiveURL(serviceName));
+   }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/DefaultURLManagerTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/DefaultURLManagerTest.java b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/DefaultURLManagerTest.java
new file mode 100644
index 0000000..c8b6c58
--- /dev/null
+++ b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/DefaultURLManagerTest.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.knox.gateway.ha.provider.impl;
+
+import org.junit.Test;
+
+import java.util.ArrayList;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class DefaultURLManagerTest {
+
+   @Test
+   public void testActiveURLManagement() {
+      ArrayList<String> urls = new ArrayList<>();
+      String url1 = "http://host1";
+      urls.add(url1);
+      String url2 = "http://host2";
+      urls.add(url2);
+      DefaultURLManager manager = new DefaultURLManager();
+      manager.setURLs(urls);
+      assertTrue(manager.getURLs().containsAll(urls));
+      assertEquals(url1, manager.getActiveURL());
+      manager.markFailed(url1);
+      assertEquals(url2, manager.getActiveURL());
+      manager.markFailed(url2);
+      assertEquals(url1, manager.getActiveURL());
+   }
+
+   @Test
+   public void testMarkingFailedURL() {
+      ArrayList<String> urls = new ArrayList<>();
+      String url1 = "http://host1:4555";
+      urls.add(url1);
+      String url2 = "http://host2:1234";
+      urls.add(url2);
+      String url3 = "http://host1:1234";
+      urls.add(url3);
+      String url4 = "http://host2:4555";
+      urls.add(url4);
+      DefaultURLManager manager = new DefaultURLManager();
+      manager.setURLs(urls);
+      assertTrue(manager.getURLs().containsAll(urls));
+      assertEquals(url1, manager.getActiveURL());
+      manager.markFailed(url1);
+      assertEquals(url2, manager.getActiveURL());
+      manager.markFailed(url1);
+      assertEquals(url2, manager.getActiveURL());
+      manager.markFailed(url3);
+      assertEquals(url2, manager.getActiveURL());
+      manager.markFailed(url4);
+      assertEquals(url2, manager.getActiveURL());
+      manager.markFailed(url2);
+      assertEquals(url3, manager.getActiveURL());
+   }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/HS2ZookeeperURLManagerTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/HS2ZookeeperURLManagerTest.java b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/HS2ZookeeperURLManagerTest.java
new file mode 100644
index 0000000..53f1e5e
--- /dev/null
+++ b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/HS2ZookeeperURLManagerTest.java
@@ -0,0 +1,133 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider.impl;
+
+import org.apache.curator.framework.CuratorFramework;
+import org.apache.curator.framework.CuratorFrameworkFactory;
+import org.apache.curator.retry.ExponentialBackoffRetry;
+import org.apache.curator.test.TestingCluster;
+import org.apache.knox.gateway.ha.provider.HaServiceConfig;
+import org.apache.knox.gateway.ha.provider.URLManager;
+import org.apache.knox.gateway.ha.provider.URLManagerLoader;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class HS2ZookeeperURLManagerTest {
+
+  private TestingCluster cluster;
+  private HS2ZookeeperURLManager manager;
+
+  @Before
+  public void setup() throws Exception {
+    cluster = new TestingCluster(3);
+    cluster.start();
+
+    CuratorFramework zooKeeperClient =
+        CuratorFrameworkFactory.builder().connectString(cluster.getConnectString())
+            .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
+
+    String host1 = "hive.server2.authentication=NONE;hive.server2.transport.mode=http;hive.server2.thrift.http.path=cliservice;" +
+        "hive.server2.thrift.http.port=10001;hive.server2.thrift.bind.host=host1;hive.server2.use.SSL=true";
+    String host2 = "hive.server2.authentication=NONE;hive.server2.transport.mode=http;hive.server2.thrift.http.path=foobar;" +
+        "hive.server2.thrift.http.port=10002;hive.server2.thrift.bind.host=host2;hive.server2.use.SSL=false";
+    String host3 = "hive.server2.authentication=NONE;hive.server2.transport.mode=http;hive.server2.thrift.http.path=cliservice;" +
+        "hive.server2.thrift.http.port=10003;hive.server2.thrift.bind.host=host3;hive.server2.use.SSL=false";
+    String host4 = "hive.server2.authentication=NONE;hive.server2.transport.mode=http;hive.server2.thrift.http.path=cliservice;" +
+        "hive.server2.thrift.http.port=10004;hive.server2.thrift.bind.host=host4;hive.server2.use.SSL=true";
+    zooKeeperClient.start();
+    zooKeeperClient.create().forPath("/hiveServer2");
+    zooKeeperClient.create().forPath("/hiveServer2/host1", host1.getBytes());
+    zooKeeperClient.create().forPath("/hiveServer2/host2", host2.getBytes());
+    zooKeeperClient.create().forPath("/hiveServer2/host3", host3.getBytes());
+    zooKeeperClient.create().forPath("/hiveServer2/host4", host4.getBytes());
+    zooKeeperClient.close();
+    manager = new HS2ZookeeperURLManager();
+    HaServiceConfig config = new DefaultHaServiceConfig("HIVE");
+    config.setEnabled(true);
+    config.setZookeeperEnsemble(cluster.getConnectString());
+    config.setZookeeperNamespace("hiveServer2");
+    manager.setConfig(config);
+
+  }
+
+  @After
+  public void teardown() throws IOException {
+    cluster.stop();
+  }
+
+  @Test
+  public void testActiveURLManagement() throws Exception {
+    List<String> urls = manager.getURLs();
+    Assert.assertNotNull(urls);
+    String url1 = urls.get( 0 ); //"https://host4:10004/cliservice";
+    String url2 = urls.get( 1 ); //"http://host3:10003/cliservice";
+    String url3 = urls.get( 2 ); //"http://host2:10002/foobar";
+    assertEquals(url1, urls.get(0));
+    assertEquals(url1, manager.getActiveURL());
+    manager.markFailed(url1);
+    assertEquals(url2, manager.getActiveURL());
+    manager.markFailed(url2);
+    assertEquals(url3, manager.getActiveURL());
+  }
+
+  @Test
+  public void testMarkingFailedURL() {
+    List<String> urls = manager.getURLs();
+    String url1 = urls.get(0); //"https://host4:10004/cliservice";
+    urls.add(url1);
+    String url2 = urls.get(1); //"http://host3:10003/cliservice";
+    urls.add(url2);
+    String url3 = urls.get(2); //"http://host2:10002/foobar";
+    urls.add(url3);
+    String url4 = urls.get(3); //"https://host1:10001/cliservice";
+    urls.add(url4);
+    assertEquals(url1, manager.getActiveURL());
+    manager.markFailed(url1);
+    assertEquals(url2, manager.getActiveURL());
+    manager.markFailed(url1);
+    assertEquals(url2, manager.getActiveURL());
+    manager.markFailed(url3);
+    assertEquals(url2, manager.getActiveURL());
+    manager.markFailed(url4);
+    assertEquals(url2, manager.getActiveURL());
+    manager.markFailed(url2);
+    //now the urls should get re-looked up
+    assertEquals(url1, manager.getActiveURL());
+  }
+
+  @Test
+  public void testHS2URLManagerLoading() {
+    HaServiceConfig config = new DefaultHaServiceConfig("HIVE");
+    config.setEnabled(true);
+    config.setZookeeperEnsemble(cluster.getConnectString());
+    config.setZookeeperNamespace("hiveServer2");
+    URLManager manager = URLManagerLoader.loadURLManager(config);
+    Assert.assertNotNull(manager);
+    Assert.assertTrue(manager instanceof HS2ZookeeperURLManager);
+  }
+
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorFactoryTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorFactoryTest.java b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorFactoryTest.java
new file mode 100644
index 0000000..bf306e9
--- /dev/null
+++ b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorFactoryTest.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.knox.gateway.ha.provider.impl;
+
+import org.apache.knox.gateway.ha.provider.HaServiceConfig;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+public class HaDescriptorFactoryTest {
+
+   @Test
+   public void testCreateDescriptor() {
+      assertNotNull(HaDescriptorFactory.createDescriptor());
+   }
+
+   @Test
+   public void testCreateServiceConfig() {
+      HaServiceConfig serviceConfig = HaDescriptorFactory.createServiceConfig("foo", "enabled=true;maxFailoverAttempts=42;failoverSleep=50;maxRetryAttempts=1;retrySleep=1000");
+      assertNotNull(serviceConfig);
+      assertTrue(serviceConfig.isEnabled());
+      assertEquals("foo", serviceConfig.getServiceName());
+      assertEquals(42, serviceConfig.getMaxFailoverAttempts());
+      assertEquals(50, serviceConfig.getFailoverSleep());
+      assertEquals(1, serviceConfig.getMaxRetryAttempts());
+      assertEquals(1000, serviceConfig.getRetrySleep());
+
+      serviceConfig = HaDescriptorFactory.createServiceConfig("bar", "false", "3", "1000", "5", "3000", null, null);
+      assertNotNull(serviceConfig);
+      assertFalse(serviceConfig.isEnabled());
+      assertEquals("bar", serviceConfig.getServiceName());
+      assertEquals(3, serviceConfig.getMaxFailoverAttempts());
+      assertEquals(1000, serviceConfig.getFailoverSleep());
+      assertEquals(5, serviceConfig.getMaxRetryAttempts());
+      assertEquals(3000, serviceConfig.getRetrySleep());
+
+   }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorManagerTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorManagerTest.java b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorManagerTest.java
new file mode 100644
index 0000000..c9ed2c7
--- /dev/null
+++ b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorManagerTest.java
@@ -0,0 +1,89 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider.impl;
+
+import org.apache.knox.gateway.ha.provider.HaDescriptor;
+import org.apache.knox.gateway.ha.provider.HaServiceConfig;
+import org.junit.Test;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.StringWriter;
+
+import static org.junit.Assert.*;
+import static org.xmlmatchers.XmlMatchers.hasXPath;
+import static org.xmlmatchers.transform.XmlConverters.the;
+
+public class HaDescriptorManagerTest {
+
+   @Test
+   public void testDescriptorLoad() throws IOException {
+      String xml = "<ha><service name='foo' maxFailoverAttempts='42' failoverSleep='4000' maxRetryAttempts='2' retrySleep='2213' enabled='false'/>" +
+            "<service name='bar' failoverLimit='3' enabled='true'/></ha>";
+      ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
+      HaDescriptor descriptor = HaDescriptorManager.load(inputStream);
+      assertNotNull(descriptor);
+      assertEquals(1, descriptor.getEnabledServiceNames().size());
+      HaServiceConfig config = descriptor.getServiceConfig("foo");
+      assertNotNull(config);
+      assertEquals("foo", config.getServiceName());
+      assertEquals(42, config.getMaxFailoverAttempts());
+      assertEquals(4000, config.getFailoverSleep());
+      assertEquals(2, config.getMaxRetryAttempts());
+      assertEquals(2213, config.getRetrySleep());
+      assertFalse(config.isEnabled());
+      config = descriptor.getServiceConfig("bar");
+      assertTrue(config.isEnabled());
+   }
+
+   @Test
+   public void testDescriptorDefaults() throws IOException {
+      String xml = "<ha><service name='foo'/></ha>";
+      ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
+      HaDescriptor descriptor = HaDescriptorManager.load(inputStream);
+      assertNotNull(descriptor);
+      assertEquals(1, descriptor.getEnabledServiceNames().size());
+      HaServiceConfig config = descriptor.getServiceConfig("foo");
+      assertNotNull(config);
+      assertEquals("foo", config.getServiceName());
+      assertEquals(HaServiceConfigConstants.DEFAULT_MAX_FAILOVER_ATTEMPTS, config.getMaxFailoverAttempts());
+      assertEquals(HaServiceConfigConstants.DEFAULT_FAILOVER_SLEEP, config.getFailoverSleep());
+      assertEquals(HaServiceConfigConstants.DEFAULT_MAX_RETRY_ATTEMPTS, config.getMaxRetryAttempts());
+      assertEquals(HaServiceConfigConstants.DEFAULT_RETRY_SLEEP, config.getRetrySleep());
+      assertEquals(HaServiceConfigConstants.DEFAULT_ENABLED, config.isEnabled());
+   }
+
+   @Test
+   public void testDescriptorStoring() throws IOException {
+      HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
+      descriptor.addServiceConfig(HaDescriptorFactory.createServiceConfig("foo", "false", "42", "1000", "3", "3000", "foo:2181,bar:2181", "hiveserver2"));
+      descriptor.addServiceConfig(HaDescriptorFactory.createServiceConfig("bar", "true", "3", "5000", "5", "8000", null, null));
+      StringWriter writer = new StringWriter();
+      HaDescriptorManager.store(descriptor, writer);
+      String descriptorXml = writer.toString();
+      String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
+            "<ha>\n" +
+            "  <service enabled=\"false\" failoverSleep=\"1000\" maxFailoverAttempts=\"42\" maxRetryAttempts=\"3\" name=\"foo\" retrySleep=\"3000\" zookeeperEnsemble=\"foo:2181,bar:2181\" zookeeperNamespace=\"hiveserver2\"/>\n" +
+            "  <service enabled=\"true\" failoverSleep=\"5000\" maxFailoverAttempts=\"3\" maxRetryAttempts=\"5\" name=\"bar\" retrySleep=\"8000\"/>\n" +
+            "</ha>\n";
+      assertThat( the( xml ), hasXPath( "/ha/service[@enabled='false' and @failoverSleep='1000' and @maxFailoverAttempts='42' and @maxRetryAttempts='3' and @name='foo' and @retrySleep='3000' and @zookeeperEnsemble='foo:2181,bar:2181' and @zookeeperNamespace='hiveserver2']" ) );
+      assertThat( the( xml ), hasXPath( "/ha/service[@enabled='true' and @failoverSleep='5000' and @maxFailoverAttempts='3' and @maxRetryAttempts='5' and @name='bar' and @retrySleep='8000']" ) );
+   }
+
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/MockURLManager.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/MockURLManager.java b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/MockURLManager.java
new file mode 100644
index 0000000..f10eb26
--- /dev/null
+++ b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/MockURLManager.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.knox.gateway.ha.provider.impl;
+
+import org.apache.knox.gateway.ha.provider.HaServiceConfig;
+
+public class MockURLManager extends DefaultURLManager {
+
+  HaServiceConfig config;
+
+  @Override
+  public boolean supportsConfig(HaServiceConfig config) {
+    return config.getServiceName().equalsIgnoreCase("mock-test");
+  }
+
+  @Override
+  public void setConfig(HaServiceConfig config) {
+    this.config = config;
+    super.setConfig(config);
+  }
+
+  public HaServiceConfig getConfig() {
+    return config;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/URLManagerLoaderTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/URLManagerLoaderTest.java b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/URLManagerLoaderTest.java
new file mode 100644
index 0000000..6dc014a
--- /dev/null
+++ b/gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/URLManagerLoaderTest.java
@@ -0,0 +1,48 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.ha.provider.impl;
+
+import org.apache.knox.gateway.ha.provider.URLManager;
+import org.apache.knox.gateway.ha.provider.URLManagerLoader;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class URLManagerLoaderTest {
+
+  @Test
+  public void testURLManagerLoader() {
+    DefaultHaServiceConfig serviceConfig = new DefaultHaServiceConfig("mock-test");
+    URLManager manager = URLManagerLoader.loadURLManager(serviceConfig);
+    Assert.assertNotNull(manager);
+    Assert.assertTrue(manager instanceof MockURLManager);
+    Assert.assertNotNull(((MockURLManager) manager).getConfig());
+    Assert.assertEquals("mock-test", ((MockURLManager) manager).getConfig().getServiceName());
+  }
+
+  @Test
+  public void testDefaultURLManager() {
+    DefaultHaServiceConfig serviceConfig = new DefaultHaServiceConfig("nothing like this exists");
+    URLManager manager = URLManagerLoader.loadURLManager(serviceConfig);
+    Assert.assertNotNull(manager);
+    Assert.assertTrue(manager instanceof DefaultURLManager);
+    manager = URLManagerLoader.loadURLManager(null);
+    Assert.assertNotNull(manager);
+    Assert.assertTrue(manager instanceof DefaultURLManager);
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/resources/META-INF/services/org.apache.hadoop.gateway.ha.provider.URLManager
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/resources/META-INF/services/org.apache.hadoop.gateway.ha.provider.URLManager b/gateway-provider-ha/src/test/resources/META-INF/services/org.apache.hadoop.gateway.ha.provider.URLManager
deleted file mode 100644
index ea210ce..0000000
--- a/gateway-provider-ha/src/test/resources/META-INF/services/org.apache.hadoop.gateway.ha.provider.URLManager
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.ha.provider.impl.MockURLManager
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-ha/src/test/resources/META-INF/services/org.apache.knox.gateway.ha.provider.URLManager
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/test/resources/META-INF/services/org.apache.knox.gateway.ha.provider.URLManager b/gateway-provider-ha/src/test/resources/META-INF/services/org.apache.knox.gateway.ha.provider.URLManager
new file mode 100644
index 0000000..4ccaa33
--- /dev/null
+++ b/gateway-provider-ha/src/test/resources/META-INF/services/org.apache.knox.gateway.ha.provider.URLManager
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.ha.provider.impl.MockURLManager
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/IdentityAsserterMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/IdentityAsserterMessages.java b/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/IdentityAsserterMessages.java
deleted file mode 100644
index c4ada6b..0000000
--- a/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/IdentityAsserterMessages.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-import org.apache.hadoop.gateway.i18n.messages.StackTrace;
-
-@Messages(logger="org.apache.hadoop.gateway")
-public interface IdentityAsserterMessages {
-
-  @Message( level = MessageLevel.WARN, text = "Skipping unencodable parameter {0}={1}, {2}: {3}" )
-  void skippingUnencodableParameter( String name, String value, String encoding, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/AbstractIdentityAsserterDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/AbstractIdentityAsserterDeploymentContributor.java b/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/AbstractIdentityAsserterDeploymentContributor.java
deleted file mode 100644
index 15ae296..0000000
--- a/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/AbstractIdentityAsserterDeploymentContributor.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.hadoop.gateway.identityasserter.common.filter;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-public abstract class AbstractIdentityAsserterDeploymentContributor extends ProviderDeploymentContributorBase {
-
-  @Override
-  public String getRole() {
-    return "identity-assertion";
-  }
-
-  @Override
-  public void contributeFilter( DeploymentContext context, Provider provider, Service service, 
-      ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
-    params = buildFilterInitParms(provider, resource, params);
-    resource.addFilter().name(getName()).role(getRole()).impl(getFilterClassname()).params(params);
-  }
-
-  public List<FilterParamDescriptor> buildFilterInitParms(Provider provider,
-      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
-    // blindly add all the provider params as filter init params
-    if (params == null) {
-      params = new ArrayList<FilterParamDescriptor>();
-    }
-    Map<String, String> providerParams = provider.getParams();
-    for(Entry<String, String> entry : providerParams.entrySet()) {
-      params.add( resource.createFilterParam().name(entry.getKey().toLowerCase()).value(entry.getValue()));
-    }
-    return params;
-  }
-
-  protected abstract String getFilterClassname();
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/AbstractIdentityAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/AbstractIdentityAssertionFilter.java b/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/AbstractIdentityAssertionFilter.java
deleted file mode 100644
index 7575b36..0000000
--- a/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/AbstractIdentityAssertionFilter.java
+++ /dev/null
@@ -1,198 +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.hadoop.gateway.identityasserter.common.filter;
-
-import java.io.IOException;
-import java.security.AccessController;
-import java.security.Principal;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.Arrays;
-import java.util.Set;
-
-import javax.security.auth.Subject;
-import javax.servlet.Filter;
-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.HttpServletRequestWrapper;
-
-import org.apache.hadoop.gateway.audit.api.Action;
-import org.apache.hadoop.gateway.audit.api.ActionOutcome;
-import org.apache.hadoop.gateway.audit.api.AuditService;
-import org.apache.hadoop.gateway.audit.api.AuditServiceFactory;
-import org.apache.hadoop.gateway.audit.api.Auditor;
-import org.apache.hadoop.gateway.audit.api.ResourceType;
-import org.apache.hadoop.gateway.audit.log4j.audit.AuditConstants;
-import org.apache.hadoop.gateway.filter.security.AbstractIdentityAssertionBase;
-import org.apache.hadoop.gateway.i18n.GatewaySpiResources;
-import org.apache.hadoop.gateway.i18n.resources.ResourcesFactory;
-import org.apache.hadoop.gateway.security.GroupPrincipal;
-import org.apache.hadoop.gateway.security.ImpersonatedPrincipal;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-
-/**
- *
- */
-public abstract class AbstractIdentityAssertionFilter extends
-  AbstractIdentityAssertionBase implements Filter {
-
-  private static final GatewaySpiResources RES = ResourcesFactory.get( GatewaySpiResources.class );
-  private static AuditService auditService = AuditServiceFactory.getAuditService();
-  private static Auditor auditor = auditService.getAuditor(
-        AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
-        AuditConstants.KNOX_COMPONENT_NAME );
-
-  /**
-   * 
-   */
-  public AbstractIdentityAssertionFilter() {
-    super();
-  }
-
-  /**
-   * This method returns a Stringp[] of new group principal names to use
-   * based on implementation specific mapping or lookup mechanisms.
-   * Returning null means that whatever set of GroupPrincipals is in the
-   * provided Subject is sufficient to use and no additional mapping is required.
-   * @param mappedPrincipalName username for the authenticated identity - post mapUserPrincipal mapping.
-   * @param subject the existing Subject from the authentication event which may or may not contain GroupPrincipals.
-   * @return String[] of new principal names to use as GroupPrincipals or null.
-   */
-  public abstract String[] mapGroupPrincipals(String mappedPrincipalName, Subject subject);
-
-  /**
-   * This method is used to map the username of the authenticated identity to some other
-   * principal name based on an implementation specific mechanism. It will either return
-   * a new principal name or the provided principal name if there is no mapping required.
-   * @param principalName
-   * @return new username or the provided principalName
-   */
-  public abstract String mapUserPrincipal(String principalName);
-
-  /**
-   * @param wrapper
-   * @param response
-   * @param chain
-   * @param mappedPrincipalName
-   * @param groups
-   */
-  protected void continueChainAsPrincipal(HttpServletRequestWrapper request, ServletResponse response,
-      FilterChain chain, String mappedPrincipalName, String[] groups) throws IOException,
-      ServletException {
-        Subject subject = null;
-        Principal impersonationPrincipal = null;
-        Principal primaryPrincipal = null;
-        
-        // get the current subject and determine whether we need another doAs with 
-        // an impersonatedPrincipal and/or mapped group principals
-        boolean impersonationNeeded = false;
-        boolean groupsMapped = false;
-        
-        // look up the current Java Subject and assosciated group principals
-        Subject currentSubject = Subject.getSubject(AccessController.getContext());
-        Set<?> currentGroups = currentSubject.getPrincipals(GroupPrincipal.class);
-        
-        primaryPrincipal = (PrimaryPrincipal) currentSubject.getPrincipals(PrimaryPrincipal.class).toArray()[0];
-        if (primaryPrincipal != null) {
-          if (!primaryPrincipal.getName().equals(mappedPrincipalName)) {
-            impersonationNeeded = true;
-            auditService.getContext().setProxyUsername( mappedPrincipalName );
-            auditor.audit( Action.IDENTITY_MAPPING, primaryPrincipal.getName(), 
-                ResourceType.PRINCIPAL, ActionOutcome.SUCCESS, RES.effectiveUser(mappedPrincipalName) );
-          }
-        }
-        else {
-          // something is amiss - authentication/federation providers should have run
-          // before identity assertion and should have ensured that the appropriate
-          // principals were added to the current subject
-          // TODO: log as appropriate
-          primaryPrincipal = new PrimaryPrincipal(((HttpServletRequest) request).getUserPrincipal().getName());
-        }
-        
-        groupsMapped = groups != null || !currentGroups.isEmpty();
-        
-        if (impersonationNeeded || groupsMapped) {
-          // gonna need a new subject and doAs
-          subject = new Subject();
-          Set<Principal> principals = subject.getPrincipals();
-          principals.add(primaryPrincipal);
-          
-          // map group principals from current Subject into newly created Subject
-          for (Object obj : currentGroups) {
-            principals.add((Principal)obj);
-          }
-          
-          if (impersonationNeeded) {
-            impersonationPrincipal = new ImpersonatedPrincipal(mappedPrincipalName);
-            subject.getPrincipals().add(impersonationPrincipal);
-          }
-          if (groupsMapped) {
-            addMappedGroupsToSubject(mappedPrincipalName, groups, subject);
-          }
-          doAs(request, response, chain, subject);
-        }
-        else {
-          doFilterInternal(request, response, chain);
-        }
-      }
-
-  private void doAs(final ServletRequest request, final ServletResponse response, final FilterChain chain, Subject subject)
-      throws IOException, ServletException {
-    try {
-      Subject.doAs(
-        subject,
-        new PrivilegedExceptionAction<Object>() {
-          public Object run() throws Exception {
-            doFilterInternal(request, response, chain);
-            return null;
-          }
-        });
-    }
-    catch (PrivilegedActionException e) {
-      Throwable t = e.getCause();
-      if (t instanceof IOException) {
-        throw (IOException) t;
-      }
-      else if (t instanceof ServletException) {
-        throw (ServletException) t;
-      }
-      else {
-        throw new ServletException(t);
-      }
-    }
-  }
-
-  private void addMappedGroupsToSubject(String mappedPrincipalName, String[] groups, Subject subject) {
-    if (groups != null) {
-      auditor.audit( Action.IDENTITY_MAPPING, mappedPrincipalName, ResourceType.PRINCIPAL, 
-          ActionOutcome.SUCCESS, RES.groupsList( Arrays.toString( groups ) ) );
-
-      for (int i = 0; i < groups.length; i++) {
-        subject.getPrincipals().add(new GroupPrincipal(groups[i]));
-      }
-    }
-  }
-
-  private void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain)
-      throws IOException, ServletException {
-    chain.doFilter(request, response);
-  }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/CommonIdentityAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/CommonIdentityAssertionFilter.java b/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/CommonIdentityAssertionFilter.java
deleted file mode 100644
index 06dbfb2..0000000
--- a/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/CommonIdentityAssertionFilter.java
+++ /dev/null
@@ -1,144 +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.hadoop.gateway.identityasserter.common.filter;
-
-import javax.security.auth.Subject;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletRequestWrapper;
-
-import org.apache.commons.lang.ArrayUtils;
-import org.apache.hadoop.gateway.identityasserter.common.filter.AbstractIdentityAssertionFilter;
-import org.apache.hadoop.gateway.security.principal.PrincipalMappingException;
-import org.apache.hadoop.gateway.security.principal.SimplePrincipalMapper;
-
-import java.io.IOException;
-import java.security.AccessController;
-
-public class CommonIdentityAssertionFilter extends AbstractIdentityAssertionFilter {
-  private static final String GROUP_PRINCIPAL_MAPPING = "group.principal.mapping";
-  private static final String PRINCIPAL_MAPPING = "principal.mapping";
-  private SimplePrincipalMapper mapper = new SimplePrincipalMapper();
-
-  /* (non-Javadoc)
-   * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
-   */
-  @Override
-  public void init(FilterConfig filterConfig) throws ServletException {
-    String principalMapping = filterConfig.getInitParameter(PRINCIPAL_MAPPING);
-    if (principalMapping == null || principalMapping.isEmpty()) {
-      principalMapping = filterConfig.getServletContext().getInitParameter(PRINCIPAL_MAPPING);
-    }
-    String groupPrincipalMapping = filterConfig.getInitParameter(GROUP_PRINCIPAL_MAPPING);
-    if (groupPrincipalMapping == null || groupPrincipalMapping.isEmpty()) {
-      groupPrincipalMapping = filterConfig.getServletContext().getInitParameter(GROUP_PRINCIPAL_MAPPING);
-    }
-    if (principalMapping != null && !principalMapping.isEmpty() || groupPrincipalMapping != null && !groupPrincipalMapping.isEmpty()) {
-      try {
-        mapper.loadMappingTable(principalMapping, groupPrincipalMapping);
-      } catch (PrincipalMappingException e) {
-        throw new ServletException("Unable to load principal mapping table.", e);
-      }
-    }
-  }
-
-  /* (non-Javadoc)
-   * @see javax.servlet.Filter#destroy()
-   */
-  @Override
-  public void destroy() {
-  }
-
-  /**
-   * Obtain the standard javax.security.auth.Subject, retrieve the caller principal, map
-   * to the identity to be asserted as appropriate and create the provider specific
-   * assertion token. Add the assertion token to the request.
-   */
-  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
-      throws IOException, ServletException {
-    Subject subject = Subject.getSubject(AccessController.getContext());
-
-    String principalName = getPrincipalName(subject);
-
-    String mappedPrincipalName = mapUserPrincipalBase(principalName);
-    mappedPrincipalName = mapUserPrincipal(mappedPrincipalName);
-    String[] mappedGroups = mapGroupPrincipals(mappedPrincipalName, subject);
-    String[] groups = mapGroupPrincipals(mappedPrincipalName, subject);
-    groups = combineGroupMappings(mappedGroups, groups);
-
-    HttpServletRequestWrapper wrapper = wrapHttpServletRequest(
-        request, mappedPrincipalName);
-
-    continueChainAsPrincipal(wrapper, response, chain, mappedPrincipalName, groups);
-  }
-
-  /**
-   * @param mappedGroups
-   * @param groups
-   * @return
-   */
-  private String[] combineGroupMappings(String[] mappedGroups, String[] groups) {
-    if (mappedGroups != null && groups != null) {
-      return (String[])ArrayUtils.addAll(mappedGroups, groups);
-    }
-    else {
-      return groups != null ? groups : mappedGroups;
-    }
-  }
-
-  public HttpServletRequestWrapper wrapHttpServletRequest(
-      ServletRequest request, String mappedPrincipalName) {
-    // wrap the request so that the proper principal is returned
-    // from request methods
-    IdentityAsserterHttpServletRequestWrapper wrapper =
-        new IdentityAsserterHttpServletRequestWrapper(
-        (HttpServletRequest)request, 
-        mappedPrincipalName);
-    return wrapper;
-  }
-
-  protected String[] mapGroupPrincipalsBase(String mappedPrincipalName, Subject subject) {
-    return mapper.mapGroupPrincipal(mappedPrincipalName);
-  }
-
-  protected String mapUserPrincipalBase(String principalName) {
-    return mapper.mapUserPrincipal(principalName);
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.identityasserter.common.filter.AbstractIdentityAssertionFilter#mapGroupPrincipals(java.lang.String, javax.security.auth.Subject)
-   */
-  @Override
-  public String[] mapGroupPrincipals(String mappedPrincipalName, Subject subject) {
-    // NOP
-    return null;
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.identityasserter.common.filter.AbstractIdentityAssertionFilter#mapUserPrincipal(java.lang.String)
-   */
-  @Override
-  public String mapUserPrincipal(String principalName) {
-    // NOP
-    return principalName;
-  }
-}


[26/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteStreamFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteStreamFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteStreamFilter.java
deleted file mode 100644
index d1c693e..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteStreamFilter.java
+++ /dev/null
@@ -1,67 +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.hadoop.gateway.filter.rewrite.impl.xml;
-
-import org.apache.commons.io.input.ReaderInputStream;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStreamFilter;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.stream.XMLStreamException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-
-public class XmlUrlRewriteStreamFilter implements UrlRewriteStreamFilter {
-
-  private static String[] TYPES = new String[]{ "application/xml", "text/xml", "*/xml" };
-  private static String[] NAMES = new String[]{ null };
-
-  @Override
-  public String[] getTypes() {
-    return TYPES;
-  }
-
-  @Override
-  public String[] getNames() {
-    return NAMES;
-  }
-
-  @Override
-  public InputStream filter(
-      InputStream stream,
-      String encoding,
-      UrlRewriter rewriter,
-      Resolver resolver,
-      UrlRewriter.Direction direction,
-      UrlRewriteFilterContentDescriptor config )
-          throws IOException {
-    try {
-      return new ReaderInputStream(
-          new XmlUrlRewriteFilterReader(
-              new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
-    } catch( ParserConfigurationException e ) {
-      throw new IOException( e );
-    } catch( XMLStreamException e ) {
-      throw new IOException( e );
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteActionDescriptorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteActionDescriptorBase.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteActionDescriptorBase.java
deleted file mode 100644
index 27085df..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteActionDescriptorBase.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.hadoop.gateway.filter.rewrite.spi;
-
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
-
-public abstract class UrlRewriteActionDescriptorBase
-    extends UrlRewriteStepDescriptorBase<UrlRewriteActionDescriptor>
-    implements UrlRewriteActionDescriptor {
-
-  private String operation;
-  private String parameter;
-
-  protected UrlRewriteActionDescriptorBase( String type ) {
-    super( type );
-  }
-
-  @Override
-  public String operation() {
-    return operation;
-  }
-
-  @Override
-  public UrlRewriteActionDescriptor operation( String operation ) {
-    this.operation = operation;
-    return this;
-  }
-
-  public void setOperation( String operation ) {
-    operation( operation );
-  }
-
-  public void setOper( String operation ) {
-    operation( operation );
-  }
-
-  public void setOp( String operation ) {
-    operation( operation );
-  }
-
-  public String getOper() {
-    return operation();
-  }
-
-  @Override
-  public String parameter() {
-    return parameter;
-  }
-
-  @Override
-  public UrlRewriteActionDescriptor parameter( String parameter ) {
-    this.parameter = parameter;
-    return this;
-  }
-
-  public void setParameter( String parameter ) {
-    parameter( parameter );
-  }
-
-  public void setParam( String parameter ) {
-    parameter( parameter );
-  }
-
-  public String getParam() {
-    return parameter();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteContext.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteContext.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteContext.java
deleted file mode 100644
index 092a6b0..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteContext.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.hadoop.gateway.filter.rewrite.spi;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.util.urltemplate.Evaluator;
-import org.apache.hadoop.gateway.util.urltemplate.Params;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-public interface UrlRewriteContext {
-
-  UrlRewriter.Direction getDirection();
-
-  Template getOriginalUrl();
-
-  Template getCurrentUrl();
-
-  void setCurrentUrl( Template url );
-
-  /**
-   * Adds parameters to the rewrite context and replaces some of them if they already exist
-   * @param parameters the parameters to be added or replaced
-   */
-  void addParameters( Params parameters );
-
-  Params getParameters();
-
-  Evaluator getEvaluator();
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteFlowDescriptorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteFlowDescriptorBase.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteFlowDescriptorBase.java
deleted file mode 100644
index 97f8c33..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteFlowDescriptorBase.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.hadoop.gateway.filter.rewrite.spi;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFlowDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepFlow;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public abstract class UrlRewriteFlowDescriptorBase<T> extends UrlRewriteStepDescriptorBase<T> implements UrlRewriteFlowDescriptor<T> {
-
-  private UrlRewriteStepFlow flow;
-  private List<UrlRewriteStepDescriptor> steps = new ArrayList<UrlRewriteStepDescriptor>();
-
-  public UrlRewriteFlowDescriptorBase( String type ) {
-    super( type );
-  }
-
-  @Override
-  public UrlRewriteStepFlow flow() {
-    return flow;
-  }
-
-  @SuppressWarnings( "unchecked" )
-  @Override
-  public <F extends UrlRewriteFlowDescriptor<?>> F flow( String flow ) {
-    setFlow( flow );
-    return (F)this;
-  }
-
-  @SuppressWarnings( "unchecked" )
-  @Override
-  public <F extends UrlRewriteFlowDescriptor<?>> F flow( UrlRewriteStepFlow flow ) {
-    setFlow( flow );
-    return (F)this;
-  }
-
-  public void setFlow( UrlRewriteStepFlow flow ) {
-    this.flow = flow;
-  }
-
-  public void setFlow( String flow ) {
-    flow = flow.trim().toUpperCase();
-    this.flow = Enum.valueOf( UrlRewriteStepFlow.class, flow );
-  }
-
-  public String getFlow() {
-    String str = null;
-    if( flow != null ) {
-      str = flow.toString();
-    }
-    return str;
-  }
-
-  @Override
-  public List<UrlRewriteStepDescriptor> steps() {
-    return steps;
-  }
-
-//  @Override
-//  public UrlRewriteMatchDescriptor addMatch() {
-//    UrlRewriteMatchDescriptor step = new UrlRewriteMatchDescriptorExt();
-//    steps.add( step );
-//    return step;
-//  }
-//
-//  @Override
-//  public UrlRewriteCheckDescriptor addCheck() {
-//    UrlRewriteCheckDescriptor step = new UrlRewriteCheckDescriptorExt();
-//    steps.add( step );
-//    return step;
-//  }
-//
-//  @Override
-//  public UrlRewriteControlDescriptor addControl() {
-//    UrlRewriteControlDescriptor step = new UrlRewriteControlDescriptorExt();
-//    steps.add( step );
-//    return step;
-//  }
-//
-//  @Override
-//  public UrlRewriteActionDescriptor addAction() {
-//    UrlRewriteActionDescriptor step = new UrlRewriteActionDescriptorBase();
-//    steps.add( step );
-//    return step;
-//  }
-
-  @SuppressWarnings( "unchecked" )
-  @Override
-  public <T extends UrlRewriteStepDescriptor<?>> T addStep( String type ) {
-    T step = (T)UrlRewriteStepDescriptorFactory.create( type );
-    steps.add( step );
-    return (T)step;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessor.java
deleted file mode 100644
index cf5a331..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessor.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.filter.rewrite.spi;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-public interface UrlRewriteFunctionProcessor<T extends UrlRewriteFunctionDescriptor> extends UrlRewriteResolver {
-
-  String name();
-
-  void initialize( UrlRewriteEnvironment environment, T descriptor ) throws Exception;
-
-  void destroy() throws Exception;
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessorBase.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessorBase.java
deleted file mode 100644
index 987e889..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessorBase.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.filter.rewrite.spi;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-public abstract class UrlRewriteFunctionProcessorBase<T extends UrlRewriteFunctionDescriptor> implements UrlRewriteFunctionProcessor<T> {
-
-  public void initialize( UrlRewriteEnvironment environment, T descriptor ) throws Exception {
-  }
-
-  public void destroy() throws Exception {
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteResolver.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteResolver.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteResolver.java
deleted file mode 100644
index ec07b5b..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteResolver.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.hadoop.gateway.filter.rewrite.spi;
-
-import java.util.List;
-
-public interface UrlRewriteResolver {
-
-  List<String> resolve( UrlRewriteContext context, List<String> parameter ) throws Exception;
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteRulesExporter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteRulesExporter.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteRulesExporter.java
deleted file mode 100644
index b393ce7..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteRulesExporter.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.filter.rewrite.spi;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
-
-import java.io.IOException;
-import java.io.Writer;
-
-public interface UrlRewriteRulesExporter {
-
-  String getFormat();
-
-  void store( UrlRewriteRulesDescriptor rules, Writer writer ) throws IOException;
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteRulesImporter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteRulesImporter.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteRulesImporter.java
deleted file mode 100644
index d342f15..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteRulesImporter.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.filter.rewrite.spi;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
-
-import java.io.IOException;
-import java.io.Reader;
-
-public interface UrlRewriteRulesImporter {
-
-  String getFormat();
-
-  UrlRewriteRulesDescriptor load( Reader reader ) throws IOException;
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStepDescriptorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStepDescriptorBase.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStepDescriptorBase.java
deleted file mode 100644
index 4d520fe..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStepDescriptorBase.java
+++ /dev/null
@@ -1,46 +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.hadoop.gateway.filter.rewrite.spi;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
-
-public abstract class UrlRewriteStepDescriptorBase<T> implements UrlRewriteStepDescriptor<T> {
-
-  private String type;
-
-  public UrlRewriteStepDescriptorBase( String type ) {
-    this.type = type;
-  }
-
-  @Override
-  public String type() {
-    return type;
-  }
-
-  @Override
-  @SuppressWarnings( "unchecked" )
-  public T type( String type ) {
-    this.type = type;
-    return (T)this;
-  }
-
-  public void setType( String type ) {
-    this.type = type;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStepProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStepProcessor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStepProcessor.java
deleted file mode 100644
index 806ec1f..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStepProcessor.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.hadoop.gateway.filter.rewrite.spi;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
-
-public interface UrlRewriteStepProcessor<T extends UrlRewriteStepDescriptor> {
-
-  String getType();
-
-  void initialize( UrlRewriteEnvironment environment, T descriptor ) throws Exception;
-
-  UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception;
-
-  void destroy() throws Exception;
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStepStatus.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStepStatus.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStepStatus.java
deleted file mode 100644
index 619652f..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStepStatus.java
+++ /dev/null
@@ -1,20 +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.hadoop.gateway.filter.rewrite.spi;
-
-public enum UrlRewriteStepStatus { SUCCESS, FAILURE, FINISHED }

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStreamFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStreamFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStreamFilter.java
deleted file mode 100644
index 413b94b..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/spi/UrlRewriteStreamFilter.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.hadoop.gateway.filter.rewrite.spi;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import static org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter.Direction;
-
-// The rewriter will try to find either a stream or reader createFilter for the mime/type and name.
-public interface UrlRewriteStreamFilter {
-
-  String[] getTypes();
-
-  String[] getNames();
-
-  InputStream filter(
-      InputStream stream,
-      String encoding,
-      UrlRewriter rewriter,
-      Resolver resolver,
-      Direction direction,
-      UrlRewriteFilterContentDescriptor config )
-          throws IOException;
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/CookieScopeServletFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/CookieScopeServletFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/CookieScopeServletFilter.java
new file mode 100644
index 0000000..93f2dc8
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/CookieScopeServletFilter.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.knox.gateway.filter.rewrite.api;
+
+import java.io.IOException;
+
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.filter.AbstractGatewayFilter;
+import org.apache.knox.gateway.filter.rewrite.impl.CookieScopeResponseWrapper;
+
+public class CookieScopeServletFilter extends AbstractGatewayFilter {
+
+  private String gatewayPath;
+
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+    super.init( filterConfig );
+    gatewayPath = filterConfig.getInitParameter("gateway.path");
+  }
+
+  @Override
+  protected void doFilter( HttpServletRequest request, HttpServletResponse response, FilterChain chain )
+      throws IOException, ServletException {
+    chain.doFilter( request, new CookieScopeResponseWrapper(response, gatewayPath));
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/FrontendFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/FrontendFunctionDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/FrontendFunctionDescriptor.java
new file mode 100644
index 0000000..c3b63cd
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/FrontendFunctionDescriptor.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+public class FrontendFunctionDescriptor implements UrlRewriteFunctionDescriptor<FrontendFunctionDescriptor> {
+
+  public static final String FUNCTION_NAME = "frontend";
+
+  public static final String FRONTEND_URI_ATTRIBUTE = "org.apache.knox.gateway.frontend.uri";
+
+  @Override
+  public String name() {
+    return FUNCTION_NAME;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteEnvironment.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteEnvironment.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteEnvironment.java
new file mode 100644
index 0000000..754d752
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteEnvironment.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+
+import java.io.IOException;
+import java.net.URL;
+
+public interface UrlRewriteEnvironment extends Resolver {
+
+  URL getResource( String name ) throws IOException;
+
+  <T> T getAttribute( String name );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterApplyDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterApplyDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterApplyDescriptor.java
new file mode 100644
index 0000000..4722322
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterApplyDescriptor.java
@@ -0,0 +1,27 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+public interface UrlRewriteFilterApplyDescriptor
+    extends UrlRewriteFilterPathDescriptor<UrlRewriteFilterApplyDescriptor> {
+
+  String rule();
+
+  UrlRewriteFilterApplyDescriptor rule( String rule );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterBufferDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterBufferDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterBufferDescriptor.java
new file mode 100644
index 0000000..f67cd83
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterBufferDescriptor.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.knox.gateway.filter.rewrite.api;
+
+public interface UrlRewriteFilterBufferDescriptor
+    extends UrlRewriteFilterPathDescriptor, UrlRewriteFilterGroupDescriptor {
+
+  public UrlRewriteFilterDetectDescriptor addDetect( String path, String value );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterContentDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterContentDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterContentDescriptor.java
new file mode 100644
index 0000000..84b22eb
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterContentDescriptor.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.knox.gateway.filter.rewrite.api;
+
+public interface UrlRewriteFilterContentDescriptor extends UrlRewriteFilterGroupDescriptor {
+
+  String type();
+
+  String asType();
+
+  UrlRewriteFilterContentDescriptor type( String type );
+
+  UrlRewriteFilterContentDescriptor asType( String type );
+
+  UrlRewriteFilterBufferDescriptor addBuffer( String path );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterDescriptor.java
new file mode 100644
index 0000000..3d9db56
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterDescriptor.java
@@ -0,0 +1,37 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+import javax.activation.MimeType;
+import java.util.List;
+
+public interface UrlRewriteFilterDescriptor {
+
+  String name();
+
+  UrlRewriteFilterDescriptor name( String name );
+
+  List<UrlRewriteFilterContentDescriptor> getContents();
+
+  UrlRewriteFilterContentDescriptor getContent( String type );
+
+  UrlRewriteFilterContentDescriptor getContent( MimeType type );
+
+  UrlRewriteFilterContentDescriptor addContent( String type );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterDetectDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterDetectDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterDetectDescriptor.java
new file mode 100644
index 0000000..e2dec91
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterDetectDescriptor.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.knox.gateway.filter.rewrite.api;
+
+public interface UrlRewriteFilterDetectDescriptor
+    extends UrlRewriteFilterPathDescriptor, UrlRewriteFilterGroupDescriptor {
+
+  String value();
+
+  UrlRewriteFilterDetectDescriptor value( String value );
+
+  <C> C compiledValue();
+
+  UrlRewriteFilterDetectDescriptor compiledValue( String compiledValue );
+
+  <C> C compiledValue( Compiler<C> compiler );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterGroupDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterGroupDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterGroupDescriptor.java
new file mode 100644
index 0000000..49064e7
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterGroupDescriptor.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.knox.gateway.filter.rewrite.api;
+
+import java.util.List;
+
+public interface UrlRewriteFilterGroupDescriptor extends UrlRewriteFilterPathDescriptor {
+
+  public List<UrlRewriteFilterPathDescriptor> getSelectors();
+
+  public void addSelector( UrlRewriteFilterPathDescriptor selector );
+
+  UrlRewriteFilterApplyDescriptor addApply( String path, String rule );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterPathDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterPathDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterPathDescriptor.java
new file mode 100644
index 0000000..d94e288
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterPathDescriptor.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.knox.gateway.filter.rewrite.api;
+
+public interface UrlRewriteFilterPathDescriptor<T> {
+
+  String path();
+
+  T path( String path );
+
+  <C> C compiledPath();
+
+  T compiledPath( Object compilePath );
+
+  <C> C compiledPath( Compiler<C> compiler );
+
+  interface Compiler<C> {
+    // The returned compiled version of the expression must be thread safe.
+    // The compiled param will be the result of the last successful call to this method for this instance of
+    // the descriptor node.
+    C compile( String expression, C compiled );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterScopeDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterScopeDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterScopeDescriptor.java
new file mode 100644
index 0000000..5058dbf
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFilterScopeDescriptor.java
@@ -0,0 +1,22 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+public interface UrlRewriteFilterScopeDescriptor
+    extends UrlRewriteFilterPathDescriptor, UrlRewriteFilterGroupDescriptor {
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFlowDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFlowDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFlowDescriptor.java
new file mode 100644
index 0000000..7d48916
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFlowDescriptor.java
@@ -0,0 +1,42 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+import java.util.List;
+
+public interface UrlRewriteFlowDescriptor<T> extends UrlRewriteStepDescriptor<T> {
+
+  UrlRewriteStepFlow flow();
+
+  <F extends UrlRewriteFlowDescriptor<?>> F flow( String flow );
+
+  <F extends UrlRewriteFlowDescriptor<?>> F flow( UrlRewriteStepFlow flow );
+
+  List<UrlRewriteStepDescriptor> steps();
+
+//  UrlRewriteMatchDescriptor addMatch();
+//
+//  UrlRewriteCheckDescriptor addCheck();
+//
+//  UrlRewriteActionDescriptor addAction();
+//
+//  UrlRewriteControlDescriptor addControl();
+
+  <T extends UrlRewriteStepDescriptor<?>> T addStep( String type );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptor.java
new file mode 100644
index 0000000..4d7591a
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptor.java
@@ -0,0 +1,24 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+public interface UrlRewriteFunctionDescriptor<T> {
+
+  String name();
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptorFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptorFactory.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptorFactory.java
new file mode 100644
index 0000000..c9f33f5
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptorFactory.java
@@ -0,0 +1,61 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.ServiceLoader;
+import java.util.Set;
+
+public abstract class UrlRewriteFunctionDescriptorFactory {
+
+  private static Map<String,Class<? extends UrlRewriteFunctionDescriptor>> MAP
+      = (Map<String, Class<? extends UrlRewriteFunctionDescriptor>>)loadDescriptors();
+
+  private UrlRewriteFunctionDescriptorFactory() {
+  }
+
+  @SuppressWarnings("unchecked")
+  public static <T extends UrlRewriteFunctionDescriptor<?>> T create( String name ) {
+    try {
+      Class<? extends UrlRewriteFunctionDescriptor> descriptorClass = MAP.get( name );
+      return (T)descriptorClass.newInstance();
+    } catch( InstantiationException e ) {
+      throw new IllegalArgumentException( name );
+    } catch( IllegalAccessException e ) {
+      throw new IllegalArgumentException( name );
+    }
+  }
+
+  private static Map<String,Class<? extends UrlRewriteFunctionDescriptor>> loadDescriptors() {
+    Map<String,Class<? extends UrlRewriteFunctionDescriptor>> map
+        = new HashMap<>();
+    ServiceLoader<? extends UrlRewriteFunctionDescriptor> descriptors
+        = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
+    for( UrlRewriteFunctionDescriptor descriptor : descriptors ) {
+      String functionName = descriptor.name();
+      Class<? extends UrlRewriteFunctionDescriptor> descriptorClass = descriptor.getClass() ;
+      map.put( functionName, descriptorClass );
+    }
+    return map;
+  }
+
+  public static Set<String> getNames() {
+    return MAP.keySet();
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessor.java
new file mode 100644
index 0000000..381af18
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessor.java
@@ -0,0 +1,179 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+import org.apache.knox.gateway.filter.rewrite.ext.ScopedMatcher;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteContextImpl;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteFunctionProcessorFactory;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteRuleProcessorHolder;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteStepProcessorHolder;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.util.urltemplate.Matcher;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class UrlRewriteProcessor implements UrlRewriter {
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+
+  UrlRewriteEnvironment environment;
+  UrlRewriteRulesDescriptor descriptor;
+  Map<String,UrlRewriteRuleProcessorHolder> rules = new HashMap<>();
+  ScopedMatcher inbound = new ScopedMatcher();
+  ScopedMatcher outbound = new ScopedMatcher();
+  Map<String,UrlRewriteFunctionProcessor> functions = new HashMap<>();
+
+  public UrlRewriteProcessor() {
+  }
+
+  // Convert the descriptor into processors.
+  public void initialize( UrlRewriteEnvironment environment, UrlRewriteRulesDescriptor descriptor ) {
+    this.environment = environment;
+    this.descriptor = descriptor;
+    initializeFunctions( descriptor );
+    initializeRules( descriptor );
+  }
+
+  public UrlRewriteRulesDescriptor getConfig() {
+    return descriptor;
+  }
+
+  @SuppressWarnings("unchecked")
+  private void initializeFunctions( UrlRewriteRulesDescriptor rules ) {
+    for( String name : UrlRewriteFunctionDescriptorFactory.getNames() ) {
+      try {
+        UrlRewriteFunctionDescriptor descriptor = rules.getFunction( name );
+        UrlRewriteFunctionProcessor processor = UrlRewriteFunctionProcessorFactory.create( name, descriptor );
+        processor.initialize( environment, descriptor );
+        functions.put( name, processor );
+      } catch( Exception e ) {
+        // Ignore it and it won't be available as a function.
+        LOG.failedToInitializeRewriteFunctions( e );
+      }
+    }
+  }
+
+  private void initializeRules( UrlRewriteRulesDescriptor descriptor ) {
+    for( UrlRewriteRuleDescriptor ruleDescriptor : descriptor.getRules() ) {
+      try {
+        UrlRewriteRuleProcessorHolder ruleProcessor = new UrlRewriteRuleProcessorHolder();
+        ruleProcessor.initialize( environment, ruleDescriptor );
+        if( !rules.containsKey( ruleDescriptor.name() ) ) {
+          rules.put( ruleDescriptor.name(), ruleProcessor );
+        }
+        Template template = ruleDescriptor.template();
+        if( template != null ) {
+          EnumSet<Direction> directions = ruleDescriptor.directions();
+          if( directions == null || directions.isEmpty() ) {
+            inbound.add( template, ruleProcessor );
+            outbound.add( template, ruleProcessor );
+          } else if( directions.contains( Direction.IN ) ) {
+            inbound.add( template, ruleProcessor );
+          } else if ( directions.contains( Direction.OUT ) ) {
+            outbound.add( template, ruleProcessor );
+          }
+        }
+      } catch( Exception e ) {
+        LOG.failedToInitializeRewriteRules( e );
+      }
+    }
+  }
+
+  public void destroy() {
+    for( UrlRewriteStepProcessorHolder rule : rules.values() ) {
+      try {
+        rule.destroy();
+      } catch ( Exception e ) {
+        LOG.failedToDestroyRewriteStepProcessor( e );
+      }
+    }
+    for( UrlRewriteFunctionProcessor function : functions.values() ) {
+      try {
+        function.destroy();
+      } catch( Exception e ) {
+        LOG.failedToDestroyRewriteFunctionProcessor( e );
+      }
+    }
+  }
+
+  @Override
+  public Template rewrite( Resolver resolver, Template inputUri, Direction direction, String ruleName ) {
+    Template outputUri = inputUri;
+    String serviceRole = null;
+    if (resolver != null) {
+      List<String> serviceRoles = resolver.resolve("service.role");
+      if ( serviceRoles != null && !serviceRoles.isEmpty() ) {
+        serviceRole = serviceRoles.get(0);
+      }
+    }
+    UrlRewriteStepProcessorHolder stepHolder = null;
+    String effectiveRuleName = null;
+    if( ruleName == null || "*".equals( ruleName ) ) {
+      ruleName = null; // Used for logging later.
+      Matcher<UrlRewriteRuleProcessorHolder>.Match match = null;
+      switch( direction ) {
+        case IN:
+          match = inbound.match( outputUri, serviceRole );
+          break;
+        case OUT:
+          match = outbound.match( outputUri, serviceRole );
+          break;
+      }
+      if( match != null ) {
+        stepHolder = match.getValue();
+        effectiveRuleName = match.getValue().getRuleName();
+      }
+    } else if( !ruleName.isEmpty() ) {
+      stepHolder = rules.get( ruleName );
+      effectiveRuleName = ruleName;
+    }
+    if( stepHolder != null ) {
+      UrlRewriteContext context = new UrlRewriteContextImpl( environment, resolver, functions, direction, inputUri );
+      try {
+        UrlRewriteStepStatus stepStatus = stepHolder.process( context );
+        if( UrlRewriteStepStatus.SUCCESS == stepStatus ) {
+          outputUri = context.getCurrentUrl();
+          if( ruleName == null ) {
+            LOG.rewroteUrlViaImplicitRule( inputUri, direction, effectiveRuleName, outputUri );
+          } else {
+            LOG.rewroteUrlViaExplicitRule( inputUri, direction, effectiveRuleName, outputUri );
+          }
+        } else {
+          LOG.failedToRewriteUrl( inputUri, direction, effectiveRuleName, stepStatus );
+          outputUri = null;
+        }
+      } catch( Exception e ) {
+        LOG.failedToRewriteUrlDueToException( inputUri, direction, effectiveRuleName, e );
+        outputUri = null;
+      }
+    } else {
+      LOG.noRuleMatchingUrl( inputUri, direction );
+    }
+    return outputUri;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRuleDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRuleDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRuleDescriptor.java
new file mode 100644
index 0000000..b65670a
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRuleDescriptor.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.knox.gateway.filter.rewrite.api;
+
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.net.URISyntaxException;
+import java.util.EnumSet;
+
+/**
+ *  <rule name="..." pattern="..." dir="request" flow="and"><match></match></rule>
+ */
+public interface UrlRewriteRuleDescriptor extends UrlRewriteFlowDescriptor<UrlRewriteRuleDescriptor> {
+
+  String name();
+
+  UrlRewriteStepDescriptor name( String name );
+
+  String scope();
+
+  UrlRewriteStepDescriptor scope( String scope );
+
+  EnumSet<UrlRewriter.Direction> directions();
+
+  UrlRewriteRuleDescriptor directions( String directions );
+
+  UrlRewriteRuleDescriptor directions( UrlRewriter.Direction... directions );
+
+  String pattern();
+
+  UrlRewriteRuleDescriptor pattern( String pattern ) throws URISyntaxException;
+
+  Template template();
+
+  UrlRewriteRuleDescriptor template( Template pattern );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptor.java
new file mode 100644
index 0000000..f046921
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptor.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.knox.gateway.filter.rewrite.api;
+
+import java.util.List;
+
+/**
+ * <rules><rule></rule></rules>
+ */
+public interface UrlRewriteRulesDescriptor {
+
+  void addRules( UrlRewriteRulesDescriptor rules );
+
+  List<UrlRewriteFunctionDescriptor> getFunctions();
+
+  <T extends UrlRewriteFunctionDescriptor<?>> T getFunction( String name );
+
+  <T extends UrlRewriteFunctionDescriptor<?>> T addFunction( String name );
+
+
+  List<UrlRewriteRuleDescriptor> getRules();
+
+  UrlRewriteRuleDescriptor getRule( String name );
+
+  UrlRewriteRuleDescriptor newRule();
+
+  UrlRewriteRuleDescriptor addRule( String name );
+
+  void addRule( UrlRewriteRuleDescriptor rule );
+
+
+  List<UrlRewriteFilterDescriptor> getFilters();
+
+  UrlRewriteFilterDescriptor getFilter( String name );
+
+  UrlRewriteFilterDescriptor newFilter();
+
+  UrlRewriteFilterDescriptor addFilter( String name );
+
+  void addFilter( UrlRewriteFilterDescriptor filter );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactory.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactory.java
new file mode 100644
index 0000000..c529809
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactory.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.knox.gateway.filter.rewrite.api;
+
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteResources;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteRulesDescriptorImpl;
+import org.apache.knox.gateway.filter.rewrite.impl.xml.XmlUrlRewriteRulesExporter;
+import org.apache.knox.gateway.filter.rewrite.impl.xml.XmlUrlRewriteRulesImporter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteRulesExporter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteRulesImporter;
+import org.apache.knox.gateway.i18n.resources.ResourcesFactory;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.Writer;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+public abstract class UrlRewriteRulesDescriptorFactory {
+
+  private static UrlRewriteResources RES = ResourcesFactory.get( UrlRewriteResources.class );
+
+  private static Map<String, UrlRewriteRulesImporter> IMPORTERS = loadImporters();
+  private static Map<String, UrlRewriteRulesExporter> EXPORTERS = loadExporters();
+
+  private UrlRewriteRulesDescriptorFactory() {
+  }
+
+  public static UrlRewriteRulesDescriptor create() {
+    return new UrlRewriteRulesDescriptorImpl();
+  }
+
+  public static UrlRewriteRulesDescriptor load( String format, Reader reader ) throws IOException {
+    UrlRewriteRulesImporter importer = IMPORTERS.get( format );
+    if( importer == null ) {
+      throw new IllegalArgumentException( RES.noImporterForFormat( format ) );
+    }
+    return importer.load( reader );
+  }
+
+  public static void store( UrlRewriteRulesDescriptor descriptor, String format, Writer writer ) throws IOException {
+    UrlRewriteRulesExporter exporter = EXPORTERS.get( format );
+    if( exporter == null ) {
+      throw new IllegalArgumentException( RES.noExporterForFormat( format ) );
+    }
+    exporter.store( descriptor, writer );
+  }
+
+  private static Map<String, UrlRewriteRulesImporter> loadImporters() {
+    Map<String, UrlRewriteRulesImporter> map = new ConcurrentHashMap<String, UrlRewriteRulesImporter>();
+    map.put( "xml", new XmlUrlRewriteRulesImporter() );
+    return map;
+  }
+
+  private static Map<String, UrlRewriteRulesExporter> loadExporters() {
+    Map<String, UrlRewriteRulesExporter> map = new ConcurrentHashMap<String, UrlRewriteRulesExporter>();
+    map.put( "xml", new XmlUrlRewriteRulesExporter() );
+    return map;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletContextListener.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletContextListener.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletContextListener.java
new file mode 100644
index 0000000..cce33b2
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletContextListener.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.knox.gateway.filter.rewrite.api;
+
+import javax.servlet.ServletContext;
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
+
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+public class UrlRewriteServletContextListener implements ServletContextListener {
+
+  public static final String PROCESSOR_ATTRIBUTE_NAME = UrlRewriteProcessor.class.getName();
+  public static final String DESCRIPTOR_LOCATION_INIT_PARAM_NAME = "rewriteDescriptorLocation";
+  public static final String DESCRIPTOR_DEFAULT_FILE_NAME = "rewrite.xml";
+  public static final String DESCRIPTOR_DEFAULT_LOCATION = "/WEB-INF/" + DESCRIPTOR_DEFAULT_FILE_NAME;
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+
+  @Override
+  public void contextInitialized( ServletContextEvent event ) {
+    UrlRewriteRulesDescriptor descriptor = null;
+    try {
+      URL url = locateDescriptor( event.getServletContext() );
+      descriptor = loadDescriptor( url );
+    } catch( IOException e ) {
+      throw new IllegalStateException( e );
+    }
+    ServletContext context = event.getServletContext();
+    UrlRewriteEnvironment environment = new UrlRewriteServletEnvironment( context );
+    UrlRewriteProcessor processor = new UrlRewriteProcessor();
+    processor.initialize( environment, descriptor );
+    event.getServletContext().setAttribute( PROCESSOR_ATTRIBUTE_NAME, processor );
+  }
+
+  @Override
+  public void contextDestroyed( ServletContextEvent event ) {
+    UrlRewriteProcessor processor =
+        (UrlRewriteProcessor)event.getServletContext().getAttribute( PROCESSOR_ATTRIBUTE_NAME );
+    event.getServletContext().removeAttribute( PROCESSOR_ATTRIBUTE_NAME );
+    if( processor != null ) {
+      processor.destroy();
+    }
+  }
+
+  public static UrlRewriter getUrlRewriter( ServletContext context ) {
+    return ((UrlRewriteProcessor)context.getAttribute( PROCESSOR_ATTRIBUTE_NAME ));
+  }
+
+  private static URL locateDescriptor( ServletContext context ) throws IOException {
+    String param = context.getInitParameter( DESCRIPTOR_LOCATION_INIT_PARAM_NAME );
+    if( param == null ) {
+      param = DESCRIPTOR_DEFAULT_LOCATION;
+    }
+    URL url;
+    try {
+      url = context.getResource( param );
+    } catch( MalformedURLException e ) {
+      // Ignore it and try using the value directly as a URL.
+      url = null;
+    }
+    if( url == null ) {
+      url = new URL( param );
+    }
+    if( url == null ) {
+      throw new FileNotFoundException( param );
+    }
+    return url;
+  }
+
+  private static UrlRewriteRulesDescriptor loadDescriptor( URL url ) throws IOException {
+    InputStream stream = url.openStream();
+    Reader reader = new InputStreamReader( stream, "UTF-8" );
+    UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.load( "xml", reader );
+    try {
+      reader.close();
+    } catch( IOException closeException ) {
+      LOG.failedToLoadRewriteRulesDescriptor( closeException );
+    }
+    return descriptor;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletEnvironment.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletEnvironment.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletEnvironment.java
new file mode 100644
index 0000000..074098c
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletEnvironment.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.knox.gateway.filter.rewrite.api;
+
+import javax.servlet.ServletContext;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Arrays;
+import java.util.List;
+
+public class UrlRewriteServletEnvironment implements UrlRewriteEnvironment {
+
+  private ServletContext context;
+
+  public UrlRewriteServletEnvironment( ServletContext context ) {
+    this.context = context;
+  }
+
+  @Override
+  public URL getResource( String name ) throws MalformedURLException {
+    URL url = context.getResource( name );
+    return url;
+  }
+
+  @Override
+  public <T> T getAttribute( String name ) {
+    T attribute = (T)context.getAttribute( name );
+    return attribute;
+  }
+
+  @Override
+  public List<String> resolve( String name ) {
+    List<String> values = null;
+    String value = context.getInitParameter( name );
+    if( value != null ) {
+      values = Arrays.asList( value );
+    }
+    return values;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletFilter.java
new file mode 100644
index 0000000..dc49dbc
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletFilter.java
@@ -0,0 +1,63 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+import org.apache.knox.gateway.filter.AbstractGatewayFilter;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteRequest;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteResponse;
+import org.apache.knox.gateway.util.MimeTypes;
+
+import javax.activation.MimeType;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ *
+ */
+public class UrlRewriteServletFilter extends AbstractGatewayFilter {
+
+  public static final String REQUEST_URL_RULE_PARAM = "request.url";
+  public static final String REQUEST_HEADERS_FILTER_PARAM = "request.headers";
+  public static final String REQUEST_COOKIES_FILTER_PARAM = "request.cookies";
+  public static final String REQUEST_BODY_FILTER_PARAM = "request.body";
+  public static final String RESPONSE_HEADERS_FILTER_PARAM = "response.headers";
+  public static final String RESPONSE_COOKIES_FILTER_PARAM = "response.cookies";
+  public static final String RESPONSE_BODY_FILTER_PARAM = "response.body";
+
+  public static final MimeType HEADERS_MIME_TYPE = MimeTypes.create( "application/x-http-headers", null );
+  public static final MimeType COOKIES_MIME_TYPE = MimeTypes.create( "application/x-http-cookies", null );
+
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+    super.init( filterConfig );
+  }
+
+  @Override
+  protected void doFilter( HttpServletRequest request, HttpServletResponse response, FilterChain chain )
+      throws IOException, ServletException {
+    FilterConfig config = getConfig();
+    UrlRewriteRequest rewriteRequest = new UrlRewriteRequest( config, request );
+    UrlRewriteResponse rewriteResponse = new UrlRewriteResponse( config, rewriteRequest, response );
+    chain.doFilter( rewriteRequest, rewriteResponse );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStepDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStepDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStepDescriptor.java
new file mode 100644
index 0000000..906a3c5
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStepDescriptor.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.knox.gateway.filter.rewrite.api;
+
+public interface UrlRewriteStepDescriptor<T> {
+
+  String type();
+
+  T type( String type );
+
+}


[42/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionProcessorTest.java b/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionProcessorTest.java
deleted file mode 100644
index a54c03b..0000000
--- a/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionProcessorTest.java
+++ /dev/null
@@ -1,248 +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.hadoop.gateway.identityasserter.function;
-
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletFilter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.identityasserter.common.function.UsernameFunctionProcessor;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.test.TestUtils;
-import org.apache.hadoop.test.log.NoOpLogger;
-import org.apache.hadoop.test.mock.MockInteraction;
-import org.apache.hadoop.test.mock.MockServlet;
-import org.apache.http.auth.BasicUserPrincipal;
-import org.eclipse.jetty.servlet.FilterHolder;
-import org.eclipse.jetty.servlet.ServletHolder;
-import org.eclipse.jetty.http.HttpTester;
-import org.eclipse.jetty.servlet.ServletTester;
-import org.eclipse.jetty.util.ArrayQueue;
-import org.eclipse.jetty.util.log.Log;
-import org.hamcrest.core.Is;
-import org.junit.After;
-import org.junit.Test;
-
-import javax.security.auth.Subject;
-import javax.servlet.DispatcherType;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.nio.ByteBuffer;
-import java.nio.charset.Charset;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.Arrays;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.nullValue;
-import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
-import static org.junit.Assert.fail;
-
-public class UsernameFunctionProcessorTest {
-
-  private ServletTester server;
-  private HttpTester.Request request;
-  private HttpTester.Response response;
-  private ArrayQueue<MockInteraction> interactions;
-  private MockInteraction interaction;
-
-  private static URL getTestResource( String name ) {
-    name = UsernameFunctionProcessorTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
-    URL url = ClassLoader.getSystemResource( name );
-    return url;
-  }
-
-  public void setUp( String username, Map<String,String> initParams ) throws Exception {
-    String descriptorUrl = getTestResource( "rewrite.xml" ).toExternalForm();
-
-    Log.setLog( new NoOpLogger() );
-
-    server = new ServletTester();
-    server.setContextPath( "/" );
-    server.getContext().addEventListener( new UrlRewriteServletContextListener() );
-    server.getContext().setInitParameter(
-        UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );
-
-    FilterHolder setupFilter = server.addFilter( SetupFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
-    setupFilter.setFilter( new SetupFilter( username ) );
-    FilterHolder rewriteFilter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
-    if( initParams != null ) {
-      for( Map.Entry<String,String> entry : initParams.entrySet() ) {
-        rewriteFilter.setInitParameter( entry.getKey(), entry.getValue() );
-      }
-    }
-    rewriteFilter.setFilter( new UrlRewriteServletFilter() );
-
-    interactions = new ArrayQueue<MockInteraction>();
-
-    ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
-    servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );
-
-    server.start();
-
-    interaction = new MockInteraction();
-    request = HttpTester.newRequest();
-    response = null;
-  }
-
-  @After
-  public void tearDown() throws Exception {
-    if( server != null ) {
-      server.stop();
-    }
-  }
-
-  @Test
-  public void testInitialize() throws Exception {
-    UsernameFunctionProcessor processor = new UsernameFunctionProcessor();
-    // Shouldn't fail.
-    processor.initialize( null, null );
-  }
-
-  @Test
-  public void testDestroy() throws Exception {
-    UsernameFunctionProcessor processor = new UsernameFunctionProcessor();
-    // Shouldn't fail.
-    processor.destroy();
-  }
-
-  @Test
-  public void testResolve() throws Exception {
-    final UsernameFunctionProcessor processor = new UsernameFunctionProcessor();
-    assertThat( processor.resolve( null, null ), nullValue() );
-    assertThat( processor.resolve( null, Arrays.asList( "test-input" ) ), contains( "test-input" ) );
-    Subject subject = new Subject();
-    subject.getPrincipals().add( new PrimaryPrincipal( "test-username" ) );
-    subject.setReadOnly();
-    Subject.doAs( subject, new PrivilegedExceptionAction<Object>() {
-      @Override
-      public Object run() throws Exception {
-        assertThat( processor.resolve( null, null ), contains( "test-username" ) );
-        assertThat( processor.resolve( null, Arrays.asList( "test-ignored" ) ), contains( "test-username" ) );
-        return null;
-      }
-    } );
-  }
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof UsernameFunctionProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find UsernameFunctionProcessor via service loader." );
-  }
-
-  @Test
-  public void testRequestUrlRewriteOfUsernameViaRewriteRule() throws Exception {
-    Map<String,String> initParams = new HashMap<>();
-    initParams.put( "request.url", "test-rule-username" );
-    setUp( "test-user", initParams );
-
-    String input = "<root/>";
-    String expect = "<root/>";
-
-    // Setup the server side request/response interaction.
-    interaction.expect()
-        .method( "PUT" )
-        .requestUrl( "test-output-scheme://test-input-host:777/test-output-path/test-input-path" )
-        .queryParam( "user.name", "test-user" )
-        .queryParam( "test-query-input-name", "test-query-input-value" )
-        .queryParam( "test-query-output-name", "test-query-output-value" )
-        .contentType( "text/xml" )
-        .content( expect, Charset.forName( "UTF-8" ) );
-    interaction.respond().status( 200 );
-    interactions.add( interaction );
-    request.setMethod( "PUT" );
-    request.setURI( "/test-input-path?test-query-input-name=test-query-input-value" );
-    //request.setVersion( "HTTP/1.1" );
-    request.setHeader( "Host", "test-input-host:777" );
-    request.setHeader( "Content-Type", "text/xml; charset=UTF-8" );
-    request.setContent( input );
-
-    response = TestUtils.execute( server, request );
-
-    // Test the results.
-    assertThat( response.getStatus(), Is.is( 200 ) );
-  }
-
-  private static class SetupFilter implements Filter {
-    private Subject subject;
-
-    public SetupFilter( String userName ) {
-      subject = new Subject();
-      subject.getPrincipals().add( new BasicUserPrincipal( userName ) );
-    }
-
-    @Override
-    public void init( FilterConfig filterConfig ) throws ServletException {
-    }
-
-    @Override
-    public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException {
-      HttpServletRequest httpRequest = ((HttpServletRequest)request);
-      StringBuffer sourceUrl = httpRequest.getRequestURL();
-      String queryString = httpRequest.getQueryString();
-      if( queryString != null ) {
-        sourceUrl.append( "?" );
-        sourceUrl.append( queryString );
-      }
-      try {
-        request.setAttribute(
-            AbstractGatewayFilter.SOURCE_REQUEST_URL_ATTRIBUTE_NAME,
-            Parser.parseLiteral( sourceUrl.toString() ) );
-      } catch( URISyntaxException e ) {
-        throw new ServletException( e );
-      }
-      try {
-        Subject.doAs( subject, new PrivilegedExceptionAction<Void>() {
-          @Override
-          public Void run() throws Exception {
-              chain.doFilter( request, response );
-              return null;
-          }
-        } );
-      } catch( PrivilegedActionException e ) {
-        throw new ServletException( e );
-      }
-    }
-
-    @Override
-    public void destroy() {
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/filter/CommonIdentityAssertionFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/filter/CommonIdentityAssertionFilterTest.java b/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/filter/CommonIdentityAssertionFilterTest.java
new file mode 100644
index 0000000..bd5b32c
--- /dev/null
+++ b/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/filter/CommonIdentityAssertionFilterTest.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.knox.gateway.identityasserter.filter;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+
+import javax.security.auth.Subject;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.identityasserter.common.filter.CommonIdentityAssertionFilter;
+import org.apache.knox.gateway.security.GroupPrincipal;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.easymock.EasyMock;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * @author larry
+ *
+ */
+public class CommonIdentityAssertionFilterTest {
+
+  private String username = null;
+  private String[] mappedGroups = null;
+  private Filter filter = null;
+  
+  @Before
+  public void setup() {
+    filter = new CommonIdentityAssertionFilter() {
+      @Override
+      public String mapUserPrincipal(String principalName) {
+        username = principalName.toUpperCase();
+        return principalName;
+      }
+
+      @Override
+      public String[] mapGroupPrincipals(String principalName, Subject subject) {
+        String[] groups = new String[2];
+        int i = 0;
+        for(GroupPrincipal p : subject.getPrincipals(GroupPrincipal.class)) {
+          groups[i] = p.getName().toUpperCase();
+          i++;
+        }
+        mappedGroups = groups;
+        return groups;
+      }
+    };
+  }
+
+  @Test
+  public void testSimpleFilter() throws ServletException, IOException,
+      URISyntaxException {
+
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.replay( config );
+
+    final HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
+    EasyMock.replay( request );
+
+    final HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
+    EasyMock.replay( response );
+
+    final FilterChain chain = new FilterChain() {
+      @Override
+      public void doFilter(ServletRequest request, ServletResponse response)
+          throws IOException, ServletException {
+      }
+    };
+    
+    Subject subject = new Subject();
+    subject.getPrincipals().add(new PrimaryPrincipal("larry"));
+    subject.getPrincipals().add(new GroupPrincipal("users"));
+    subject.getPrincipals().add(new GroupPrincipal("admin"));
+    try {
+      Subject.doAs(
+        subject,
+        new PrivilegedExceptionAction<Object>() {
+          public Object run() throws Exception {
+            filter.doFilter(request, response, chain);
+            return null;
+          }
+        });
+    }
+    catch (PrivilegedActionException e) {
+      Throwable t = e.getCause();
+      if (t instanceof IOException) {
+        throw (IOException) t;
+      }
+      else if (t instanceof ServletException) {
+        throw (ServletException) t;
+      }
+      else {
+        throw new ServletException(t);
+      }
+    }
+    assertEquals("LARRY", username);
+    assertEquals(mappedGroups.length, 2);
+    assertTrue(mappedGroups[0].equals("USERS") || mappedGroups[0].equals("ADMIN"));
+    assertTrue(mappedGroups[1], mappedGroups[1].equals("USERS") || mappedGroups[1].equals("ADMIN"));
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/filter/IdentityAssertionHttpServletRequestWrapperTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/filter/IdentityAssertionHttpServletRequestWrapperTest.java b/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/filter/IdentityAssertionHttpServletRequestWrapperTest.java
new file mode 100644
index 0000000..745fbdd
--- /dev/null
+++ b/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/filter/IdentityAssertionHttpServletRequestWrapperTest.java
@@ -0,0 +1,279 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.identityasserter.filter;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.knox.gateway.config.GatewayConfig;
+import org.apache.knox.gateway.identityasserter.common.filter.IdentityAsserterHttpServletRequestWrapper;
+import org.apache.hadoop.test.category.FastTests;
+import org.apache.hadoop.test.category.UnitTests;
+import org.apache.hadoop.test.mock.MockHttpServletRequest;
+import org.apache.hadoop.test.mock.MockServletInputStream;
+import org.junit.Test;
+import org.junit.After;
+import org.junit.experimental.categories.Category;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.not;
+
+@Category( { UnitTests.class, FastTests.class } )
+public class IdentityAssertionHttpServletRequestWrapperTest {
+
+  @After
+  public void resetSystemProps() {
+    System.setProperty(GatewayConfig.HADOOP_KERBEROS_SECURED, "false");
+  }
+
+  @Test
+  public void testInsertUserNameInPostMethod() throws IOException {
+    String inputBody = "jar=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaWebHCat%2Fhadoop-examples.jar&class=org.apache.org.apache.hadoop.examples.WordCount&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Finput&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Foutput";
+
+    MockHttpServletRequest request = new MockHttpServletRequest();
+    request.setInputStream( new MockServletInputStream( new ByteArrayInputStream( inputBody.getBytes( "UTF-8" ) ) ) );
+    request.setCharacterEncoding( "UTF-8" );
+    request.setContentType( "application/x-www-form-urlencoded" );
+    request.setMethod("POST");
+
+    IdentityAsserterHttpServletRequestWrapper wrapper
+        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
+
+    String outputBody = IOUtils.toString( wrapper.getInputStream(), wrapper.getCharacterEncoding() );
+    String output = wrapper.getQueryString();
+    assertThat( output, containsString( "user.name=output-user" ) );
+  }
+
+  @Test
+  public void testInsertUserNameInPostMethodWithoutEncoding() throws IOException {
+    String inputBody = "jar=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaWebHCat%2Fhadoop-examples.jar&class=org.apache.org.apache.hadoop.examples.WordCount&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Finput&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Foutput";
+
+    MockHttpServletRequest request = new MockHttpServletRequest();
+    request.setInputStream( new MockServletInputStream( new ByteArrayInputStream( inputBody.getBytes( "UTF-8" ) ) ) );
+    request.setContentType( "application/x-www-form-urlencoded" );
+    request.setMethod("POST");
+
+    IdentityAsserterHttpServletRequestWrapper wrapper
+        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
+
+    String outputBody = IOUtils.toString( wrapper.getInputStream(), wrapper.getCharacterEncoding() );
+    String output = wrapper.getQueryString();
+    assertThat( output, containsString( "user.name=output-user" ) );
+  }
+
+  @Test
+  public void testInsertUserNameInPostMethodWithIso88591Encoding() throws IOException {
+    String inputBody = "jar=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaWebHCat%2Fhadoop-examples.jar&class=org.apache.org.apache.hadoop.examples.WordCount&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Finput&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Foutput";
+
+    MockHttpServletRequest request = new MockHttpServletRequest();
+    request.setInputStream( new MockServletInputStream( new ByteArrayInputStream( inputBody.getBytes( "UTF-8" ) ) ) );
+    request.setContentType( "application/x-www-form-urlencoded" );
+    request.setCharacterEncoding( "ISO-8859-1" );
+    request.setMethod("POST");
+
+    IdentityAsserterHttpServletRequestWrapper wrapper
+        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
+
+    String outputBody = IOUtils.toString( wrapper.getInputStream(), wrapper.getCharacterEncoding() );
+    String output = wrapper.getQueryString();
+    assertThat( output, containsString( "user.name=output-user" ) );
+  }
+
+  @Test
+  public void testOverwriteUserNameInPostMethod() throws IOException {
+    String inputBody = "user.name=input-user&jar=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaWebHCat%2Fhadoop-examples.jar&class=org.apache.org.apache.hadoop.examples.WordCount&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Finput&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Foutput";
+
+    MockHttpServletRequest request = new MockHttpServletRequest();
+    request.setInputStream( new MockServletInputStream( new ByteArrayInputStream( inputBody.getBytes( "UTF-8" ) ) ) );
+    request.setCharacterEncoding( "UTF-8" );
+    request.setContentType( "application/x-www-form-urlencoded" );
+    request.setMethod("POST");
+    
+    IdentityAsserterHttpServletRequestWrapper wrapper
+        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
+
+    String outputBody = IOUtils.toString( wrapper.getInputStream(), wrapper.getCharacterEncoding() );
+    String output = wrapper.getQueryString();
+    assertThat( output, containsString( "user.name=output-user" ) );
+    assertThat( output, not( containsString( "input-user" ) ) );
+  }
+
+  @Test
+  public void testIngoreNonFormBody() throws IOException {
+    String inputBody = "user.name=input-user&jar=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaWebHCat%2Fhadoop-examples.jar&class=org.apache.org.apache.hadoop.examples.WordCount&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Finput&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Foutput";
+
+    MockHttpServletRequest request = new MockHttpServletRequest();
+    request.setInputStream( new MockServletInputStream( new ByteArrayInputStream( inputBody.getBytes( "UTF-8" ) ) ) );
+    request.setCharacterEncoding( "UTF-8" );
+    request.setContentType( "text/plain" );
+
+    IdentityAsserterHttpServletRequestWrapper wrapper
+        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
+
+    String outputBody = IOUtils.toString( wrapper.getInputStream(), wrapper.getCharacterEncoding() );
+
+    assertThat( outputBody, containsString( "user.name=input-user" ) );
+    assertThat( outputBody, not( containsString( "output-user" ) ) );
+  }
+
+  @Test
+  public void testInsertUserNameInQueryString() {
+    String input = "param=value";
+
+    MockHttpServletRequest request = new MockHttpServletRequest();
+    request.setQueryString( input );
+
+    IdentityAsserterHttpServletRequestWrapper wrapper
+        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
+
+    String output = wrapper.getQueryString();
+
+    assertThat( output, containsString( "user.name=output-user" ) );
+  }
+
+  @Test
+  public void testInsertDoAsInQueryString() {
+    System.setProperty(GatewayConfig.HADOOP_KERBEROS_SECURED, "true");
+    MockHttpServletRequest request = new MockHttpServletRequest();
+    request.setQueryString("op=LISTSTATUS&user.name=jack&User.Name=jill&DOas=admin&doas=root");
+
+    IdentityAsserterHttpServletRequestWrapper wrapper
+        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
+
+    String output = wrapper.getQueryString();
+    assertThat(output, is("op=LISTSTATUS&doAs=output-user"));
+  }
+
+  @Test
+  public void testInsertUserNameInNullQueryString() {
+    String input = null;
+
+    MockHttpServletRequest request = new MockHttpServletRequest();
+    request.setQueryString( input );
+
+    IdentityAsserterHttpServletRequestWrapper wrapper
+        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
+
+    String output = wrapper.getQueryString();
+
+    assertThat( output, containsString( "user.name=output-user" ) );
+  }
+
+  @Test
+  public void testInsertUserNameInNullQueryStringForGET() {
+    String input = null;
+
+    MockHttpServletRequest request = new MockHttpServletRequest();
+    request.setQueryString( input );
+
+    IdentityAsserterHttpServletRequestWrapper wrapper
+        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
+
+    String output = wrapper.getQueryString();
+
+    assertThat( output, containsString( "user.name=output-user" ) );
+  }
+
+  @Test
+  public void testInsertUserNameInQueryStringForPOST() {
+    String input = null;
+
+    MockHttpServletRequest request = new MockHttpServletRequest();
+    request.setQueryString( input );
+    request.setMethod("POST");
+
+    IdentityAsserterHttpServletRequestWrapper wrapper
+        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
+
+    String output = wrapper.getQueryString();
+
+    assertThat( output, containsString( "user.name=output-user" ) );
+  }
+
+  @Test
+  public void testOverwriteUserNameInQueryString() {
+    String input = "user.name=input-user";
+
+    MockHttpServletRequest request = new MockHttpServletRequest();
+    request.setQueryString( input );
+
+    IdentityAsserterHttpServletRequestWrapper wrapper
+        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
+
+    String output = wrapper.getQueryString();
+
+    assertThat( output, containsString( "user.name=output-user" ) );
+    assertThat( output, not( containsString( "input-user" ) ) );
+  }
+
+  @Test
+  public void testParameterWithNullValueInQueryString() {
+    String input = "paramWithNullValue&param2=abc";
+
+    MockHttpServletRequest request = new MockHttpServletRequest();
+    request.setQueryString( input );
+
+    IdentityAsserterHttpServletRequestWrapper wrapper
+      = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
+
+    String output = wrapper.getQueryString();
+
+    assertThat( output, containsString( "user.name=output-user" ) );
+    assertThat( output, containsString( "paramWithNullValue" ) );
+    assertThat( output, containsString( "param2=abc" ) );
+  }
+
+  @Test
+  public void testUrlEncode() {
+    String s;
+    HashMap<String,List<String>> m;
+
+    m = new HashMap<>();
+    m.put( "null-values", null );
+    s = IdentityAsserterHttpServletRequestWrapper.urlEncode( m, "UTF-8" );
+    assertThat( s, is( "null-values" ) );
+
+    m = new HashMap<>();
+    m.put( "no-values", new ArrayList<String>(0) );
+    s = IdentityAsserterHttpServletRequestWrapper.urlEncode( m, "UTF-8" );
+    assertThat( s, is( "no-values" ) );
+
+    m = new HashMap<>();
+    List<String> lst = new ArrayList<String>();
+    lst.add("value1");
+    m.put( "one-value", lst);
+    s = IdentityAsserterHttpServletRequestWrapper.urlEncode( m, "UTF-8" );
+    assertThat( s, is( "one-value=value1" ) );
+
+    m = new HashMap<>();
+    lst = new ArrayList<String>();
+    String[] a = {"value1", "value2"};
+    lst.addAll(Arrays.asList(a));
+    m.put( "two-values", lst);
+    s = IdentityAsserterHttpServletRequestWrapper.urlEncode( m, "UTF-8" );
+    assertThat( s, is( "two-values=value1&two-values=value2" ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/function/UsernameFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/function/UsernameFunctionDescriptorTest.java b/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/function/UsernameFunctionDescriptorTest.java
new file mode 100644
index 0000000..3cce3a0
--- /dev/null
+++ b/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/function/UsernameFunctionDescriptorTest.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.knox.gateway.identityasserter.function;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+import org.apache.knox.gateway.identityasserter.common.function.UsernameFunctionDescriptor;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class UsernameFunctionDescriptorTest {
+
+  @Test
+  public void testName() throws Exception {
+    UsernameFunctionDescriptor descriptor = new UsernameFunctionDescriptor();
+    assertThat( descriptor.name(), is( "username" ) );
+  }
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
+    Iterator iterator = loader.iterator();
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof UsernameFunctionDescriptor ) {
+        return;
+      }
+    }
+    fail( "Failed to find UsernameFunctionDescriptor via service loader." );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/function/UsernameFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/function/UsernameFunctionProcessorTest.java b/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/function/UsernameFunctionProcessorTest.java
new file mode 100644
index 0000000..0f9d67c
--- /dev/null
+++ b/gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/function/UsernameFunctionProcessorTest.java
@@ -0,0 +1,247 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.identityasserter.function;
+
+import org.apache.knox.gateway.filter.AbstractGatewayFilter;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletFilter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.identityasserter.common.function.UsernameFunctionProcessor;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.hadoop.test.TestUtils;
+import org.apache.hadoop.test.log.NoOpLogger;
+import org.apache.hadoop.test.mock.MockInteraction;
+import org.apache.hadoop.test.mock.MockServlet;
+import org.apache.http.auth.BasicUserPrincipal;
+import org.eclipse.jetty.servlet.FilterHolder;
+import org.eclipse.jetty.servlet.ServletHolder;
+import org.eclipse.jetty.http.HttpTester;
+import org.eclipse.jetty.servlet.ServletTester;
+import org.eclipse.jetty.util.ArrayQueue;
+import org.eclipse.jetty.util.log.Log;
+import org.hamcrest.core.Is;
+import org.junit.After;
+import org.junit.Test;
+
+import javax.security.auth.Subject;
+import javax.servlet.DispatcherType;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.nio.charset.Charset;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.Arrays;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.nullValue;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
+import static org.junit.Assert.fail;
+
+public class UsernameFunctionProcessorTest {
+
+  private ServletTester server;
+  private HttpTester.Request request;
+  private HttpTester.Response response;
+  private ArrayQueue<MockInteraction> interactions;
+  private MockInteraction interaction;
+
+  private static URL getTestResource( String name ) {
+    name = UsernameFunctionProcessorTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
+    URL url = ClassLoader.getSystemResource( name );
+    return url;
+  }
+
+  public void setUp( String username, Map<String,String> initParams ) throws Exception {
+    String descriptorUrl = getTestResource( "rewrite.xml" ).toExternalForm();
+
+    Log.setLog( new NoOpLogger() );
+
+    server = new ServletTester();
+    server.setContextPath( "/" );
+    server.getContext().addEventListener( new UrlRewriteServletContextListener() );
+    server.getContext().setInitParameter(
+        UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );
+
+    FilterHolder setupFilter = server.addFilter( SetupFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
+    setupFilter.setFilter( new SetupFilter( username ) );
+    FilterHolder rewriteFilter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
+    if( initParams != null ) {
+      for( Map.Entry<String,String> entry : initParams.entrySet() ) {
+        rewriteFilter.setInitParameter( entry.getKey(), entry.getValue() );
+      }
+    }
+    rewriteFilter.setFilter( new UrlRewriteServletFilter() );
+
+    interactions = new ArrayQueue<MockInteraction>();
+
+    ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
+    servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );
+
+    server.start();
+
+    interaction = new MockInteraction();
+    request = HttpTester.newRequest();
+    response = null;
+  }
+
+  @After
+  public void tearDown() throws Exception {
+    if( server != null ) {
+      server.stop();
+    }
+  }
+
+  @Test
+  public void testInitialize() throws Exception {
+    UsernameFunctionProcessor processor = new UsernameFunctionProcessor();
+    // Shouldn't fail.
+    processor.initialize( null, null );
+  }
+
+  @Test
+  public void testDestroy() throws Exception {
+    UsernameFunctionProcessor processor = new UsernameFunctionProcessor();
+    // Shouldn't fail.
+    processor.destroy();
+  }
+
+  @Test
+  public void testResolve() throws Exception {
+    final UsernameFunctionProcessor processor = new UsernameFunctionProcessor();
+    assertThat( processor.resolve( null, null ), nullValue() );
+    assertThat( processor.resolve( null, Arrays.asList( "test-input" ) ), contains( "test-input" ) );
+    Subject subject = new Subject();
+    subject.getPrincipals().add( new PrimaryPrincipal( "test-username" ) );
+    subject.setReadOnly();
+    Subject.doAs( subject, new PrivilegedExceptionAction<Object>() {
+      @Override
+      public Object run() throws Exception {
+        assertThat( processor.resolve( null, null ), contains( "test-username" ) );
+        assertThat( processor.resolve( null, Arrays.asList( "test-ignored" ) ), contains( "test-username" ) );
+        return null;
+      }
+    } );
+  }
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof UsernameFunctionProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find UsernameFunctionProcessor via service loader." );
+  }
+
+  @Test
+  public void testRequestUrlRewriteOfUsernameViaRewriteRule() throws Exception {
+    Map<String,String> initParams = new HashMap<>();
+    initParams.put( "request.url", "test-rule-username" );
+    setUp( "test-user", initParams );
+
+    String input = "<root/>";
+    String expect = "<root/>";
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "PUT" )
+        .requestUrl( "test-output-scheme://test-input-host:777/test-output-path/test-input-path" )
+        .queryParam( "user.name", "test-user" )
+        .queryParam( "test-query-input-name", "test-query-input-value" )
+        .queryParam( "test-query-output-name", "test-query-output-value" )
+        .contentType( "text/xml" )
+        .content( expect, Charset.forName( "UTF-8" ) );
+    interaction.respond().status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "PUT" );
+    request.setURI( "/test-input-path?test-query-input-name=test-query-input-value" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "test-input-host:777" );
+    request.setHeader( "Content-Type", "text/xml; charset=UTF-8" );
+    request.setContent( input );
+
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), Is.is( 200 ) );
+  }
+
+  private static class SetupFilter implements Filter {
+    private Subject subject;
+
+    public SetupFilter( String userName ) {
+      subject = new Subject();
+      subject.getPrincipals().add( new BasicUserPrincipal( userName ) );
+    }
+
+    @Override
+    public void init( FilterConfig filterConfig ) throws ServletException {
+    }
+
+    @Override
+    public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException {
+      HttpServletRequest httpRequest = ((HttpServletRequest)request);
+      StringBuffer sourceUrl = httpRequest.getRequestURL();
+      String queryString = httpRequest.getQueryString();
+      if( queryString != null ) {
+        sourceUrl.append( "?" );
+        sourceUrl.append( queryString );
+      }
+      try {
+        request.setAttribute(
+            AbstractGatewayFilter.SOURCE_REQUEST_URL_ATTRIBUTE_NAME,
+            Parser.parseLiteral( sourceUrl.toString() ) );
+      } catch( URISyntaxException e ) {
+        throw new ServletException( e );
+      }
+      try {
+        Subject.doAs( subject, new PrivilegedExceptionAction<Void>() {
+          @Override
+          public Void run() throws Exception {
+              chain.doFilter( request, response );
+              return null;
+          }
+        } );
+      } catch( PrivilegedActionException e ) {
+        throw new ServletException( e );
+      }
+    }
+
+    @Override
+    public void destroy() {
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/test/resources/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/test/resources/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml b/gateway-provider-identity-assertion-common/src/test/resources/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml
deleted file mode 100644
index cf28b92..0000000
--- a/gateway-provider-identity-assertion-common/src/test/resources/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml
+++ /dev/null
@@ -1,24 +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.
--->
-<rules>
-
-    <rule name="test-rule-username">
-        <match pattern="*://{host}:{port}/{path=**}?{**}"/>
-        <rewrite template="test-output-scheme://{host}:{port}/test-output-path/{path=**}?user.name={$username}?{**}?test-query-output-name=test-query-output-value"/>
-    </rule>
-
-</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/test/resources/org/apache/knox/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/test/resources/org/apache/knox/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml b/gateway-provider-identity-assertion-common/src/test/resources/org/apache/knox/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml
new file mode 100644
index 0000000..cf28b92
--- /dev/null
+++ b/gateway-provider-identity-assertion-common/src/test/resources/org/apache/knox/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml
@@ -0,0 +1,24 @@
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one or more
+  contributor license agreements.  See the NOTICE file distributed with
+  this work for additional information regarding copyright ownership.
+  The ASF licenses this file to You under the Apache License, Version 2.0
+  (the "License"); you may not use this file except in compliance with
+  the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+-->
+<rules>
+
+    <rule name="test-rule-username">
+        <match pattern="*://{host}:{port}/{path=**}?{**}"/>
+        <rewrite template="test-output-scheme://{host}:{port}/test-output-path/{path=**}?user.name={$username}?{**}?test-query-output-name=test-query-output-value"/>
+    </rule>
+
+</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-concat/src/main/java/org/apache/hadoop/gateway/ConcatIdentityAsserterMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-concat/src/main/java/org/apache/hadoop/gateway/ConcatIdentityAsserterMessages.java b/gateway-provider-identity-assertion-concat/src/main/java/org/apache/hadoop/gateway/ConcatIdentityAsserterMessages.java
deleted file mode 100644
index 548f3cc..0000000
--- a/gateway-provider-identity-assertion-concat/src/main/java/org/apache/hadoop/gateway/ConcatIdentityAsserterMessages.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-import org.apache.hadoop.gateway.i18n.messages.StackTrace;
-
-@Messages(logger="org.apache.hadoop.gateway")
-public interface ConcatIdentityAsserterMessages {
-
-  @Message( level = MessageLevel.WARN, text = "Skipping unencodable parameter {0}={1}, {2}: {3}" )
-  void skippingUnencodableParameter( String name, String value, String encoding, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-concat/src/main/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-concat/src/main/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributor.java b/gateway-provider-identity-assertion-concat/src/main/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributor.java
deleted file mode 100644
index 5eb2ca1..0000000
--- a/gateway-provider-identity-assertion-concat/src/main/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributor.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.hadoop.gateway.identityasserter.concat.filter;
-
-import org.apache.hadoop.gateway.identityasserter.common.filter.AbstractIdentityAsserterDeploymentContributor;
-
-public class ConcatIdentityAsserterDeploymentContributor extends AbstractIdentityAsserterDeploymentContributor {
-
-  @Override
-  public String getName() {
-    return "Concat";
-  }
-
-  protected String getFilterClassname() {
-    return ConcatIdentityAssertionFilter.class.getName();
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-concat/src/main/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-concat/src/main/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilter.java b/gateway-provider-identity-assertion-concat/src/main/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilter.java
deleted file mode 100644
index aea98e6..0000000
--- a/gateway-provider-identity-assertion-concat/src/main/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilter.java
+++ /dev/null
@@ -1,61 +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.hadoop.gateway.identityasserter.concat.filter;
-
-import javax.security.auth.Subject;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import org.apache.hadoop.gateway.identityasserter.common.filter.CommonIdentityAssertionFilter;
-
-public class ConcatIdentityAssertionFilter extends CommonIdentityAssertionFilter {
-  private String prefix = null;
-  private String suffix = null;
-  
-  /* (non-Javadoc)
-   * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
-   */
-  @Override
-  public void init(FilterConfig filterConfig) throws ServletException {
-    super.init(filterConfig);
-
-    prefix = filterConfig.getInitParameter("concat.prefix");
-    suffix = filterConfig.getInitParameter("concat.suffix");
-    if (prefix == null) {
-      prefix = "";
-    }
-    if (suffix == null) {
-      suffix = "";
-    }
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.identityasserter.common.filter.AbstractIdentityAssertionFilter#mapGroupPrincipals(java.lang.String, javax.security.auth.Subject)
-   */
-  @Override
-  public String[] mapGroupPrincipals(String mappedPrincipalName, Subject subject) {
-    return null;
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.identityasserter.common.filter.AbstractIdentityAssertionFilter#mapUserPrincipal(java.lang.String)
-   */
-  @Override
-  public String mapUserPrincipal(String principalName) {
-    return prefix + principalName + suffix;
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/ConcatIdentityAsserterMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/ConcatIdentityAsserterMessages.java b/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/ConcatIdentityAsserterMessages.java
new file mode 100644
index 0000000..a1d9db1
--- /dev/null
+++ b/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/ConcatIdentityAsserterMessages.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway;
+
+import org.apache.knox.gateway.i18n.messages.Message;
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.Messages;
+import org.apache.knox.gateway.i18n.messages.StackTrace;
+
+@Messages(logger="org.apache.hadoop.gateway")
+public interface ConcatIdentityAsserterMessages {
+
+  @Message( level = MessageLevel.WARN, text = "Skipping unencodable parameter {0}={1}, {2}: {3}" )
+  void skippingUnencodableParameter( String name, String value, String encoding, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributor.java b/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributor.java
new file mode 100644
index 0000000..726ac6e
--- /dev/null
+++ b/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributor.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.knox.gateway.identityasserter.concat.filter;
+
+import org.apache.knox.gateway.identityasserter.common.filter.AbstractIdentityAsserterDeploymentContributor;
+
+public class ConcatIdentityAsserterDeploymentContributor extends AbstractIdentityAsserterDeploymentContributor {
+
+  @Override
+  public String getName() {
+    return "Concat";
+  }
+
+  protected String getFilterClassname() {
+    return ConcatIdentityAssertionFilter.class.getName();
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilter.java b/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilter.java
new file mode 100644
index 0000000..9665d78
--- /dev/null
+++ b/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilter.java
@@ -0,0 +1,61 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.identityasserter.concat.filter;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import org.apache.knox.gateway.identityasserter.common.filter.CommonIdentityAssertionFilter;
+
+public class ConcatIdentityAssertionFilter extends CommonIdentityAssertionFilter {
+  private String prefix = null;
+  private String suffix = null;
+  
+  /* (non-Javadoc)
+   * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
+   */
+  @Override
+  public void init(FilterConfig filterConfig) throws ServletException {
+    super.init(filterConfig);
+
+    prefix = filterConfig.getInitParameter("concat.prefix");
+    suffix = filterConfig.getInitParameter("concat.suffix");
+    if (prefix == null) {
+      prefix = "";
+    }
+    if (suffix == null) {
+      suffix = "";
+    }
+  }
+
+  /* (non-Javadoc)
+   * @see AbstractIdentityAssertionFilter#mapGroupPrincipals(java.lang.String, javax.security.auth.Subject)
+   */
+  @Override
+  public String[] mapGroupPrincipals(String mappedPrincipalName, Subject subject) {
+    return null;
+  }
+
+  /* (non-Javadoc)
+   * @see AbstractIdentityAssertionFilter#mapUserPrincipal(java.lang.String)
+   */
+  @Override
+  public String mapUserPrincipal(String principalName) {
+    return prefix + principalName + suffix;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-concat/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-concat/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-identity-assertion-concat/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index bbfd4ae..0000000
--- a/gateway-provider-identity-assertion-concat/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.identityasserter.concat.filter.ConcatIdentityAsserterDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-concat/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-concat/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-identity-assertion-concat/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..b7255bc
--- /dev/null
+++ b/gateway-provider-identity-assertion-concat/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.identityasserter.concat.filter.ConcatIdentityAsserterDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-concat/src/test/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-concat/src/test/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributorTest.java b/gateway-provider-identity-assertion-concat/src/test/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributorTest.java
deleted file mode 100644
index b046ef6..0000000
--- a/gateway-provider-identity-assertion-concat/src/test/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributorTest.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.hadoop.gateway.identityasserter.concat.filter;
-
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor;
-import org.apache.hadoop.gateway.identityasserter.concat.filter.ConcatIdentityAsserterDeploymentContributor;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class ConcatIdentityAsserterDeploymentContributorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader<ProviderDeploymentContributor> loader = ServiceLoader.load( ProviderDeploymentContributor.class );
-    Iterator<ProviderDeploymentContributor> iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ConcatIdentityAsserterDeploymentContributor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ConcatIdentityAsserterDeploymentContributor.class.getName() + " via service loader." );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-concat/src/test/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-concat/src/test/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilterTest.java b/gateway-provider-identity-assertion-concat/src/test/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilterTest.java
deleted file mode 100644
index 2531779..0000000
--- a/gateway-provider-identity-assertion-concat/src/test/java/org/apache/hadoop/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilterTest.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.hadoop.gateway.identityasserter.concat.filter;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-import java.security.Principal;
-
-import javax.security.auth.Subject;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-
-import org.apache.hadoop.gateway.security.GroupPrincipal;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-/**
- *
- */
-public class ConcatIdentityAssertionFilterTest {
-
-  @Test
-  public void testPrefixAndSuffix() throws Exception {
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    ConcatIdentityAssertionFilter filter = new ConcatIdentityAssertionFilter();
-    Subject subject = new Subject();
-    
-    subject.getPrincipals().add(new PrimaryPrincipal("larry"));
-    subject.getPrincipals().add(new GroupPrincipal("users"));
-    subject.getPrincipals().add(new GroupPrincipal("admin"));
-    
-    filter.init(config);
-    String username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    String[] groups = filter.mapGroupPrincipals(username, subject);
-    assertEquals(username, "larry");
-    assertNull(groups); // means for the caller to use the existing subject groups
-    
-    config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.expect(config.getInitParameter("concat.prefix") ).andReturn( "sir-" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-    filter.init(config);
-    username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    assertEquals(username, "sir-larry");
-
-    config = EasyMock.createNiceMock( FilterConfig.class );
-    context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.expect(config.getInitParameter("concat.suffix") ).andReturn( "-tenant-1" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-    filter.init(config);
-    username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    assertEquals(username, "larry-tenant-1");
-
-    config = EasyMock.createNiceMock( FilterConfig.class );
-    context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.expect(config.getInitParameter("concat.prefix") ).andReturn( "sir-" ).anyTimes();
-    EasyMock.expect(config.getInitParameter("concat.suffix") ).andReturn( "-tenant-1" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-    filter.init(config);
-    username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    assertEquals(username, "sir-larry-tenant-1");
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-concat/src/test/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-concat/src/test/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributorTest.java b/gateway-provider-identity-assertion-concat/src/test/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributorTest.java
new file mode 100644
index 0000000..f1bae77
--- /dev/null
+++ b/gateway-provider-identity-assertion-concat/src/test/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAsserterDeploymentContributorTest.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.knox.gateway.identityasserter.concat.filter;
+
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributor;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class ConcatIdentityAsserterDeploymentContributorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader<ProviderDeploymentContributor> loader = ServiceLoader.load( ProviderDeploymentContributor.class );
+    Iterator<ProviderDeploymentContributor> iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ConcatIdentityAsserterDeploymentContributor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ConcatIdentityAsserterDeploymentContributor.class.getName() + " via service loader." );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-concat/src/test/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-concat/src/test/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilterTest.java b/gateway-provider-identity-assertion-concat/src/test/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilterTest.java
new file mode 100644
index 0000000..ec0a1e4
--- /dev/null
+++ b/gateway-provider-identity-assertion-concat/src/test/java/org/apache/knox/gateway/identityasserter/concat/filter/ConcatIdentityAssertionFilterTest.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.knox.gateway.identityasserter.concat.filter;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+import java.security.Principal;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+
+import org.apache.knox.gateway.security.GroupPrincipal;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+/**
+ *
+ */
+public class ConcatIdentityAssertionFilterTest {
+
+  @Test
+  public void testPrefixAndSuffix() throws Exception {
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    ConcatIdentityAssertionFilter filter = new ConcatIdentityAssertionFilter();
+    Subject subject = new Subject();
+    
+    subject.getPrincipals().add(new PrimaryPrincipal("larry"));
+    subject.getPrincipals().add(new GroupPrincipal("users"));
+    subject.getPrincipals().add(new GroupPrincipal("admin"));
+    
+    filter.init(config);
+    String username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    String[] groups = filter.mapGroupPrincipals(username, subject);
+    assertEquals(username, "larry");
+    assertNull(groups); // means for the caller to use the existing subject groups
+    
+    config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.expect(config.getInitParameter("concat.prefix") ).andReturn( "sir-" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+    filter.init(config);
+    username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    assertEquals(username, "sir-larry");
+
+    config = EasyMock.createNiceMock( FilterConfig.class );
+    context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.expect(config.getInitParameter("concat.suffix") ).andReturn( "-tenant-1" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+    filter.init(config);
+    username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    assertEquals(username, "larry-tenant-1");
+
+    config = EasyMock.createNiceMock( FilterConfig.class );
+    context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.expect(config.getInitParameter("concat.prefix") ).andReturn( "sir-" ).anyTimes();
+    EasyMock.expect(config.getInitParameter("concat.suffix") ).andReturn( "-tenant-1" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+    filter.init(config);
+    username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    assertEquals(username, "sir-larry-tenant-1");
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributor.java b/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributor.java
deleted file mode 100644
index e20f17a..0000000
--- a/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributor.java
+++ /dev/null
@@ -1,64 +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.hadoop.gateway.identityasserter.hadoop.groups.filter;
-
-import org.apache.hadoop.gateway.identityasserter.common.filter.AbstractIdentityAsserterDeploymentContributor;
-
-/**
- * A provider deployment contributor for looking up authenticated user groups as
- * seen by Hadoop implementation.
- * 
- * @since 0.11.0
- */
-
-public class HadoopGroupProviderDeploymentContributor
-    extends AbstractIdentityAsserterDeploymentContributor {
-
-  /**
-   * Name of our <b>identity-assertion</b> provider.
-   */
-  public static final String HADOOP_GROUP_PROVIDER = "HadoopGroupProvider";
-
-  /* create an instance */
-  public HadoopGroupProviderDeploymentContributor() {
-    super();
-  }
-
-  /*
-   * (non-Javadoc)
-   * 
-   * @see
-   * org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor#getName()
-   */
-  @Override
-  public String getName() {
-    return HADOOP_GROUP_PROVIDER;
-  }
-
-  /*
-   * (non-Javadoc)
-   * 
-   * @see org.apache.hadoop.gateway.identityasserter.common.filter.
-   * AbstractIdentityAsserterDeploymentContributor#getFilterClassname()
-   */
-  @Override
-  protected String getFilterClassname() {
-    return HadoopGroupProviderFilter.class.getName();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilter.java b/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilter.java
deleted file mode 100644
index 31ab827..0000000
--- a/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilter.java
+++ /dev/null
@@ -1,121 +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.hadoop.gateway.identityasserter.hadoop.groups.filter;
-
-import java.io.IOException;
-import java.util.Enumeration;
-import java.util.List;
-
-import javax.security.auth.Subject;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.identityasserter.common.filter.CommonIdentityAssertionFilter;
-import org.apache.hadoop.security.GroupMappingServiceProvider;
-import org.apache.hadoop.security.Groups;
-
-/**
- * A filter that integrates the Hadoop {@link GroupMappingServiceProvider} for
- * looking up group membership of the authenticated (asserted) identity.
- * 
- * @since 0.11.0
- */
-public class HadoopGroupProviderFilter extends CommonIdentityAssertionFilter {
-
-  /**
-   * Logging
-   */
-  public static HadoopGroupProviderMessages LOG = MessagesFactory
-      .get(HadoopGroupProviderMessages.class);
-
-  /**
-   * Configuration object needed by for hadoop classes
-   */
-  private Configuration hadoopConfig;
-
-  /**
-   * Hadoop Groups implementation.
-   */
-  private Groups hadoopGroups;
-
-  /* create an instance */
-  public HadoopGroupProviderFilter() {
-    super();
-  }
-
-  @Override
-  public void init(final FilterConfig filterConfig) throws ServletException {
-    super.init(filterConfig);
-
-    try {
-      hadoopConfig = new Configuration(false);
-
-      if (filterConfig.getInitParameterNames() != null) {
-
-        for (final Enumeration<String> keys = filterConfig
-            .getInitParameterNames(); keys.hasMoreElements();) {
-
-          final String key = keys.nextElement();
-          hadoopConfig.set(key, filterConfig.getInitParameter(key));
-
-        }
-
-      }
-      hadoopGroups = new Groups(hadoopConfig);
-
-    } catch (final Exception e) {
-      throw new ServletException(e);
-    }
-
-  }
-
-  /**
-   * Query the Hadoop implementation of {@link Groups} to retrieve groups for
-   * provided user.
-   */
-  public String[] mapGroupPrincipals(final String mappedPrincipalName,
-      final Subject subject) {
-    /* return the groups as seen by Hadoop */
-    String[] groups = null;
-    try {
-      final List<String> groupList = hadoopGroups
-          .getGroups(mappedPrincipalName);
-      LOG.groupsFound(mappedPrincipalName, groupList.toString());
-      groups = groupList.toArray(new String[0]);
-
-    } catch (final IOException e) {
-      if (e.toString().contains("No groups found for user")) {
-        /* no groups found move on */
-        LOG.noGroupsFound(mappedPrincipalName);
-      } else {
-        /* Log the error and return empty group */
-        LOG.errorGettingUserGroups(mappedPrincipalName, e);
-      }
-      groups = new String[0];
-    }
-    return groups;
-  }
-
-  public String mapUserPrincipal(final String principalName) {
-    /* return the passed principal */
-    return principalName;
-  }
-
-}


[43/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/IdentityAsserterHttpServletRequestWrapper.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/IdentityAsserterHttpServletRequestWrapper.java b/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/IdentityAsserterHttpServletRequestWrapper.java
deleted file mode 100644
index 961fef7..0000000
--- a/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/filter/IdentityAsserterHttpServletRequestWrapper.java
+++ /dev/null
@@ -1,294 +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.hadoop.gateway.identityasserter.common.filter;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.hadoop.gateway.SpiGatewayMessages;
-import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.apache.hadoop.gateway.servlet.SynchronousServletInputStreamAdapter;
-import org.apache.hadoop.gateway.util.HttpUtils;
-
-import javax.servlet.ServletInputStream;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletRequestWrapper;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-import java.nio.charset.Charset;
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-
-public class IdentityAsserterHttpServletRequestWrapper extends HttpServletRequestWrapper {
-
-private static SpiGatewayMessages log = MessagesFactory.get( SpiGatewayMessages.class );
-
-  private static final String PRINCIPAL_PARAM = "user.name";
-  private static final String DOAS_PRINCIPAL_PARAM = "doAs";
-  
-  String username = null;
-
-  public IdentityAsserterHttpServletRequestWrapper( HttpServletRequest request, String principal ) {
-    super(request);
-    username = principal;
-  }
-
-  @Override
-  public Principal getUserPrincipal() {
-    return new PrimaryPrincipal(username);
-  }
-
-  @Override
-  public String getParameter(String name) {
-    if (name.equals(PRINCIPAL_PARAM)) {
-      return username;
-    }
-    return super.getParameter(name);
-  }
-  
-  @SuppressWarnings("rawtypes")
-  @Override
-  public Map getParameterMap() {
-    Map map = null;
-    try {
-      map = getParams();
-    } catch (UnsupportedEncodingException e) {
-      log.unableToGetParamsFromQueryString(e);
-    }
-    return map;
-  }
-
-  @SuppressWarnings({ "unchecked", "rawtypes" })
-  @Override
-  public Enumeration getParameterNames() {
-    Enumeration<String> e = null;
-    Map<String, List<String>> params;
-    try {
-      params = getParams();
-      if (params == null) {
-        params = new HashMap<>();
-      }
-      e = Collections.enumeration((Collection<String>) params.keySet());
-    } catch (UnsupportedEncodingException e1) {
-      log.unableToGetParamsFromQueryString(e1);
-    }
-
-    return e;
-  }
-
-  @Override
-  public String[] getParameterValues(String name) {
-    String[] p = null;
-    Map<String, List<String>> params;
-    try {
-      params = getParams();
-      if (params == null) {
-        params = new HashMap<>();
-      }
-      p = (String[]) params.get(name).toArray();
-    } catch (UnsupportedEncodingException e) {
-      log.unableToGetParamsFromQueryString(e);
-    }
-
-    return p;
-  }
-
-  private Map<String, List<String>> getParams( String qString )
-      throws UnsupportedEncodingException {
-    Map<String, List<String>> params = null;
-    if (getMethod().equals("GET")) {
-      if (qString != null && qString.length() > 0) {
-        params = HttpUtils.splitQuery( qString );
-      }
-      else {
-        params = new HashMap<>();
-      }
-    }
-    else {
-      if (qString == null || qString.length() == 0) {
-        return null;
-      }
-      else {
-        params = HttpUtils.splitQuery( qString );
-      }
-    }  
-    return params;
-  }
-
-  private Map<String, List<String>> getParams()
-      throws UnsupportedEncodingException {
-    return getParams( super.getQueryString() );
-  }
-
-  @Override
-  public String getQueryString() {
-    String q = null;
-    Map<String, List<String>> params;
-    try {
-      params = getParams();
-      if (params == null) {
-        params = new HashMap<>();
-      }
-      ArrayList<String> al = new ArrayList<String>();
-      al.add(username);
-
-      List<String> principalParamNames = getImpersonationParamNames();
-      params = scrubOfExistingPrincipalParams(params, principalParamNames);
-
-      if ("true".equals(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) {
-        params.put(DOAS_PRINCIPAL_PARAM, al);
-      } else {
-        params.put(PRINCIPAL_PARAM, al);
-      }
-
-      String encoding = getCharacterEncoding();
-      if (encoding == null) {
-        encoding = Charset.defaultCharset().name();
-      }
-      q = urlEncode(params, encoding);
-    } catch (UnsupportedEncodingException e) {
-      log.unableToGetParamsFromQueryString(e);
-    }
-
-    return q;
-  }
-
-  private List<String> getImpersonationParamNames() {
-    // TODO: let's have service definitions register their impersonation
-    // params in a future release and get this list from a central registry.
-    // This will provide better coverage of protection by removing any
-    // prepopulated impersonation params.
-    ArrayList<String> principalParamNames = new ArrayList<String>();
-    principalParamNames.add(DOAS_PRINCIPAL_PARAM);
-    principalParamNames.add(PRINCIPAL_PARAM);
-    return principalParamNames;
-  }
-
-  private Map<String, List<String>> scrubOfExistingPrincipalParams(
-      Map<String, List<String>> params, List<String> principalParamNames) {
-    HashSet<String> remove = new HashSet<>();
-    for (String paramKey : params.keySet()) {
-      for (String p : principalParamNames) {
-        if (p.equalsIgnoreCase(paramKey)) {
-          remove.add(paramKey);
-          log.possibleIdentitySpoofingAttempt(paramKey);
-        }
-      }
-    }
-    params.keySet().removeAll(remove);
-    return params;
-  }
-
-  @Override
-  public int getContentLength() {
-    int len;
-    String contentType = getContentType();
-    // If the content type is a form we might rewrite the body so default it to -1.
-    if( contentType != null && contentType.startsWith( "application/x-www-form-urlencoded" ) ) {
-      len = -1;
-    } else {
-      len = super.getContentLength();
-    }
-    return len;
-  }
-
-  @Override
-  public ServletInputStream getInputStream() throws java.io.IOException {
-    String contentType = getContentType();
-    if( contentType != null && contentType.startsWith( "application/x-www-form-urlencoded" ) ) {
-      String encoding = getCharacterEncoding();
-      if( encoding == null ) {
-        encoding = Charset.defaultCharset().name();
-      }
-      String body = IOUtils.toString( super.getInputStream(), encoding );
-      Map<String, List<String>> params = getParams( body );
-      if (params == null) {
-        params = new HashMap<>();
-      }
-      body = urlEncode( params, encoding );
-      // ASCII is OK here because the urlEncode about should have already escaped
-      return new ServletInputStreamWrapper( new ByteArrayInputStream( body.getBytes( "US-ASCII" ) ) );
-    } else {
-      return super.getInputStream();
-    }
-  }
-
-  static String urlEncode( String string, String encoding ) {
-    try {
-      return URLEncoder.encode( string, encoding );
-    } catch (UnsupportedEncodingException e) {
-      throw new UnsupportedOperationException(e);
-    }
-  }
-
-  public static String urlEncode( Map<String, List<String>> map, String encoding ) {
-    StringBuilder sb = new StringBuilder();
-    for( Map.Entry<String,List<String>> entry : map.entrySet() ) {
-      String name = entry.getKey();
-      if( name != null && name.length() > 0 ) {
-        List<String> values = entry.getValue();
-        if( values == null || values.size() == 0 ) {
-          sb.append( entry.getKey() );
-        } else {
-          for( int i = 0; i < values.size(); i++ ) {
-            String value = values.get(i);
-              if( sb.length() > 0 ) {
-                sb.append( "&" );
-              }
-              try {
-                sb.append( urlEncode( name, encoding ) );
-                if( value != null ) {
-                  sb.append("=");
-                  sb.append(urlEncode(value, encoding));
-                }
-              } catch( IllegalArgumentException e ) {
-                log.skippingUnencodableParameter( name, value, encoding, e );
-              }
-          }
-        }
-      }
-    }
-    return sb.toString();
-  }
-
-  private static class ServletInputStreamWrapper extends SynchronousServletInputStreamAdapter {
-
-    private InputStream stream;
-
-    private ServletInputStreamWrapper( InputStream stream ) {
-      this.stream = stream;
-    }
-
-    @Override
-    public int read() throws IOException {
-      return stream.read();
-    }
-
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/function/UsernameFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/function/UsernameFunctionDescriptor.java b/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/function/UsernameFunctionDescriptor.java
deleted file mode 100644
index f997de8..0000000
--- a/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/function/UsernameFunctionDescriptor.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.identityasserter.common.function;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-public class UsernameFunctionDescriptor implements UrlRewriteFunctionDescriptor<UsernameFunctionDescriptor> {
-
-  public static final String FUNCTION_NAME = "username";
-
-  @Override
-  public String name() {
-    return FUNCTION_NAME;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/function/UsernameFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/function/UsernameFunctionProcessor.java b/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/function/UsernameFunctionProcessor.java
deleted file mode 100644
index cc5d39d..0000000
--- a/gateway-provider-identity-assertion-common/src/main/java/org/apache/hadoop/gateway/identityasserter/common/function/UsernameFunctionProcessor.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.hadoop.gateway.identityasserter.common.function;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.apache.hadoop.gateway.filter.security.AbstractIdentityAssertionBase;
-import org.apache.hadoop.gateway.i18n.GatewaySpiMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.security.SubjectUtils;
-
-import javax.security.auth.Subject;
-import java.security.AccessController;
-import java.util.ArrayList;
-import java.util.List;
-
-public class UsernameFunctionProcessor
-    implements UrlRewriteFunctionProcessor<UsernameFunctionDescriptor> {
-
-  private static final GatewaySpiMessages LOG = MessagesFactory.get( GatewaySpiMessages.class );
-//  private PrincipalMapper mapper = null;
-
-  @Override
-  public String name() {
-    return UsernameFunctionDescriptor.FUNCTION_NAME;
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, UsernameFunctionDescriptor descriptor ) throws Exception {
-//    if( environment != null ) {
-//      GatewayServices services = environment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE );
-//      if( services != null ) {
-//        mapper = (PrincipalMapper)services.getService( "PrincipalMapperService" /*GatewayServices.PRINCIPAL_MAPPER_SERVICE*/ );
-//      }
-//    }
-  }
-
-  @Override
-  public void destroy() throws Exception {
-  }
-
-  @Override
-  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
-    List<String> results = null;
-    Subject subject = SubjectUtils.getCurrentSubject( );
-    if( subject != null ) {
-      results = new ArrayList<String>( 1 );
-      String username = SubjectUtils.getEffectivePrincipalName(subject);
-      results.add( username );
-    } else if( parameters != null && parameters.size() > 0 ) {
-      results = new ArrayList<String>( 1 );
-      results.add( parameters.get( 0 ) );
-    }
-    return results;
-  }
-
-}
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java
new file mode 100644
index 0000000..e614c25
--- /dev/null
+++ b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway;
+
+import org.apache.knox.gateway.i18n.messages.Message;
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.Messages;
+import org.apache.knox.gateway.i18n.messages.StackTrace;
+
+@Messages(logger="org.apache.hadoop.gateway")
+public interface IdentityAsserterMessages {
+
+  @Message( level = MessageLevel.WARN, text = "Skipping unencodable parameter {0}={1}, {2}: {3}" )
+  void skippingUnencodableParameter( String name, String value, String encoding, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/AbstractIdentityAsserterDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/AbstractIdentityAsserterDeploymentContributor.java b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/AbstractIdentityAsserterDeploymentContributor.java
new file mode 100644
index 0000000..8f2adb8
--- /dev/null
+++ b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/AbstractIdentityAsserterDeploymentContributor.java
@@ -0,0 +1,61 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.identityasserter.common.filter;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public abstract class AbstractIdentityAsserterDeploymentContributor extends
+    ProviderDeploymentContributorBase {
+
+  @Override
+  public String getRole() {
+    return "identity-assertion";
+  }
+
+  @Override
+  public void contributeFilter( DeploymentContext context, Provider provider, Service service,
+      ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
+    params = buildFilterInitParms(provider, resource, params);
+    resource.addFilter().name(getName()).role(getRole()).impl(getFilterClassname()).params(params);
+  }
+
+  public List<FilterParamDescriptor> buildFilterInitParms(Provider provider,
+      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
+    // blindly add all the provider params as filter init params
+    if (params == null) {
+      params = new ArrayList<FilterParamDescriptor>();
+    }
+    Map<String, String> providerParams = provider.getParams();
+    for(Entry<String, String> entry : providerParams.entrySet()) {
+      params.add( resource.createFilterParam().name(entry.getKey().toLowerCase()).value(entry.getValue()));
+    }
+    return params;
+  }
+
+  protected abstract String getFilterClassname();
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/AbstractIdentityAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/AbstractIdentityAssertionFilter.java b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/AbstractIdentityAssertionFilter.java
new file mode 100644
index 0000000..a007ab6
--- /dev/null
+++ b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/AbstractIdentityAssertionFilter.java
@@ -0,0 +1,198 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.identityasserter.common.filter;
+
+import java.io.IOException;
+import java.security.AccessController;
+import java.security.Principal;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.Arrays;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.servlet.Filter;
+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.HttpServletRequestWrapper;
+
+import org.apache.knox.gateway.audit.api.Action;
+import org.apache.knox.gateway.audit.api.ActionOutcome;
+import org.apache.knox.gateway.audit.api.AuditService;
+import org.apache.knox.gateway.audit.api.AuditServiceFactory;
+import org.apache.knox.gateway.audit.api.Auditor;
+import org.apache.knox.gateway.audit.api.ResourceType;
+import org.apache.knox.gateway.audit.log4j.audit.AuditConstants;
+import org.apache.knox.gateway.filter.security.AbstractIdentityAssertionBase;
+import org.apache.knox.gateway.i18n.GatewaySpiResources;
+import org.apache.knox.gateway.i18n.resources.ResourcesFactory;
+import org.apache.knox.gateway.security.GroupPrincipal;
+import org.apache.knox.gateway.security.ImpersonatedPrincipal;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+
+/**
+ *
+ */
+public abstract class AbstractIdentityAssertionFilter extends
+  AbstractIdentityAssertionBase implements Filter {
+
+  private static final GatewaySpiResources RES = ResourcesFactory.get( GatewaySpiResources.class );
+  private static AuditService auditService = AuditServiceFactory.getAuditService();
+  private static Auditor auditor = auditService.getAuditor(
+        AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
+        AuditConstants.KNOX_COMPONENT_NAME );
+
+  /**
+   * 
+   */
+  public AbstractIdentityAssertionFilter() {
+    super();
+  }
+
+  /**
+   * This method returns a Stringp[] of new group principal names to use
+   * based on implementation specific mapping or lookup mechanisms.
+   * Returning null means that whatever set of GroupPrincipals is in the
+   * provided Subject is sufficient to use and no additional mapping is required.
+   * @param mappedPrincipalName username for the authenticated identity - post mapUserPrincipal mapping.
+   * @param subject the existing Subject from the authentication event which may or may not contain GroupPrincipals.
+   * @return String[] of new principal names to use as GroupPrincipals or null.
+   */
+  public abstract String[] mapGroupPrincipals(String mappedPrincipalName, Subject subject);
+
+  /**
+   * This method is used to map the username of the authenticated identity to some other
+   * principal name based on an implementation specific mechanism. It will either return
+   * a new principal name or the provided principal name if there is no mapping required.
+   * @param principalName
+   * @return new username or the provided principalName
+   */
+  public abstract String mapUserPrincipal(String principalName);
+
+  /**
+   * @param wrapper
+   * @param response
+   * @param chain
+   * @param mappedPrincipalName
+   * @param groups
+   */
+  protected void continueChainAsPrincipal(HttpServletRequestWrapper request, ServletResponse response,
+      FilterChain chain, String mappedPrincipalName, String[] groups) throws IOException,
+      ServletException {
+        Subject subject = null;
+        Principal impersonationPrincipal = null;
+        Principal primaryPrincipal = null;
+        
+        // get the current subject and determine whether we need another doAs with 
+        // an impersonatedPrincipal and/or mapped group principals
+        boolean impersonationNeeded = false;
+        boolean groupsMapped = false;
+        
+        // look up the current Java Subject and assosciated group principals
+        Subject currentSubject = Subject.getSubject(AccessController.getContext());
+        Set<?> currentGroups = currentSubject.getPrincipals(GroupPrincipal.class);
+        
+        primaryPrincipal = (PrimaryPrincipal) currentSubject.getPrincipals(PrimaryPrincipal.class).toArray()[0];
+        if (primaryPrincipal != null) {
+          if (!primaryPrincipal.getName().equals(mappedPrincipalName)) {
+            impersonationNeeded = true;
+            auditService.getContext().setProxyUsername( mappedPrincipalName );
+            auditor.audit( Action.IDENTITY_MAPPING, primaryPrincipal.getName(), 
+                ResourceType.PRINCIPAL, ActionOutcome.SUCCESS, RES.effectiveUser(mappedPrincipalName) );
+          }
+        }
+        else {
+          // something is amiss - authentication/federation providers should have run
+          // before identity assertion and should have ensured that the appropriate
+          // principals were added to the current subject
+          // TODO: log as appropriate
+          primaryPrincipal = new PrimaryPrincipal(((HttpServletRequest) request).getUserPrincipal().getName());
+        }
+        
+        groupsMapped = groups != null || !currentGroups.isEmpty();
+        
+        if (impersonationNeeded || groupsMapped) {
+          // gonna need a new subject and doAs
+          subject = new Subject();
+          Set<Principal> principals = subject.getPrincipals();
+          principals.add(primaryPrincipal);
+          
+          // map group principals from current Subject into newly created Subject
+          for (Object obj : currentGroups) {
+            principals.add((Principal)obj);
+          }
+          
+          if (impersonationNeeded) {
+            impersonationPrincipal = new ImpersonatedPrincipal(mappedPrincipalName);
+            subject.getPrincipals().add(impersonationPrincipal);
+          }
+          if (groupsMapped) {
+            addMappedGroupsToSubject(mappedPrincipalName, groups, subject);
+          }
+          doAs(request, response, chain, subject);
+        }
+        else {
+          doFilterInternal(request, response, chain);
+        }
+      }
+
+  private void doAs(final ServletRequest request, final ServletResponse response, final FilterChain chain, Subject subject)
+      throws IOException, ServletException {
+    try {
+      Subject.doAs(
+        subject,
+        new PrivilegedExceptionAction<Object>() {
+          public Object run() throws Exception {
+            doFilterInternal(request, response, chain);
+            return null;
+          }
+        });
+    }
+    catch (PrivilegedActionException e) {
+      Throwable t = e.getCause();
+      if (t instanceof IOException) {
+        throw (IOException) t;
+      }
+      else if (t instanceof ServletException) {
+        throw (ServletException) t;
+      }
+      else {
+        throw new ServletException(t);
+      }
+    }
+  }
+
+  private void addMappedGroupsToSubject(String mappedPrincipalName, String[] groups, Subject subject) {
+    if (groups != null) {
+      auditor.audit( Action.IDENTITY_MAPPING, mappedPrincipalName, ResourceType.PRINCIPAL, 
+          ActionOutcome.SUCCESS, RES.groupsList( Arrays.toString( groups ) ) );
+
+      for (int i = 0; i < groups.length; i++) {
+        subject.getPrincipals().add(new GroupPrincipal(groups[i]));
+      }
+    }
+  }
+
+  private void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain)
+      throws IOException, ServletException {
+    chain.doFilter(request, response);
+  }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/CommonIdentityAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/CommonIdentityAssertionFilter.java b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/CommonIdentityAssertionFilter.java
new file mode 100644
index 0000000..391aa9e
--- /dev/null
+++ b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/CommonIdentityAssertionFilter.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.knox.gateway.identityasserter.common.filter;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletRequestWrapper;
+
+import org.apache.commons.lang.ArrayUtils;
+import org.apache.knox.gateway.security.principal.PrincipalMappingException;
+import org.apache.knox.gateway.security.principal.SimplePrincipalMapper;
+
+import java.io.IOException;
+import java.security.AccessController;
+
+public class CommonIdentityAssertionFilter extends AbstractIdentityAssertionFilter {
+  private static final String GROUP_PRINCIPAL_MAPPING = "group.principal.mapping";
+  private static final String PRINCIPAL_MAPPING = "principal.mapping";
+  private SimplePrincipalMapper mapper = new SimplePrincipalMapper();
+
+  /* (non-Javadoc)
+   * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
+   */
+  @Override
+  public void init(FilterConfig filterConfig) throws ServletException {
+    String principalMapping = filterConfig.getInitParameter(PRINCIPAL_MAPPING);
+    if (principalMapping == null || principalMapping.isEmpty()) {
+      principalMapping = filterConfig.getServletContext().getInitParameter(PRINCIPAL_MAPPING);
+    }
+    String groupPrincipalMapping = filterConfig.getInitParameter(GROUP_PRINCIPAL_MAPPING);
+    if (groupPrincipalMapping == null || groupPrincipalMapping.isEmpty()) {
+      groupPrincipalMapping = filterConfig.getServletContext().getInitParameter(GROUP_PRINCIPAL_MAPPING);
+    }
+    if (principalMapping != null && !principalMapping.isEmpty() || groupPrincipalMapping != null && !groupPrincipalMapping.isEmpty()) {
+      try {
+        mapper.loadMappingTable(principalMapping, groupPrincipalMapping);
+      } catch (PrincipalMappingException e) {
+        throw new ServletException("Unable to load principal mapping table.", e);
+      }
+    }
+  }
+
+  /* (non-Javadoc)
+   * @see javax.servlet.Filter#destroy()
+   */
+  @Override
+  public void destroy() {
+  }
+
+  /**
+   * Obtain the standard javax.security.auth.Subject, retrieve the caller principal, map
+   * to the identity to be asserted as appropriate and create the provider specific
+   * assertion token. Add the assertion token to the request.
+   */
+  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
+      throws IOException, ServletException {
+    Subject subject = Subject.getSubject(AccessController.getContext());
+
+    String principalName = getPrincipalName(subject);
+
+    String mappedPrincipalName = mapUserPrincipalBase(principalName);
+    mappedPrincipalName = mapUserPrincipal(mappedPrincipalName);
+    String[] mappedGroups = mapGroupPrincipals(mappedPrincipalName, subject);
+    String[] groups = mapGroupPrincipals(mappedPrincipalName, subject);
+    groups = combineGroupMappings(mappedGroups, groups);
+
+    HttpServletRequestWrapper wrapper = wrapHttpServletRequest(
+        request, mappedPrincipalName);
+
+    continueChainAsPrincipal(wrapper, response, chain, mappedPrincipalName, groups);
+  }
+
+  /**
+   * @param mappedGroups
+   * @param groups
+   * @return
+   */
+  private String[] combineGroupMappings(String[] mappedGroups, String[] groups) {
+    if (mappedGroups != null && groups != null) {
+      return (String[])ArrayUtils.addAll(mappedGroups, groups);
+    }
+    else {
+      return groups != null ? groups : mappedGroups;
+    }
+  }
+
+  public HttpServletRequestWrapper wrapHttpServletRequest(
+      ServletRequest request, String mappedPrincipalName) {
+    // wrap the request so that the proper principal is returned
+    // from request methods
+    IdentityAsserterHttpServletRequestWrapper wrapper =
+        new IdentityAsserterHttpServletRequestWrapper(
+        (HttpServletRequest)request, 
+        mappedPrincipalName);
+    return wrapper;
+  }
+
+  protected String[] mapGroupPrincipalsBase(String mappedPrincipalName, Subject subject) {
+    return mapper.mapGroupPrincipal(mappedPrincipalName);
+  }
+
+  protected String mapUserPrincipalBase(String principalName) {
+    return mapper.mapUserPrincipal(principalName);
+  }
+
+  /* (non-Javadoc)
+   * @see AbstractIdentityAssertionFilter#mapGroupPrincipals(java.lang.String, javax.security.auth.Subject)
+   */
+  @Override
+  public String[] mapGroupPrincipals(String mappedPrincipalName, Subject subject) {
+    // NOP
+    return null;
+  }
+
+  /* (non-Javadoc)
+   * @see AbstractIdentityAssertionFilter#mapUserPrincipal(java.lang.String)
+   */
+  @Override
+  public String mapUserPrincipal(String principalName) {
+    // NOP
+    return principalName;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/IdentityAsserterHttpServletRequestWrapper.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/IdentityAsserterHttpServletRequestWrapper.java b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/IdentityAsserterHttpServletRequestWrapper.java
new file mode 100644
index 0000000..a484d16
--- /dev/null
+++ b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/IdentityAsserterHttpServletRequestWrapper.java
@@ -0,0 +1,295 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.identityasserter.common.filter;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.knox.gateway.SpiGatewayMessages;
+import org.apache.knox.gateway.config.GatewayConfig;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.apache.knox.gateway.servlet.SynchronousServletInputStreamAdapter;
+import org.apache.knox.gateway.util.HttpUtils;
+
+import javax.servlet.ServletInputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletRequestWrapper;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.nio.charset.Charset;
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+
+public class IdentityAsserterHttpServletRequestWrapper extends HttpServletRequestWrapper {
+
+private static SpiGatewayMessages log = MessagesFactory.get( SpiGatewayMessages.class );
+
+  private static final String PRINCIPAL_PARAM = "user.name";
+  private static final String DOAS_PRINCIPAL_PARAM = "doAs";
+  
+  String username = null;
+
+  public IdentityAsserterHttpServletRequestWrapper( HttpServletRequest request, String principal ) {
+    super(request);
+    username = principal;
+  }
+
+  @Override
+  public Principal getUserPrincipal() {
+    return new PrimaryPrincipal(username);
+  }
+
+  @Override
+  public String getParameter(String name) {
+    if (name.equals(PRINCIPAL_PARAM)) {
+      return username;
+    }
+    return super.getParameter(name);
+  }
+  
+  @SuppressWarnings("rawtypes")
+  @Override
+  public Map getParameterMap() {
+    Map map = null;
+    try {
+      map = getParams();
+    } catch (UnsupportedEncodingException e) {
+      log.unableToGetParamsFromQueryString(e);
+    }
+    return map;
+  }
+
+  @SuppressWarnings({ "unchecked", "rawtypes" })
+  @Override
+  public Enumeration getParameterNames() {
+    Enumeration<String> e = null;
+    Map<String, List<String>> params;
+    try {
+      params = getParams();
+      if (params == null) {
+        params = new HashMap<>();
+      }
+      e = Collections.enumeration((Collection<String>) params.keySet());
+    } catch (UnsupportedEncodingException e1) {
+      log.unableToGetParamsFromQueryString(e1);
+    }
+
+    return e;
+  }
+
+  @Override
+  public String[] getParameterValues(String name) {
+    String[] p = null;
+    Map<String, List<String>> params;
+    try {
+      params = getParams();
+      if (params == null) {
+        params = new HashMap<>();
+      }
+      p = (String[]) params.get(name).toArray();
+    } catch (UnsupportedEncodingException e) {
+      log.unableToGetParamsFromQueryString(e);
+    }
+
+    return p;
+  }
+
+  private Map<String, List<String>> getParams( String qString )
+      throws UnsupportedEncodingException {
+    Map<String, List<String>> params = null;
+    if (getMethod().equals("GET")) {
+      if (qString != null && qString.length() > 0) {
+        params = HttpUtils.splitQuery( qString );
+      }
+      else {
+        params = new HashMap<>();
+      }
+    }
+    else {
+      if (qString == null || qString.length() == 0) {
+        return null;
+      }
+      else {
+        params = HttpUtils.splitQuery( qString );
+      }
+    }  
+    return params;
+  }
+
+  private Map<String, List<String>> getParams()
+      throws UnsupportedEncodingException {
+    return getParams( super.getQueryString() );
+  }
+
+  @Override
+  public String getQueryString() {
+    String q = null;
+    Map<String, List<String>> params;
+    try {
+      params = getParams();
+      if (params == null) {
+        params = new HashMap<>();
+      }
+      ArrayList<String> al = new ArrayList<String>();
+      al.add(username);
+
+      List<String> principalParamNames = getImpersonationParamNames();
+      params = scrubOfExistingPrincipalParams(params, principalParamNames);
+
+      if ("true".equals(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) {
+        params.put(DOAS_PRINCIPAL_PARAM, al);
+      } else {
+        params.put(PRINCIPAL_PARAM, al);
+      }
+
+      String encoding = getCharacterEncoding();
+      if (encoding == null) {
+        encoding = Charset.defaultCharset().name();
+      }
+      q = urlEncode(params, encoding);
+    } catch (UnsupportedEncodingException e) {
+      log.unableToGetParamsFromQueryString(e);
+    }
+
+    return q;
+  }
+
+  private List<String> getImpersonationParamNames() {
+    // TODO: let's have service definitions register their impersonation
+    // params in a future release and get this list from a central registry.
+    // This will provide better coverage of protection by removing any
+    // prepopulated impersonation params.
+    ArrayList<String> principalParamNames = new ArrayList<String>();
+    principalParamNames.add(DOAS_PRINCIPAL_PARAM);
+    principalParamNames.add(PRINCIPAL_PARAM);
+    return principalParamNames;
+  }
+
+  private Map<String, List<String>> scrubOfExistingPrincipalParams(
+      Map<String, List<String>> params, List<String> principalParamNames) {
+    HashSet<String> remove = new HashSet<>();
+    for (String paramKey : params.keySet()) {
+      for (String p : principalParamNames) {
+        if (p.equalsIgnoreCase(paramKey)) {
+          remove.add(paramKey);
+          log.possibleIdentitySpoofingAttempt(paramKey);
+        }
+      }
+    }
+    params.keySet().removeAll(remove);
+    return params;
+  }
+
+  @Override
+  public int getContentLength() {
+    int len;
+    String contentType = getContentType();
+    // If the content type is a form we might rewrite the body so default it to -1.
+    if( contentType != null && contentType.startsWith( "application/x-www-form-urlencoded" ) ) {
+      len = -1;
+    } else {
+      len = super.getContentLength();
+    }
+    return len;
+  }
+
+  @Override
+  public ServletInputStream getInputStream() throws java.io.IOException {
+    String contentType = getContentType();
+    if( contentType != null && contentType.startsWith( "application/x-www-form-urlencoded" ) ) {
+      String encoding = getCharacterEncoding();
+      if( encoding == null ) {
+        encoding = Charset.defaultCharset().name();
+      }
+      String body = IOUtils.toString( super.getInputStream(), encoding );
+      Map<String, List<String>> params = getParams( body );
+      if (params == null) {
+        params = new HashMap<>();
+      }
+      body = urlEncode( params, encoding );
+      // ASCII is OK here because the urlEncode about should have already escaped
+      return new ServletInputStreamWrapper( new ByteArrayInputStream( body.getBytes( "US-ASCII" ) ) );
+    } else {
+      return super.getInputStream();
+    }
+  }
+
+  static String urlEncode( String string, String encoding ) {
+    try {
+      return URLEncoder.encode( string, encoding );
+    } catch (UnsupportedEncodingException e) {
+      throw new UnsupportedOperationException(e);
+    }
+  }
+
+  public static String urlEncode( Map<String, List<String>> map, String encoding ) {
+    StringBuilder sb = new StringBuilder();
+    for( Map.Entry<String,List<String>> entry : map.entrySet() ) {
+      String name = entry.getKey();
+      if( name != null && name.length() > 0 ) {
+        List<String> values = entry.getValue();
+        if( values == null || values.size() == 0 ) {
+          sb.append( entry.getKey() );
+        } else {
+          for( int i = 0; i < values.size(); i++ ) {
+            String value = values.get(i);
+              if( sb.length() > 0 ) {
+                sb.append( "&" );
+              }
+              try {
+                sb.append( urlEncode( name, encoding ) );
+                if( value != null ) {
+                  sb.append("=");
+                  sb.append(urlEncode(value, encoding));
+                }
+              } catch( IllegalArgumentException e ) {
+                log.skippingUnencodableParameter( name, value, encoding, e );
+              }
+          }
+        }
+      }
+    }
+    return sb.toString();
+  }
+
+  private static class ServletInputStreamWrapper extends
+      SynchronousServletInputStreamAdapter {
+
+    private InputStream stream;
+
+    private ServletInputStreamWrapper( InputStream stream ) {
+      this.stream = stream;
+    }
+
+    @Override
+    public int read() throws IOException {
+      return stream.read();
+    }
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/function/UsernameFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/function/UsernameFunctionDescriptor.java b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/function/UsernameFunctionDescriptor.java
new file mode 100644
index 0000000..37b0aaf
--- /dev/null
+++ b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/function/UsernameFunctionDescriptor.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.knox.gateway.identityasserter.common.function;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+public class UsernameFunctionDescriptor implements
+    UrlRewriteFunctionDescriptor<UsernameFunctionDescriptor> {
+
+  public static final String FUNCTION_NAME = "username";
+
+  @Override
+  public String name() {
+    return FUNCTION_NAME;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/function/UsernameFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/function/UsernameFunctionProcessor.java b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/function/UsernameFunctionProcessor.java
new file mode 100644
index 0000000..7d3c4d0
--- /dev/null
+++ b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/function/UsernameFunctionProcessor.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.knox.gateway.identityasserter.common.function;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.i18n.GatewaySpiMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.security.SubjectUtils;
+
+import javax.security.auth.Subject;
+import java.util.ArrayList;
+import java.util.List;
+
+public class UsernameFunctionProcessor
+    implements UrlRewriteFunctionProcessor<UsernameFunctionDescriptor> {
+
+  private static final GatewaySpiMessages LOG = MessagesFactory.get( GatewaySpiMessages.class );
+//  private PrincipalMapper mapper = null;
+
+  @Override
+  public String name() {
+    return UsernameFunctionDescriptor.FUNCTION_NAME;
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, UsernameFunctionDescriptor descriptor ) throws Exception {
+//    if( environment != null ) {
+//      GatewayServices services = environment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE );
+//      if( services != null ) {
+//        mapper = (PrincipalMapper)services.getService( "PrincipalMapperService" /*GatewayServices.PRINCIPAL_MAPPER_SERVICE*/ );
+//      }
+//    }
+  }
+
+  @Override
+  public void destroy() throws Exception {
+  }
+
+  @Override
+  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
+    List<String> results = null;
+    Subject subject = SubjectUtils.getCurrentSubject( );
+    if( subject != null ) {
+      results = new ArrayList<String>( 1 );
+      String username = SubjectUtils.getEffectivePrincipalName(subject);
+      results.add( username );
+    } else if( parameters != null && parameters.size() > 0 ) {
+      results = new ArrayList<String>( 1 );
+      results.add( parameters.get( 0 ) );
+    }
+    return results;
+  }
+
+}
+

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index 2545fb6..0000000
--- a/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,18 +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.
-##########################################################################
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor b/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
deleted file mode 100644
index 9671caf..0000000
--- a/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.identityasserter.common.function.UsernameFunctionDescriptor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor b/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
deleted file mode 100644
index 5038d11..0000000
--- a/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.identityasserter.common.function.UsernameFunctionProcessor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..2545fb6
--- /dev/null
+++ b/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,18 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor b/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
new file mode 100644
index 0000000..2f684f2
--- /dev/null
+++ b/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.identityasserter.common.function.UsernameFunctionDescriptor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor b/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
new file mode 100644
index 0000000..6cf41b0
--- /dev/null
+++ b/gateway-provider-identity-assertion-common/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.identityasserter.common.function.UsernameFunctionProcessor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/filter/CommonIdentityAssertionFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/filter/CommonIdentityAssertionFilterTest.java b/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/filter/CommonIdentityAssertionFilterTest.java
deleted file mode 100644
index 4d53dbb..0000000
--- a/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/filter/CommonIdentityAssertionFilterTest.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.hadoop.gateway.identityasserter.filter;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-
-import javax.security.auth.Subject;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.hadoop.gateway.identityasserter.common.filter.CommonIdentityAssertionFilter;
-import org.apache.hadoop.gateway.security.GroupPrincipal;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.easymock.EasyMock;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * @author larry
- *
- */
-public class CommonIdentityAssertionFilterTest {
-
-  private String username = null;
-  private String[] mappedGroups = null;
-  private Filter filter = null;
-  
-  @Before
-  public void setup() {
-    filter = new CommonIdentityAssertionFilter() {
-      @Override
-      public String mapUserPrincipal(String principalName) {
-        username = principalName.toUpperCase();
-        return principalName;
-      }
-
-      @Override
-      public String[] mapGroupPrincipals(String principalName, Subject subject) {
-        String[] groups = new String[2];
-        int i = 0;
-        for(GroupPrincipal p : subject.getPrincipals(GroupPrincipal.class)) {
-          groups[i] = p.getName().toUpperCase();
-          i++;
-        }
-        mappedGroups = groups;
-        return groups;
-      }
-    };
-  }
-
-  @Test
-  public void testSimpleFilter() throws ServletException, IOException,
-      URISyntaxException {
-
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.replay( config );
-
-    final HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
-    EasyMock.replay( request );
-
-    final HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
-    EasyMock.replay( response );
-
-    final FilterChain chain = new FilterChain() {
-      @Override
-      public void doFilter(ServletRequest request, ServletResponse response)
-          throws IOException, ServletException {
-      }
-    };
-    
-    Subject subject = new Subject();
-    subject.getPrincipals().add(new PrimaryPrincipal("larry"));
-    subject.getPrincipals().add(new GroupPrincipal("users"));
-    subject.getPrincipals().add(new GroupPrincipal("admin"));
-    try {
-      Subject.doAs(
-        subject,
-        new PrivilegedExceptionAction<Object>() {
-          public Object run() throws Exception {
-            filter.doFilter(request, response, chain);
-            return null;
-          }
-        });
-    }
-    catch (PrivilegedActionException e) {
-      Throwable t = e.getCause();
-      if (t instanceof IOException) {
-        throw (IOException) t;
-      }
-      else if (t instanceof ServletException) {
-        throw (ServletException) t;
-      }
-      else {
-        throw new ServletException(t);
-      }
-    }
-    assertEquals("LARRY", username);
-    assertEquals(mappedGroups.length, 2);
-    assertTrue(mappedGroups[0].equals("USERS") || mappedGroups[0].equals("ADMIN"));
-    assertTrue(mappedGroups[1], mappedGroups[1].equals("USERS") || mappedGroups[1].equals("ADMIN"));
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/filter/IdentityAssertionHttpServletRequestWrapperTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/filter/IdentityAssertionHttpServletRequestWrapperTest.java b/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/filter/IdentityAssertionHttpServletRequestWrapperTest.java
deleted file mode 100644
index 709c6e4..0000000
--- a/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/filter/IdentityAssertionHttpServletRequestWrapperTest.java
+++ /dev/null
@@ -1,279 +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.hadoop.gateway.identityasserter.filter;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.identityasserter.common.filter.IdentityAsserterHttpServletRequestWrapper;
-import org.apache.hadoop.test.category.FastTests;
-import org.apache.hadoop.test.category.UnitTests;
-import org.apache.hadoop.test.mock.MockHttpServletRequest;
-import org.apache.hadoop.test.mock.MockServletInputStream;
-import org.junit.Test;
-import org.junit.After;
-import org.junit.experimental.categories.Category;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.not;
-
-@Category( { UnitTests.class, FastTests.class } )
-public class IdentityAssertionHttpServletRequestWrapperTest {
-
-  @After
-  public void resetSystemProps() {
-    System.setProperty(GatewayConfig.HADOOP_KERBEROS_SECURED, "false");
-  }
-
-  @Test
-  public void testInsertUserNameInPostMethod() throws IOException {
-    String inputBody = "jar=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaWebHCat%2Fhadoop-examples.jar&class=org.apache.org.apache.hadoop.examples.WordCount&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Finput&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Foutput";
-
-    MockHttpServletRequest request = new MockHttpServletRequest();
-    request.setInputStream( new MockServletInputStream( new ByteArrayInputStream( inputBody.getBytes( "UTF-8" ) ) ) );
-    request.setCharacterEncoding( "UTF-8" );
-    request.setContentType( "application/x-www-form-urlencoded" );
-    request.setMethod("POST");
-
-    IdentityAsserterHttpServletRequestWrapper wrapper
-        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
-
-    String outputBody = IOUtils.toString( wrapper.getInputStream(), wrapper.getCharacterEncoding() );
-    String output = wrapper.getQueryString();
-    assertThat( output, containsString( "user.name=output-user" ) );
-  }
-
-  @Test
-  public void testInsertUserNameInPostMethodWithoutEncoding() throws IOException {
-    String inputBody = "jar=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaWebHCat%2Fhadoop-examples.jar&class=org.apache.org.apache.hadoop.examples.WordCount&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Finput&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Foutput";
-
-    MockHttpServletRequest request = new MockHttpServletRequest();
-    request.setInputStream( new MockServletInputStream( new ByteArrayInputStream( inputBody.getBytes( "UTF-8" ) ) ) );
-    request.setContentType( "application/x-www-form-urlencoded" );
-    request.setMethod("POST");
-
-    IdentityAsserterHttpServletRequestWrapper wrapper
-        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
-
-    String outputBody = IOUtils.toString( wrapper.getInputStream(), wrapper.getCharacterEncoding() );
-    String output = wrapper.getQueryString();
-    assertThat( output, containsString( "user.name=output-user" ) );
-  }
-
-  @Test
-  public void testInsertUserNameInPostMethodWithIso88591Encoding() throws IOException {
-    String inputBody = "jar=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaWebHCat%2Fhadoop-examples.jar&class=org.apache.org.apache.hadoop.examples.WordCount&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Finput&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Foutput";
-
-    MockHttpServletRequest request = new MockHttpServletRequest();
-    request.setInputStream( new MockServletInputStream( new ByteArrayInputStream( inputBody.getBytes( "UTF-8" ) ) ) );
-    request.setContentType( "application/x-www-form-urlencoded" );
-    request.setCharacterEncoding( "ISO-8859-1" );
-    request.setMethod("POST");
-
-    IdentityAsserterHttpServletRequestWrapper wrapper
-        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
-
-    String outputBody = IOUtils.toString( wrapper.getInputStream(), wrapper.getCharacterEncoding() );
-    String output = wrapper.getQueryString();
-    assertThat( output, containsString( "user.name=output-user" ) );
-  }
-
-  @Test
-  public void testOverwriteUserNameInPostMethod() throws IOException {
-    String inputBody = "user.name=input-user&jar=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaWebHCat%2Fhadoop-examples.jar&class=org.apache.org.apache.hadoop.examples.WordCount&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Finput&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Foutput";
-
-    MockHttpServletRequest request = new MockHttpServletRequest();
-    request.setInputStream( new MockServletInputStream( new ByteArrayInputStream( inputBody.getBytes( "UTF-8" ) ) ) );
-    request.setCharacterEncoding( "UTF-8" );
-    request.setContentType( "application/x-www-form-urlencoded" );
-    request.setMethod("POST");
-    
-    IdentityAsserterHttpServletRequestWrapper wrapper
-        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
-
-    String outputBody = IOUtils.toString( wrapper.getInputStream(), wrapper.getCharacterEncoding() );
-    String output = wrapper.getQueryString();
-    assertThat( output, containsString( "user.name=output-user" ) );
-    assertThat( output, not( containsString( "input-user" ) ) );
-  }
-
-  @Test
-  public void testIngoreNonFormBody() throws IOException {
-    String inputBody = "user.name=input-user&jar=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaWebHCat%2Fhadoop-examples.jar&class=org.apache.org.apache.hadoop.examples.WordCount&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Finput&arg=%2Ftmp%2FGatewayWebHdfsFuncTest%2FtestJavaMapReduceViaTempleton%2Foutput";
-
-    MockHttpServletRequest request = new MockHttpServletRequest();
-    request.setInputStream( new MockServletInputStream( new ByteArrayInputStream( inputBody.getBytes( "UTF-8" ) ) ) );
-    request.setCharacterEncoding( "UTF-8" );
-    request.setContentType( "text/plain" );
-
-    IdentityAsserterHttpServletRequestWrapper wrapper
-        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
-
-    String outputBody = IOUtils.toString( wrapper.getInputStream(), wrapper.getCharacterEncoding() );
-
-    assertThat( outputBody, containsString( "user.name=input-user" ) );
-    assertThat( outputBody, not( containsString( "output-user" ) ) );
-  }
-
-  @Test
-  public void testInsertUserNameInQueryString() {
-    String input = "param=value";
-
-    MockHttpServletRequest request = new MockHttpServletRequest();
-    request.setQueryString( input );
-
-    IdentityAsserterHttpServletRequestWrapper wrapper
-        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
-
-    String output = wrapper.getQueryString();
-
-    assertThat( output, containsString( "user.name=output-user" ) );
-  }
-
-  @Test
-  public void testInsertDoAsInQueryString() {
-    System.setProperty(GatewayConfig.HADOOP_KERBEROS_SECURED, "true");
-    MockHttpServletRequest request = new MockHttpServletRequest();
-    request.setQueryString("op=LISTSTATUS&user.name=jack&User.Name=jill&DOas=admin&doas=root");
-
-    IdentityAsserterHttpServletRequestWrapper wrapper
-        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
-
-    String output = wrapper.getQueryString();
-    assertThat(output, is("op=LISTSTATUS&doAs=output-user"));
-  }
-
-  @Test
-  public void testInsertUserNameInNullQueryString() {
-    String input = null;
-
-    MockHttpServletRequest request = new MockHttpServletRequest();
-    request.setQueryString( input );
-
-    IdentityAsserterHttpServletRequestWrapper wrapper
-        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
-
-    String output = wrapper.getQueryString();
-
-    assertThat( output, containsString( "user.name=output-user" ) );
-  }
-
-  @Test
-  public void testInsertUserNameInNullQueryStringForGET() {
-    String input = null;
-
-    MockHttpServletRequest request = new MockHttpServletRequest();
-    request.setQueryString( input );
-
-    IdentityAsserterHttpServletRequestWrapper wrapper
-        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
-
-    String output = wrapper.getQueryString();
-
-    assertThat( output, containsString( "user.name=output-user" ) );
-  }
-
-  @Test
-  public void testInsertUserNameInQueryStringForPOST() {
-    String input = null;
-
-    MockHttpServletRequest request = new MockHttpServletRequest();
-    request.setQueryString( input );
-    request.setMethod("POST");
-
-    IdentityAsserterHttpServletRequestWrapper wrapper
-        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
-
-    String output = wrapper.getQueryString();
-
-    assertThat( output, containsString( "user.name=output-user" ) );
-  }
-
-  @Test
-  public void testOverwriteUserNameInQueryString() {
-    String input = "user.name=input-user";
-
-    MockHttpServletRequest request = new MockHttpServletRequest();
-    request.setQueryString( input );
-
-    IdentityAsserterHttpServletRequestWrapper wrapper
-        = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
-
-    String output = wrapper.getQueryString();
-
-    assertThat( output, containsString( "user.name=output-user" ) );
-    assertThat( output, not( containsString( "input-user" ) ) );
-  }
-
-  @Test
-  public void testParameterWithNullValueInQueryString() {
-    String input = "paramWithNullValue&param2=abc";
-
-    MockHttpServletRequest request = new MockHttpServletRequest();
-    request.setQueryString( input );
-
-    IdentityAsserterHttpServletRequestWrapper wrapper
-      = new IdentityAsserterHttpServletRequestWrapper( request, "output-user" );
-
-    String output = wrapper.getQueryString();
-
-    assertThat( output, containsString( "user.name=output-user" ) );
-    assertThat( output, containsString( "paramWithNullValue" ) );
-    assertThat( output, containsString( "param2=abc" ) );
-  }
-
-  @Test
-  public void testUrlEncode() {
-    String s;
-    HashMap<String,List<String>> m;
-
-    m = new HashMap<>();
-    m.put( "null-values", null );
-    s = IdentityAsserterHttpServletRequestWrapper.urlEncode( m, "UTF-8" );
-    assertThat( s, is( "null-values" ) );
-
-    m = new HashMap<>();
-    m.put( "no-values", new ArrayList<String>(0) );
-    s = IdentityAsserterHttpServletRequestWrapper.urlEncode( m, "UTF-8" );
-    assertThat( s, is( "no-values" ) );
-
-    m = new HashMap<>();
-    List<String> lst = new ArrayList<String>();
-    lst.add("value1");
-    m.put( "one-value", lst);
-    s = IdentityAsserterHttpServletRequestWrapper.urlEncode( m, "UTF-8" );
-    assertThat( s, is( "one-value=value1" ) );
-
-    m = new HashMap<>();
-    lst = new ArrayList<String>();
-    String[] a = {"value1", "value2"};
-    lst.addAll(Arrays.asList(a));
-    m.put( "two-values", lst);
-    s = IdentityAsserterHttpServletRequestWrapper.urlEncode( m, "UTF-8" );
-    assertThat( s, is( "two-values=value1&two-values=value2" ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionDescriptorTest.java b/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionDescriptorTest.java
deleted file mode 100644
index 51f9d57..0000000
--- a/gateway-provider-identity-assertion-common/src/test/java/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionDescriptorTest.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.hadoop.gateway.identityasserter.function;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-import org.apache.hadoop.gateway.identityasserter.common.function.UsernameFunctionDescriptor;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class UsernameFunctionDescriptorTest {
-
-  @Test
-  public void testName() throws Exception {
-    UsernameFunctionDescriptor descriptor = new UsernameFunctionDescriptor();
-    assertThat( descriptor.name(), is( "username" ) );
-  }
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
-    Iterator iterator = loader.iterator();
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof UsernameFunctionDescriptor ) {
-        return;
-      }
-    }
-    fail( "Failed to find UsernameFunctionDescriptor via service loader." );
-  }
-
-}


[47/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/test/TestMessageRecord.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/test/TestMessageRecord.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/test/TestMessageRecord.java
deleted file mode 100644
index 46edf98..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/messages/loggers/test/TestMessageRecord.java
+++ /dev/null
@@ -1,67 +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.hadoop.gateway.i18n.messages.loggers.test;
-
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-
-/**
- *
- */
-public class TestMessageRecord {
-
-  private final TestMessageLogger logger;
-  private final StackTraceElement caller;
-  private final MessageLevel level;
-  private final String id;
-  private final String message;
-  private final Throwable throwable;
-
-  public TestMessageRecord( TestMessageLogger logger, StackTraceElement caller, MessageLevel level, String id, String message, Throwable throwable ) {
-    this.logger = logger;
-    this.caller = caller;
-    this.level = level;
-    this.id = id;
-    this.message = message;
-    this.throwable = throwable;
-  }
-  
-  public TestMessageLogger getLogger() {
-    return logger;
-  }
-
-  public StackTraceElement getCaller() {
-    return caller;
-  }
-
-  public MessageLevel getLevel() {
-    return level;
-  }
-
-  public String getId() {
-    return id;
-  }
-
-  public String getMessage() {
-    return message;
-  }
-
-  public Throwable getThrowable() {
-    return throwable;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/Resource.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/Resource.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/Resource.java
deleted file mode 100644
index 727b385..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/Resource.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.hadoop.gateway.i18n.resources;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- *
- */
-@Retention( RetentionPolicy.RUNTIME )
-@Target( ElementType.METHOD )
-public @interface Resource {
-  static final String DEFAULT_TEXT = "{}";
-  String text() default DEFAULT_TEXT;
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/Resources.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/Resources.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/Resources.java
deleted file mode 100644
index 2762dd5..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/Resources.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.hadoop.gateway.i18n.resources;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- *
- */
-@Retention( RetentionPolicy.RUNTIME )
-@Target( ElementType.TYPE )
-public @interface Resources {
-  static final String DEFAULT_BUNDLE = "";
-  String bundle() default DEFAULT_BUNDLE;
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/ResourcesFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/ResourcesFactory.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/ResourcesFactory.java
deleted file mode 100644
index b98adc5..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/ResourcesFactory.java
+++ /dev/null
@@ -1,46 +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.hadoop.gateway.i18n.resources;
-
-import java.lang.reflect.Proxy;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- *
- */
-public class ResourcesFactory {
-
-  private static Map<Class<?>, Object> proxies = new ConcurrentHashMap<Class<?>, Object>();
-
-  @SuppressWarnings( "unchecked" )
-  public static <T> T get( Class<T> clazz ) {
-    Object proxy = proxies.get( clazz );
-    if( proxy == null ) {
-      Resources anno = clazz.getAnnotation( Resources.class );
-      if( anno == null ) {
-        throw new IllegalArgumentException( clazz.getName() + " missing @" + Resources.class.getCanonicalName() );
-      }
-      ResourcesInvoker invoker = new ResourcesInvoker( clazz );
-      proxy = Proxy.newProxyInstance( clazz.getClassLoader(), new Class[]{ clazz }, invoker );
-      proxies.put( clazz, proxy );
-    }
-    return (T)proxy;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/ResourcesInvoker.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/ResourcesInvoker.java b/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/ResourcesInvoker.java
deleted file mode 100644
index 865f8db..0000000
--- a/gateway-i18n/src/main/java/org/apache/hadoop/gateway/i18n/resources/ResourcesInvoker.java
+++ /dev/null
@@ -1,162 +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.hadoop.gateway.i18n.resources;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.text.MessageFormat;
-import java.util.ListResourceBundle;
-import java.util.Locale;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- *
- */
-public class ResourcesInvoker implements InvocationHandler {
-
-  private static ResourceBundle MISSING_BUNDLE = new ListResourceBundle() {
-    @Override
-    protected Object[][] getContents() {
-      return null;
-    }
-  };
-
-  private Class bundleClass;
-  private String bundleName;
-  private ConcurrentHashMap<Locale, ResourceBundle> bundles;
-
-  public ResourcesInvoker( Class<?> bundleClass ) {
-    this.bundleClass = bundleClass;
-    this.bundleName = calcBundleName( bundleClass );
-    this.bundles = new ConcurrentHashMap<Locale, ResourceBundle>();
-  }
-
-  @Override
-  public Object invoke( final Object proxy, final Method method, final Object[] args ) throws Throwable {
-    return getText( method, args );
-  }
-
-  protected final String getText( final Method method, final Object[] args ) {
-    String pattern = getPattern( method );
-    String text = MessageFormat.format( pattern, args );
-    return text;
-  }
-
-  protected final String getPattern( final Method method ) {
-    String pattern = getBundlePattern( method );
-    if( pattern == null ) {
-      pattern = getAnnotationPattern( method );
-      if( pattern == null || Resource.DEFAULT_TEXT.equals( pattern ) ) {
-        pattern = getDefaultPattern( method );
-      }
-    }
-    return pattern;
-  }
-
-  protected String getAnnotationPattern( final Method method ) {
-    String pattern = null;
-    final Resource anno = method.getAnnotation( Resource.class );
-    if( anno != null ) {
-      pattern = anno.text();
-    }
-    return pattern;
-  }
-
-  protected final String getBundlePattern( final Method method ) {
-    String pattern = null;
-    final ResourceBundle bundle = findBundle();
-    if( bundle != null && bundle.containsKey( method.getName() ) ) {
-      pattern = bundle.getString( method.getName() );
-    }
-    return pattern;
-  }
-
-  protected static final String getDefaultPattern( final Method method ) {
-    final String prefix = method.getName();
-    String suffix;
-    final int params = method.getParameterTypes().length;
-    switch( params ) {
-      case( 0 )  : suffix = ""; break;
-      case( 1 )  : suffix = "(\"{0}\")"; break;
-      case( 2 )  : suffix = "(\"{0}\",\"{1}\")"; break;
-      case( 3 )  : suffix = "(\"{0}\",\"{1}\",\"{2}\")"; break;
-      case( 4 )  : suffix = "(\"{0}\",\"{1}\",\"{2}\",\"{3}\")"; break;
-      case( 5 )  : suffix = "(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\")"; break;
-      case( 6 )  : suffix = "(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\")"; break;
-      case( 7 )  : suffix = "(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\")"; break;
-      case( 8 )  : suffix = "(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\")"; break;
-      case( 9 )  : suffix = "(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\")"; break;
-      case( 10 ) : suffix = "(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\")"; break;
-      default    : suffix = createDefaultPatternSuffix( params );
-    }
-    return prefix + suffix;
-  }
-
-  private static final String createDefaultPatternSuffix( final int size ) {
-    StringBuilder builder = new StringBuilder( 1 + size*7 );
-    builder.append( "(" );
-    for( int i=0; i<size; i++ ) {
-      if( i>0 ) {
-        builder.append( "," );
-      }
-      builder.append( "\"{" ).append( i ).append( "}\"" );
-    }
-    builder.append( ")" );
-    return builder.toString();
-
-  }
-
-  private static final String calcBundleName( final Class<?> clazz ) {
-    String bundle = null;
-    final Resources anno = clazz.getAnnotation( Resources.class );
-    if( anno != null ) {
-      bundle = anno.bundle();
-      if( Resources.DEFAULT_BUNDLE.equals( bundle ) ) {
-        bundle = null;
-      }
-    }
-    if( bundle == null ) {
-      bundle = clazz.getCanonicalName().replace( '.', '/' );
-    }
-    return bundle;
-  }
-
-
-  protected String getBundleName() {
-    return bundleName;
-  }
-
-  protected final ResourceBundle findBundle() {
-    final Locale locale = Locale.getDefault();
-    ResourceBundle bundle = bundles.get( locale );
-    if( bundle == MISSING_BUNDLE ) {
-      bundle = null;
-    } else if ( bundle == null ) {
-      try {
-        bundle = ResourceBundle.getBundle( getBundleName(), locale, bundleClass.getClassLoader() );
-        bundles.put( locale, bundle );
-      } catch( MissingResourceException e ) {
-        bundles.put( locale, MISSING_BUNDLE );
-      }
-    }
-    return bundle;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/Message.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/Message.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/Message.java
new file mode 100644
index 0000000..68761ac
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/Message.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.knox.gateway.i18n.messages;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ *
+ */
+@Retention( RetentionPolicy.RUNTIME )
+@Target( ElementType.METHOD )
+public @interface Message {
+  static final String DEFAULT_TEXT = "{}";
+  static final int DEFAULT_CODE = -1;
+  MessageLevel level() default MessageLevel.INFO;
+  int code() default DEFAULT_CODE;
+  String text() default DEFAULT_TEXT;
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessageLevel.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessageLevel.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessageLevel.java
new file mode 100644
index 0000000..38058de
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessageLevel.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.knox.gateway.i18n.messages;
+
+/**
+ *
+ */
+public enum MessageLevel {
+  FATAL, ERROR, WARN, INFO, DEBUG, TRACE
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessageLogger.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessageLogger.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessageLogger.java
new file mode 100644
index 0000000..851ec80
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessageLogger.java
@@ -0,0 +1,29 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.messages;
+
+/**
+ *
+ */
+public interface MessageLogger {
+
+  boolean isLoggable( MessageLevel level );
+
+  void log( StackTraceElement caller, MessageLevel messageLevel, String messageId, String messageText, Throwable thrown );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessageLoggerFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessageLoggerFactory.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessageLoggerFactory.java
new file mode 100644
index 0000000..3d87360
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessageLoggerFactory.java
@@ -0,0 +1,27 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.messages;
+
+/**
+ *
+ */
+public interface MessageLoggerFactory {
+
+  MessageLogger getLogger( String name );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/Messages.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/Messages.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/Messages.java
new file mode 100644
index 0000000..041da6d
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/Messages.java
@@ -0,0 +1,37 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.messages;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ *
+ */
+@Retention( RetentionPolicy.RUNTIME )
+@Target( ElementType.TYPE )
+public @interface Messages {
+  static final String DEFAULT_BUNDLE = "";
+  static final String DEFAULT_LOGGER = "";
+  static final String DEFAULT_CODES = "{0}";
+  String bundle() default DEFAULT_BUNDLE;
+  String logger() default DEFAULT_LOGGER;
+  String codes() default DEFAULT_CODES;
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessagesFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessagesFactory.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessagesFactory.java
new file mode 100644
index 0000000..26a48e9
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessagesFactory.java
@@ -0,0 +1,63 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.messages;
+
+import org.apache.knox.gateway.i18n.messages.loggers.jdk.JdkMessageLoggerFactory;
+
+import java.lang.reflect.Proxy;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.ServiceLoader;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ *
+ */
+public class MessagesFactory {
+
+  private static MessageLoggerFactory loggers = getMessageLoggerFactory();
+  private static Map<Class<?>, Object> proxies = new ConcurrentHashMap<Class<?>, Object>();
+
+  @SuppressWarnings( "unchecked" )
+  public static <T> T get( Class<T> clazz ) {
+    Object proxy = proxies.get( clazz );
+    if( proxy == null ) {
+      Messages anno = clazz.getAnnotation( Messages.class );
+      if( anno == null ) {
+        throw new IllegalArgumentException( clazz.getName() + " missing @" + Messages.class.getCanonicalName() );
+      }
+      MessagesInvoker invoker = new MessagesInvoker( clazz, loggers );
+      proxy = Proxy.newProxyInstance( clazz.getClassLoader(), new Class[]{ clazz }, invoker );
+      proxies.put( clazz, proxy );
+    }
+    return (T)proxy;
+  }
+
+  private static MessageLoggerFactory getMessageLoggerFactory() {
+    MessageLoggerFactory factory;
+    ServiceLoader<MessageLoggerFactory> loader = ServiceLoader.load( MessageLoggerFactory.class );
+    Iterator<MessageLoggerFactory> factories = loader.iterator();
+    if( factories != null && factories.hasNext() ) {
+      factory = loader.iterator().next();
+    } else {
+      factory = new JdkMessageLoggerFactory();
+    }
+    return factory;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessagesInvoker.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessagesInvoker.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessagesInvoker.java
new file mode 100644
index 0000000..87e3845
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/MessagesInvoker.java
@@ -0,0 +1,173 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.messages;
+
+import org.apache.knox.gateway.i18n.resources.ResourcesInvoker;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.text.MessageFormat;
+
+/**
+ *
+ */
+public class MessagesInvoker extends ResourcesInvoker implements InvocationHandler {
+
+  private String codes;
+  private MessageLogger logger;
+  private String bundle;
+
+  public MessagesInvoker( Class<?> clazz, MessageLoggerFactory loggers ) {
+    super( clazz );
+    Messages anno = clazz.getAnnotation( Messages.class );
+    codes = calcCodePattern( clazz, anno );
+    bundle = calcBundleName( clazz, anno );
+    logger = getLogger( clazz, anno, loggers );
+  }
+
+  @Override
+  public Object invoke( final Object proxy, final Method method, final Object[] args ) throws Throwable {
+    String message = null;
+    MessageLevel level = getLevel( method );
+    if( logger.isLoggable( level ) ) {
+      message = getText( method, args );
+      String code = getCode( method );
+      Throwable throwable = findLoggableThrowable( logger, method, args );
+      // Supposedly this Throwable way is faster than the Thread way.
+      // From looking at the JRE code it looks this is probably the case.
+      // The second version ends up calling the first version after getting the current thread
+      // and then checking that it is being called from the current thread.
+      //TODO: Should probably only do this if the logger is at debug or finer to make sure there isn't a performance impact during production usage.
+      StackTraceElement caller = new Throwable().getStackTrace()[2];
+      // StackTraceElement caller = Thread.currentThread().getStackTrace()[3];
+      logger.log( caller, level, code, message, throwable );
+    }
+    return message;
+  }
+
+  private final String getCode( final Method method ) {
+    String code = null;
+    Message anno = method.getAnnotation( Message.class );
+    if( anno != null ) {
+      int num = anno.code();
+      if( Message.DEFAULT_CODE != num ) {
+        code = MessageFormat.format( codes, num );
+      }
+    }
+    return code;
+  }
+
+  private static final StackTrace getStackTraceAnno( final Method method, final int param ) {
+    final Annotation[] annos = method.getParameterAnnotations()[ param ];
+    for( Annotation anno: annos ) {
+      if( anno instanceof StackTrace ) {
+        return (StackTrace)anno;
+      }
+    }
+    return null;
+  }
+
+  private static final Throwable findLoggableThrowable( final MessageLogger logger, final Method method, final Object[] args ) {
+    Throwable throwable = null;
+    if( args != null ) {
+      for( int i=0; i<args.length; i++ ) {
+        Object arg = args[i];
+        if( arg instanceof Throwable ) {
+          StackTrace anno = getStackTraceAnno( method, i );
+          if( anno != null ) {
+            if( logger.isLoggable( anno.level() ) ) {
+              throwable = (Throwable)arg;
+              break;
+            }
+          }
+        }
+      }
+    }
+    return throwable;
+  }
+
+  protected String getAnnotationPattern( final Method method ) {
+    String pattern = null;
+    Message anno = method.getAnnotation( Message.class );
+    if( anno != null ) {
+      pattern = anno.text();
+    }
+    return pattern;
+  }
+
+  private static final MessageLevel getLevel( final Method method ) {
+    MessageLevel level;
+    Message anno = method.getAnnotation( Message.class );
+    if( anno == null ) {
+      level = MessageLevel.INFO;
+    } else {
+      level = anno.level();
+    }
+    return level;
+  }
+
+  private static String calcCodePattern( final Class<?> clazz, final Messages anno ) {
+    String pattern = anno.codes();
+    if( Messages.DEFAULT_CODES.equals( pattern ) ) {
+      pattern = clazz.getCanonicalName().replace( '.', '/' );
+    }
+    return pattern;
+  }
+
+  private static String calcBundleName( Class<?> clazz, Messages anno ) {
+    String bundle = null;
+    if( anno != null ) {
+      bundle = anno.bundle();
+      if( Messages.DEFAULT_BUNDLE.equals( bundle ) ) {
+        bundle = null;
+      }
+    }
+    if( bundle == null ) {
+      bundle = clazz.getCanonicalName().replace( '.', '/' );
+    }
+    return bundle;
+  }
+
+  private static final String calcLoggerName( final Class<?> clazz, final Messages anno ) {
+    String logger = null;
+    if( anno != null ) {
+      logger = anno.logger();
+      if( Messages.DEFAULT_LOGGER.equals( logger ) ) {
+        logger = null;
+      }
+    }
+    if( logger == null ) {
+      logger = clazz.getCanonicalName();
+    }
+    return logger;
+  }
+
+  protected String getBundleName() {
+    return bundle;
+  }
+
+  private static final MessageLogger getLogger( final Class<?> clazz, final Messages anno, final MessageLoggerFactory loggers ) {
+    return loggers.getLogger( calcLoggerName( clazz, anno ) );
+  }
+
+  public String toString() {
+    return "MessageInvoker["+bundle+"]";
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/StackTrace.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/StackTrace.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/StackTrace.java
new file mode 100644
index 0000000..e4aec45
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/StackTrace.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.knox.gateway.i18n.messages;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ *
+ */
+@Retention( RetentionPolicy.RUNTIME )
+@Target( ElementType.PARAMETER )
+public @interface StackTrace {
+  MessageLevel level() default MessageLevel.DEBUG;
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/jdk/JdkMessageLogger.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/jdk/JdkMessageLogger.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/jdk/JdkMessageLogger.java
new file mode 100644
index 0000000..ead570a
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/jdk/JdkMessageLogger.java
@@ -0,0 +1,67 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.messages.loggers.jdk;
+
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.MessageLogger;
+
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
+
+/**
+ *
+ */
+final class JdkMessageLogger implements MessageLogger {
+
+  private final Logger logger;
+
+  JdkMessageLogger( final Logger logger ) {
+    this.logger = logger;
+  }
+
+  @Override
+  public final boolean isLoggable( final MessageLevel level ) {
+    return logger.isLoggable( toLevel( level ) );
+  }
+
+  //TODO: Handle message ID.
+  @Override
+  public final void log( final StackTraceElement caller, final MessageLevel level, final String id, final String message, final Throwable thrown ) {
+    LogRecord record = new LogRecord( toLevel( level ), message );
+    record.setSourceClassName( caller.getClassName() );
+    record.setSourceMethodName( caller.getMethodName() );
+    if( thrown != null ) {
+      record.setThrown( thrown );
+    }
+    logger.log( record );
+  }
+
+  private static final Level toLevel( final MessageLevel level ) {
+    switch( level ) {
+      case FATAL: return Level.SEVERE;
+      case ERROR: return Level.SEVERE;
+      case WARN: return Level.WARNING;
+      case INFO: return Level.INFO;
+      case DEBUG: return Level.FINE;
+      case TRACE: return Level.FINEST;
+      default: return Level.OFF;
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/jdk/JdkMessageLoggerFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/jdk/JdkMessageLoggerFactory.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/jdk/JdkMessageLoggerFactory.java
new file mode 100644
index 0000000..d1127bd
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/jdk/JdkMessageLoggerFactory.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.knox.gateway.i18n.messages.loggers.jdk;
+
+import org.apache.knox.gateway.i18n.messages.MessageLogger;
+import org.apache.knox.gateway.i18n.messages.MessageLoggerFactory;
+
+import java.util.logging.Logger;
+
+/**
+ *
+ */
+public class JdkMessageLoggerFactory implements MessageLoggerFactory {
+
+  @Override
+  public MessageLogger getLogger( String name ) {
+    return new JdkMessageLogger( Logger.getLogger( name ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sout/SoutMessageLogger.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sout/SoutMessageLogger.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sout/SoutMessageLogger.java
new file mode 100644
index 0000000..b444faae
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sout/SoutMessageLogger.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.knox.gateway.i18n.messages.loggers.sout;
+
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.MessageLogger;
+
+import java.text.MessageFormat;
+
+/**
+ *
+ */
+public class SoutMessageLogger implements MessageLogger {
+
+  private static final String FORMAT_WITHOUT_ID = "{0}: {2}";
+  private static final String FORMAT_WITH_ID = "{0}: {2} [{1}]";
+
+  private final String name;
+
+  SoutMessageLogger( String name ) {
+    this.name = name;
+  }
+
+  @Override
+  public boolean isLoggable( MessageLevel level ) {
+    return true;
+  }
+
+  private static final String getFormat( final String id ) {
+    return( id == null ) ? FORMAT_WITHOUT_ID : FORMAT_WITH_ID;
+  }
+
+  @Override
+  public void log( final StackTraceElement caller, final MessageLevel level, final String id, final String message, final Throwable thrown ) {
+    System.out.println( MessageFormat.format( getFormat( id ), level, id, message ) ); // I18N not required.
+    if( thrown != null ) {
+      thrown.printStackTrace();
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sout/SoutMessageLoggerFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sout/SoutMessageLoggerFactory.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sout/SoutMessageLoggerFactory.java
new file mode 100644
index 0000000..567d5b8
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/sout/SoutMessageLoggerFactory.java
@@ -0,0 +1,55 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.messages.loggers.sout;
+
+import org.apache.knox.gateway.i18n.messages.MessageLogger;
+import org.apache.knox.gateway.i18n.messages.MessageLoggerFactory;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ *
+ */
+public class SoutMessageLoggerFactory implements MessageLoggerFactory {
+
+  private static SoutMessageLoggerFactory INSTANCE;
+  private static final Map<String,MessageLogger> LOGGERS = new ConcurrentHashMap<String,MessageLogger>();
+
+  public static SoutMessageLoggerFactory getFactory() {
+    if( INSTANCE == null ) {
+      INSTANCE = new SoutMessageLoggerFactory();
+    }
+    return INSTANCE;
+  }
+
+  public SoutMessageLoggerFactory() {
+    INSTANCE = this;
+  }
+
+  @Override
+  public MessageLogger getLogger( String name ) {
+    MessageLogger logger = LOGGERS.get( name );
+    if( logger == null ) {
+      logger = new SoutMessageLogger( name );
+      LOGGERS.put( name, logger );
+    }
+    return logger;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/test/TestMessageLogger.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/test/TestMessageLogger.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/test/TestMessageLogger.java
new file mode 100644
index 0000000..4641b22
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/test/TestMessageLogger.java
@@ -0,0 +1,55 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.messages.loggers.test;
+
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.MessageLogger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ *
+ */
+public class TestMessageLogger implements MessageLogger {
+
+  public final List<TestMessageRecord> records = Collections.synchronizedList( new ArrayList<TestMessageRecord>() );
+
+  public final String name;
+
+  TestMessageLogger( final String name ) {
+    this.name = name;
+  }
+
+  public String getName() {
+    return name;
+  }
+
+  @Override
+  public boolean isLoggable( MessageLevel level ) {
+    return true;
+  }
+
+  @Override
+  public void log( final StackTraceElement caller, final MessageLevel level, final String id, final String text, final Throwable thrown ) {
+    TestMessageRecord record = new TestMessageRecord( this, caller, level, id, text, thrown );
+    records.add( record );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/test/TestMessageLoggerFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/test/TestMessageLoggerFactory.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/test/TestMessageLoggerFactory.java
new file mode 100644
index 0000000..3d093a9
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/test/TestMessageLoggerFactory.java
@@ -0,0 +1,55 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.messages.loggers.test;
+
+import org.apache.knox.gateway.i18n.messages.MessageLogger;
+import org.apache.knox.gateway.i18n.messages.MessageLoggerFactory;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ *
+ */
+public class TestMessageLoggerFactory implements MessageLoggerFactory {
+
+  private static TestMessageLoggerFactory INSTANCE;
+  private static final Map<String,MessageLogger> LOGGERS = new ConcurrentHashMap<String,MessageLogger>();
+
+  public static TestMessageLoggerFactory getFactory() {
+    if( INSTANCE == null ) {
+      INSTANCE = new TestMessageLoggerFactory();
+    }
+    return INSTANCE;
+  }
+
+  public TestMessageLoggerFactory() {
+    INSTANCE = this;
+  }
+
+  @Override
+  public MessageLogger getLogger( String name ) {
+    MessageLogger logger = LOGGERS.get( name );
+    if( logger == null ) {
+      logger = new TestMessageLogger( name );
+      LOGGERS.put( name, logger );
+    }
+    return logger;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/test/TestMessageRecord.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/test/TestMessageRecord.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/test/TestMessageRecord.java
new file mode 100644
index 0000000..e51b0a6
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/test/TestMessageRecord.java
@@ -0,0 +1,67 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.messages.loggers.test;
+
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+
+/**
+ *
+ */
+public class TestMessageRecord {
+
+  private final TestMessageLogger logger;
+  private final StackTraceElement caller;
+  private final MessageLevel level;
+  private final String id;
+  private final String message;
+  private final Throwable throwable;
+
+  public TestMessageRecord( TestMessageLogger logger, StackTraceElement caller, MessageLevel level, String id, String message, Throwable throwable ) {
+    this.logger = logger;
+    this.caller = caller;
+    this.level = level;
+    this.id = id;
+    this.message = message;
+    this.throwable = throwable;
+  }
+  
+  public TestMessageLogger getLogger() {
+    return logger;
+  }
+
+  public StackTraceElement getCaller() {
+    return caller;
+  }
+
+  public MessageLevel getLevel() {
+    return level;
+  }
+
+  public String getId() {
+    return id;
+  }
+
+  public String getMessage() {
+    return message;
+  }
+
+  public Throwable getThrowable() {
+    return throwable;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/Resource.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/Resource.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/Resource.java
new file mode 100644
index 0000000..5e37c64
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/Resource.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.knox.gateway.i18n.resources;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ *
+ */
+@Retention( RetentionPolicy.RUNTIME )
+@Target( ElementType.METHOD )
+public @interface Resource {
+  static final String DEFAULT_TEXT = "{}";
+  String text() default DEFAULT_TEXT;
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/Resources.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/Resources.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/Resources.java
new file mode 100644
index 0000000..4d0c053
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/Resources.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.knox.gateway.i18n.resources;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ *
+ */
+@Retention( RetentionPolicy.RUNTIME )
+@Target( ElementType.TYPE )
+public @interface Resources {
+  static final String DEFAULT_BUNDLE = "";
+  String bundle() default DEFAULT_BUNDLE;
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/ResourcesFactory.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/ResourcesFactory.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/ResourcesFactory.java
new file mode 100644
index 0000000..cf7fa23
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/ResourcesFactory.java
@@ -0,0 +1,46 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.resources;
+
+import java.lang.reflect.Proxy;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ *
+ */
+public class ResourcesFactory {
+
+  private static Map<Class<?>, Object> proxies = new ConcurrentHashMap<Class<?>, Object>();
+
+  @SuppressWarnings( "unchecked" )
+  public static <T> T get( Class<T> clazz ) {
+    Object proxy = proxies.get( clazz );
+    if( proxy == null ) {
+      Resources anno = clazz.getAnnotation( Resources.class );
+      if( anno == null ) {
+        throw new IllegalArgumentException( clazz.getName() + " missing @" + Resources.class.getCanonicalName() );
+      }
+      ResourcesInvoker invoker = new ResourcesInvoker( clazz );
+      proxy = Proxy.newProxyInstance( clazz.getClassLoader(), new Class[]{ clazz }, invoker );
+      proxies.put( clazz, proxy );
+    }
+    return (T)proxy;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/ResourcesInvoker.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/ResourcesInvoker.java b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/ResourcesInvoker.java
new file mode 100644
index 0000000..065da0c
--- /dev/null
+++ b/gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/ResourcesInvoker.java
@@ -0,0 +1,162 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.resources;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.text.MessageFormat;
+import java.util.ListResourceBundle;
+import java.util.Locale;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ *
+ */
+public class ResourcesInvoker implements InvocationHandler {
+
+  private static ResourceBundle MISSING_BUNDLE = new ListResourceBundle() {
+    @Override
+    protected Object[][] getContents() {
+      return null;
+    }
+  };
+
+  private Class bundleClass;
+  private String bundleName;
+  private ConcurrentHashMap<Locale, ResourceBundle> bundles;
+
+  public ResourcesInvoker( Class<?> bundleClass ) {
+    this.bundleClass = bundleClass;
+    this.bundleName = calcBundleName( bundleClass );
+    this.bundles = new ConcurrentHashMap<Locale, ResourceBundle>();
+  }
+
+  @Override
+  public Object invoke( final Object proxy, final Method method, final Object[] args ) throws Throwable {
+    return getText( method, args );
+  }
+
+  protected final String getText( final Method method, final Object[] args ) {
+    String pattern = getPattern( method );
+    String text = MessageFormat.format( pattern, args );
+    return text;
+  }
+
+  protected final String getPattern( final Method method ) {
+    String pattern = getBundlePattern( method );
+    if( pattern == null ) {
+      pattern = getAnnotationPattern( method );
+      if( pattern == null || Resource.DEFAULT_TEXT.equals( pattern ) ) {
+        pattern = getDefaultPattern( method );
+      }
+    }
+    return pattern;
+  }
+
+  protected String getAnnotationPattern( final Method method ) {
+    String pattern = null;
+    final Resource anno = method.getAnnotation( Resource.class );
+    if( anno != null ) {
+      pattern = anno.text();
+    }
+    return pattern;
+  }
+
+  protected final String getBundlePattern( final Method method ) {
+    String pattern = null;
+    final ResourceBundle bundle = findBundle();
+    if( bundle != null && bundle.containsKey( method.getName() ) ) {
+      pattern = bundle.getString( method.getName() );
+    }
+    return pattern;
+  }
+
+  protected static final String getDefaultPattern( final Method method ) {
+    final String prefix = method.getName();
+    String suffix;
+    final int params = method.getParameterTypes().length;
+    switch( params ) {
+      case( 0 )  : suffix = ""; break;
+      case( 1 )  : suffix = "(\"{0}\")"; break;
+      case( 2 )  : suffix = "(\"{0}\",\"{1}\")"; break;
+      case( 3 )  : suffix = "(\"{0}\",\"{1}\",\"{2}\")"; break;
+      case( 4 )  : suffix = "(\"{0}\",\"{1}\",\"{2}\",\"{3}\")"; break;
+      case( 5 )  : suffix = "(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\")"; break;
+      case( 6 )  : suffix = "(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\")"; break;
+      case( 7 )  : suffix = "(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\")"; break;
+      case( 8 )  : suffix = "(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\")"; break;
+      case( 9 )  : suffix = "(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\")"; break;
+      case( 10 ) : suffix = "(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",\"{8}\",\"{9}\")"; break;
+      default    : suffix = createDefaultPatternSuffix( params );
+    }
+    return prefix + suffix;
+  }
+
+  private static final String createDefaultPatternSuffix( final int size ) {
+    StringBuilder builder = new StringBuilder( 1 + size*7 );
+    builder.append( "(" );
+    for( int i=0; i<size; i++ ) {
+      if( i>0 ) {
+        builder.append( "," );
+      }
+      builder.append( "\"{" ).append( i ).append( "}\"" );
+    }
+    builder.append( ")" );
+    return builder.toString();
+
+  }
+
+  private static final String calcBundleName( final Class<?> clazz ) {
+    String bundle = null;
+    final Resources anno = clazz.getAnnotation( Resources.class );
+    if( anno != null ) {
+      bundle = anno.bundle();
+      if( Resources.DEFAULT_BUNDLE.equals( bundle ) ) {
+        bundle = null;
+      }
+    }
+    if( bundle == null ) {
+      bundle = clazz.getCanonicalName().replace( '.', '/' );
+    }
+    return bundle;
+  }
+
+
+  protected String getBundleName() {
+    return bundleName;
+  }
+
+  protected final ResourceBundle findBundle() {
+    final Locale locale = Locale.getDefault();
+    ResourceBundle bundle = bundles.get( locale );
+    if( bundle == MISSING_BUNDLE ) {
+      bundle = null;
+    } else if ( bundle == null ) {
+      try {
+        bundle = ResourceBundle.getBundle( getBundleName(), locale, bundleClass.getClassLoader() );
+        bundles.put( locale, bundle );
+      } catch( MissingResourceException e ) {
+        bundles.put( locale, MISSING_BUNDLE );
+      }
+    }
+    return bundle;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/messages/MessagesTest.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/messages/MessagesTest.java b/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/messages/MessagesTest.java
deleted file mode 100644
index 56f0b69..0000000
--- a/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/messages/MessagesTest.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.hadoop.gateway.i18n.messages;
-
-import org.apache.hadoop.gateway.i18n.messages.loggers.test.TestMessageLogger;
-import org.apache.hadoop.gateway.i18n.messages.loggers.test.TestMessageLoggerFactory;
-import org.apache.hadoop.gateway.i18n.messages.loggers.test.TestMessageRecord;
-import org.apache.hadoop.test.category.FastTests;
-import org.apache.hadoop.test.category.UnitTests;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-/**
- *
- */
-@Category( { UnitTests.class, FastTests.class } )
-public class MessagesTest {
-
-  @Test
-  public void testFirst() {
-    MessagesTestSubject log = MessagesFactory.get( MessagesTestSubject.class );
-
-    log.withFullAnnotationAndParameter( 7 );
-
-    TestMessageLogger logger = (TestMessageLogger)TestMessageLoggerFactory.getFactory().getLogger( "some.logger.name" );
-    assertThat( logger.records.size(), equalTo( 1 ) );
-
-    TestMessageRecord record = logger.records.get( 0 );
-
-    assertThat( record.getCaller().getClassName(), is( this.getClass().getName() ) );
-    assertThat( record.getCaller().getMethodName(), is( "testFirst" ) );
-
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/messages/MessagesTestSubject.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/messages/MessagesTestSubject.java b/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/messages/MessagesTestSubject.java
deleted file mode 100644
index 8129aa5..0000000
--- a/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/messages/MessagesTestSubject.java
+++ /dev/null
@@ -1,46 +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.hadoop.gateway.i18n.messages;
-
-import static org.apache.hadoop.gateway.i18n.messages.MessageLevel.ERROR;
-import static org.apache.hadoop.gateway.i18n.messages.MessageLevel.INFO;
-
-/**
- *
- */
-@Messages( bundle="some.bundle.name", logger="some.logger.name", codes="ID:{0}" )
-public interface MessagesTestSubject {
-
-  @Message( level=ERROR, code=3, text="p0={0}" )
-  void withFullAnnotationAndParameter( int x );
-
-  @Message( level=INFO, code=42, text="str={0}, t={1}" )
-  void withEverything( String str, @StackTrace(level=INFO) Throwable t );
-
-  @Message
-  void withoutParams();
-
-  void withoutAnnotations( int x );
-
-  @Message
-  void withoutStackTrace( Throwable t );
-
-  @Message
-  void withMismatchedText();
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTest.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTest.java b/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTest.java
deleted file mode 100644
index 28313d9..0000000
--- a/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTest.java
+++ /dev/null
@@ -1,121 +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.hadoop.gateway.i18n.resources;
-
-import org.apache.hadoop.test.category.FastTests;
-import org.apache.hadoop.test.category.UnitTests;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import java.util.Locale;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-/**
- *
- */
-@Category( { UnitTests.class, FastTests.class } )
-public class ResourcesTest {
-
-  private Locale locale;
-
-  @Before
-  public void setup() {
-    locale = Locale.getDefault();
-  }
-
-  @After
-  public void cleanup() {
-    Locale.setDefault( locale );
-  }
-
-  @Test
-  public void testResourceFormatting() {
-
-    ResourcesTestFormattingSubject res = ResourcesFactory.get( ResourcesTestFormattingSubject.class );
-
-    assertThat(
-        res.withoutAnnotationsOrParameters(),
-        equalTo( "withoutAnnotationsOrParameters" ) );
-
-    assertThat(
-        res.withAnnotationWithoutPatternOneParam( 42 ),
-        equalTo( "withAnnotationWithoutPatternOneParam(\"42\")" ) );
-
-    assertThat(
-        res.withAnnotationWithPatternOneParam( 72 ),
-        equalTo( "before72after" ) );
-
-    assertThat(
-        res.withAnnotationWithSimplePatternOneParam( 33 ),
-        equalTo( "33" ) );
-
-    assertThat(
-        res.withoutAnnotationsWithElevenParams( "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11" ),
-        equalTo( "withoutAnnotationsWithElevenParams(\"v1\",\"v2\",\"v3\",\"v4\",\"v5\",\"v6\",\"v7\",\"v8\",\"v9\",\"v10\",\"v11\")" ) );
-
-    assertThat(
-        res.withoutAnnotationsWithOneParam( 17 ),
-        equalTo( "withoutAnnotationsWithOneParam(\"17\")" ) );
-
-    assertThat(
-        res.withMoreFormatParamsThanMethodParams( 7 ),
-        equalTo( "7,{1}" ) );
-
-    assertThat(
-        res.withLessFormatParamsThanMethodParams( 7, 11 ),
-        equalTo( "7" ) );
-  }
-
-  @Test
-  public void testResourceLocales() {
-
-    ResourcesTestLocaleSubject res = ResourcesFactory.get( ResourcesTestLocaleSubject.class );
-
-    Locale.setDefault( Locale.CHINESE ); // Change to something that we won't have test bundles for.
-    assertThat( res.testResource( "queryParam" ), equalTo( "default=[queryParam]" ) );
-
-    Locale.setDefault( Locale.ENGLISH );
-    assertThat( res.testResource( "queryParam" ), equalTo( "en=[queryParam]" ) );
-
-    Locale.setDefault( Locale.US );
-    assertThat( res.testResource( "queryParam" ), equalTo( "us=[queryParam]" ) );
-
-    Locale.setDefault( Locale.UK );
-    assertThat( res.testResource( "queryParam" ), equalTo( "uk=[queryParam]" ) );
-
-  }
-
-  @Test
-  public void testNamedBundle() {
-
-    ResourcesTestNamedSubject res = ResourcesFactory.get( ResourcesTestNamedSubject.class );
-
-    Locale.setDefault( Locale.CHINESE ); // Change to something that we won't have test bundles for.
-    assertThat( res.testResource( "queryParam" ), equalTo( "default=[queryParam]" ) );
-
-    Locale.setDefault( Locale.CANADA );
-    assertThat( res.testResource( "queryParam" ), equalTo( "ca=[queryParam]" ) );
-
-  }
-
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTestFormattingSubject.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTestFormattingSubject.java b/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTestFormattingSubject.java
deleted file mode 100644
index 0ff337f..0000000
--- a/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTestFormattingSubject.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.hadoop.gateway.i18n.resources;
-
-/**
- *
- */
-@Resources( bundle="some.bundle.name" )
-public interface ResourcesTestFormattingSubject {
-
-  @Resource(text="{0}")
-  String withAnnotationWithSimplePatternOneParam( int x );
-
-  @Resource(text="before{0}after")
-  String withAnnotationWithPatternOneParam( int x );
-
-  @Resource
-  String withAnnotationWithoutPatternOneParam( int x );
-
-  String withoutAnnotationsOrParameters();
-
-  String withoutAnnotationsWithOneParam( int x );
-
-  String withoutAnnotationsWithElevenParams( String p1, String p2, String p3, String p4, String p5, String p6, String p7, String p8, String p9, String p10, String p11 );
-
-  @Resource(text="{0},{1}")
-  String withMoreFormatParamsThanMethodParams( int x );
-
-  @Resource(text="{0}")
-  String withLessFormatParamsThanMethodParams( int x, int y );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject.java b/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject.java
deleted file mode 100644
index 1f4dc6a..0000000
--- a/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTestLocaleSubject.java
+++ /dev/null
@@ -1,29 +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.hadoop.gateway.i18n.resources;
-
-/**
- *
- */
-@Resources
-public interface ResourcesTestLocaleSubject {
-
-  @Resource(text="default=[{0}]")
-  String testResource( String param );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTestNamedSubject.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTestNamedSubject.java b/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTestNamedSubject.java
deleted file mode 100644
index 198786f..0000000
--- a/gateway-i18n/src/test/java/org/apache/hadoop/gateway/i18n/resources/ResourcesTestNamedSubject.java
+++ /dev/null
@@ -1,29 +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.hadoop.gateway.i18n.resources;
-
-/**
- *
- */
-@Resources( bundle="org.apache.hadoop.gateway.i18n.resources.NamedBundle" )
-public interface ResourcesTestNamedSubject {
-
-  @Resource(text="default=[{0}]")
-  String testResource( String param );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/messages/MessagesTest.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/messages/MessagesTest.java b/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/messages/MessagesTest.java
new file mode 100644
index 0000000..d53e99d
--- /dev/null
+++ b/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/messages/MessagesTest.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.knox.gateway.i18n.messages;
+
+import org.apache.knox.gateway.i18n.messages.loggers.test.TestMessageLogger;
+import org.apache.knox.gateway.i18n.messages.loggers.test.TestMessageLoggerFactory;
+import org.apache.knox.gateway.i18n.messages.loggers.test.TestMessageRecord;
+import org.apache.hadoop.test.category.FastTests;
+import org.apache.hadoop.test.category.UnitTests;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+/**
+ *
+ */
+@Category( { UnitTests.class, FastTests.class } )
+public class MessagesTest {
+
+  @Test
+  public void testFirst() {
+    MessagesTestSubject log = MessagesFactory.get( MessagesTestSubject.class );
+
+    log.withFullAnnotationAndParameter( 7 );
+
+    TestMessageLogger logger = (TestMessageLogger)TestMessageLoggerFactory.getFactory().getLogger( "some.logger.name" );
+    assertThat( logger.records.size(), equalTo( 1 ) );
+
+    TestMessageRecord record = logger.records.get( 0 );
+
+    assertThat( record.getCaller().getClassName(), is( this.getClass().getName() ) );
+    assertThat( record.getCaller().getMethodName(), is( "testFirst" ) );
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/messages/MessagesTestSubject.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/messages/MessagesTestSubject.java b/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/messages/MessagesTestSubject.java
new file mode 100644
index 0000000..fdecab5
--- /dev/null
+++ b/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/messages/MessagesTestSubject.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.knox.gateway.i18n.messages;
+
+/**
+ *
+ */
+@Messages( bundle="some.bundle.name", logger="some.logger.name", codes="ID:{0}" )
+public interface MessagesTestSubject {
+
+  @Message(level= MessageLevel.ERROR, code=3, text="p0={0}" )
+  void withFullAnnotationAndParameter( int x );
+
+  @Message(level= MessageLevel.INFO, code=42, text="str={0}, t={1}" )
+  void withEverything( String str, @StackTrace(level= MessageLevel.INFO) Throwable t );
+
+  @Message
+  void withoutParams();
+
+  void withoutAnnotations( int x );
+
+  @Message
+  void withoutStackTrace( Throwable t );
+
+  @Message
+  void withMismatchedText();
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTest.java
----------------------------------------------------------------------
diff --git a/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTest.java b/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTest.java
new file mode 100644
index 0000000..a876b89
--- /dev/null
+++ b/gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTest.java
@@ -0,0 +1,121 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.i18n.resources;
+
+import org.apache.hadoop.test.category.FastTests;
+import org.apache.hadoop.test.category.UnitTests;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import java.util.Locale;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertThat;
+
+/**
+ *
+ */
+@Category( { UnitTests.class, FastTests.class } )
+public class ResourcesTest {
+
+  private Locale locale;
+
+  @Before
+  public void setup() {
+    locale = Locale.getDefault();
+  }
+
+  @After
+  public void cleanup() {
+    Locale.setDefault( locale );
+  }
+
+  @Test
+  public void testResourceFormatting() {
+
+    ResourcesTestFormattingSubject res = ResourcesFactory.get( ResourcesTestFormattingSubject.class );
+
+    assertThat(
+        res.withoutAnnotationsOrParameters(),
+        equalTo( "withoutAnnotationsOrParameters" ) );
+
+    assertThat(
+        res.withAnnotationWithoutPatternOneParam( 42 ),
+        equalTo( "withAnnotationWithoutPatternOneParam(\"42\")" ) );
+
+    assertThat(
+        res.withAnnotationWithPatternOneParam( 72 ),
+        equalTo( "before72after" ) );
+
+    assertThat(
+        res.withAnnotationWithSimplePatternOneParam( 33 ),
+        equalTo( "33" ) );
+
+    assertThat(
+        res.withoutAnnotationsWithElevenParams( "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11" ),
+        equalTo( "withoutAnnotationsWithElevenParams(\"v1\",\"v2\",\"v3\",\"v4\",\"v5\",\"v6\",\"v7\",\"v8\",\"v9\",\"v10\",\"v11\")" ) );
+
+    assertThat(
+        res.withoutAnnotationsWithOneParam( 17 ),
+        equalTo( "withoutAnnotationsWithOneParam(\"17\")" ) );
+
+    assertThat(
+        res.withMoreFormatParamsThanMethodParams( 7 ),
+        equalTo( "7,{1}" ) );
+
+    assertThat(
+        res.withLessFormatParamsThanMethodParams( 7, 11 ),
+        equalTo( "7" ) );
+  }
+
+  @Test
+  public void testResourceLocales() {
+
+    ResourcesTestLocaleSubject res = ResourcesFactory.get( ResourcesTestLocaleSubject.class );
+
+    Locale.setDefault( Locale.CHINESE ); // Change to something that we won't have test bundles for.
+    assertThat( res.testResource( "queryParam" ), equalTo( "default=[queryParam]" ) );
+
+    Locale.setDefault( Locale.ENGLISH );
+    assertThat( res.testResource( "queryParam" ), equalTo( "en=[queryParam]" ) );
+
+    Locale.setDefault( Locale.US );
+    assertThat( res.testResource( "queryParam" ), equalTo( "us=[queryParam]" ) );
+
+    Locale.setDefault( Locale.UK );
+    assertThat( res.testResource( "queryParam" ), equalTo( "uk=[queryParam]" ) );
+
+  }
+
+  @Test
+  public void testNamedBundle() {
+
+    ResourcesTestNamedSubject res = ResourcesFactory.get( ResourcesTestNamedSubject.class );
+
+    Locale.setDefault( Locale.CHINESE ); // Change to something that we won't have test bundles for.
+    assertThat( res.testResource( "queryParam" ), equalTo( "default=[queryParam]" ) );
+
+    Locale.setDefault( Locale.CANADA );
+    assertThat( res.testResource( "queryParam" ), equalTo( "ca=[queryParam]" ) );
+
+  }
+
+
+}


[41/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderMessages.java b/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderMessages.java
deleted file mode 100644
index d67b811..0000000
--- a/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderMessages.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.hadoop.gateway.identityasserter.hadoop.groups.filter;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-import org.apache.hadoop.gateway.i18n.messages.StackTrace;
-
-/**
- * Messages for provider - HadoopGroupProvider
- * 
- * @since 0.11
- */
-
-@Messages(logger="org.apache.hadoop.gateway")
-public interface HadoopGroupProviderMessages {
-
-  @Message( level = MessageLevel.ERROR, text = "Error getting groups for principal {0}" )
-  void errorGettingUserGroups(final String principal , @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-  
-  @Message( level = MessageLevel.INFO, text = "No groups for principal {0} found" )
-  void noGroupsFound(final String principal);
-  
-  @Message( level = MessageLevel.DEBUG, text = "Found groups for principal {0} : {1}" )
-  void groupsFound(final String principal, final String groups );
-  
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributor.java b/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributor.java
new file mode 100644
index 0000000..d04713d
--- /dev/null
+++ b/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributor.java
@@ -0,0 +1,64 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.identityasserter.hadoop.groups.filter;
+
+import org.apache.knox.gateway.identityasserter.common.filter.AbstractIdentityAsserterDeploymentContributor;
+
+/**
+ * A provider deployment contributor for looking up authenticated user groups as
+ * seen by Hadoop implementation.
+ * 
+ * @since 0.11.0
+ */
+
+public class HadoopGroupProviderDeploymentContributor
+    extends AbstractIdentityAsserterDeploymentContributor {
+
+  /**
+   * Name of our <b>identity-assertion</b> provider.
+   */
+  public static final String HADOOP_GROUP_PROVIDER = "HadoopGroupProvider";
+
+  /* create an instance */
+  public HadoopGroupProviderDeploymentContributor() {
+    super();
+  }
+
+  /*
+   * (non-Javadoc)
+   * 
+   * @see
+   * ProviderDeploymentContributor#getName()
+   */
+  @Override
+  public String getName() {
+    return HADOOP_GROUP_PROVIDER;
+  }
+
+  /*
+   * (non-Javadoc)
+   * 
+   * @see org.apache.hadoop.gateway.identityasserter.common.filter.
+   * AbstractIdentityAsserterDeploymentContributor#getFilterClassname()
+   */
+  @Override
+  protected String getFilterClassname() {
+    return HadoopGroupProviderFilter.class.getName();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilter.java b/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilter.java
new file mode 100644
index 0000000..7709f68
--- /dev/null
+++ b/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilter.java
@@ -0,0 +1,121 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.identityasserter.hadoop.groups.filter;
+
+import java.io.IOException;
+import java.util.Enumeration;
+import java.util.List;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.identityasserter.common.filter.CommonIdentityAssertionFilter;
+import org.apache.hadoop.security.GroupMappingServiceProvider;
+import org.apache.hadoop.security.Groups;
+
+/**
+ * A filter that integrates the Hadoop {@link GroupMappingServiceProvider} for
+ * looking up group membership of the authenticated (asserted) identity.
+ * 
+ * @since 0.11.0
+ */
+public class HadoopGroupProviderFilter extends CommonIdentityAssertionFilter {
+
+  /**
+   * Logging
+   */
+  public static HadoopGroupProviderMessages LOG = MessagesFactory
+      .get(HadoopGroupProviderMessages.class);
+
+  /**
+   * Configuration object needed by for hadoop classes
+   */
+  private Configuration hadoopConfig;
+
+  /**
+   * Hadoop Groups implementation.
+   */
+  private Groups hadoopGroups;
+
+  /* create an instance */
+  public HadoopGroupProviderFilter() {
+    super();
+  }
+
+  @Override
+  public void init(final FilterConfig filterConfig) throws ServletException {
+    super.init(filterConfig);
+
+    try {
+      hadoopConfig = new Configuration(false);
+
+      if (filterConfig.getInitParameterNames() != null) {
+
+        for (final Enumeration<String> keys = filterConfig
+            .getInitParameterNames(); keys.hasMoreElements();) {
+
+          final String key = keys.nextElement();
+          hadoopConfig.set(key, filterConfig.getInitParameter(key));
+
+        }
+
+      }
+      hadoopGroups = new Groups(hadoopConfig);
+
+    } catch (final Exception e) {
+      throw new ServletException(e);
+    }
+
+  }
+
+  /**
+   * Query the Hadoop implementation of {@link Groups} to retrieve groups for
+   * provided user.
+   */
+  public String[] mapGroupPrincipals(final String mappedPrincipalName,
+      final Subject subject) {
+    /* return the groups as seen by Hadoop */
+    String[] groups = null;
+    try {
+      final List<String> groupList = hadoopGroups
+          .getGroups(mappedPrincipalName);
+      LOG.groupsFound(mappedPrincipalName, groupList.toString());
+      groups = groupList.toArray(new String[0]);
+
+    } catch (final IOException e) {
+      if (e.toString().contains("No groups found for user")) {
+        /* no groups found move on */
+        LOG.noGroupsFound(mappedPrincipalName);
+      } else {
+        /* Log the error and return empty group */
+        LOG.errorGettingUserGroups(mappedPrincipalName, e);
+      }
+      groups = new String[0];
+    }
+    return groups;
+  }
+
+  public String mapUserPrincipal(final String principalName) {
+    /* return the passed principal */
+    return principalName;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderMessages.java b/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderMessages.java
new file mode 100644
index 0000000..311b00a
--- /dev/null
+++ b/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderMessages.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.knox.gateway.identityasserter.hadoop.groups.filter;
+
+import org.apache.knox.gateway.i18n.messages.Message;
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.Messages;
+import org.apache.knox.gateway.i18n.messages.StackTrace;
+
+/**
+ * Messages for provider - HadoopGroupProvider
+ * 
+ * @since 0.11
+ */
+
+@Messages(logger="org.apache.hadoop.gateway")
+public interface HadoopGroupProviderMessages {
+
+  @Message( level = MessageLevel.ERROR, text = "Error getting groups for principal {0}" )
+  void errorGettingUserGroups(final String principal , @StackTrace( level = MessageLevel.DEBUG ) Exception e );
+  
+  @Message( level = MessageLevel.INFO, text = "No groups for principal {0} found" )
+  void noGroupsFound(final String principal);
+  
+  @Message( level = MessageLevel.DEBUG, text = "Found groups for principal {0} : {1}" )
+  void groupsFound(final String principal, final String groups );
+  
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-hadoop-groups/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-identity-assertion-hadoop-groups/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index 5445ddc..0000000
--- a/gateway-provider-identity-assertion-hadoop-groups/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.identityasserter.hadoop.groups.filter.HadoopGroupProviderDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-hadoop-groups/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-identity-assertion-hadoop-groups/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..2191300
--- /dev/null
+++ b/gateway-provider-identity-assertion-hadoop-groups/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.identityasserter.hadoop.groups.filter.HadoopGroupProviderDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributorTest.java b/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributorTest.java
deleted file mode 100644
index b146b7c..0000000
--- a/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributorTest.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.hadoop.gateway.identityasserter.hadoop.groups.filter;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor;
-import org.junit.Test;
-
-/**
- * Test for {@link HadoopGroupProviderDeploymentContributor}
- * @since 0.11
- */
-public class HadoopGroupProviderDeploymentContributorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    
-    ServiceLoader<ProviderDeploymentContributor> loader = ServiceLoader
-        .load(ProviderDeploymentContributor.class);
-    
-    Iterator<ProviderDeploymentContributor> iterator = loader.iterator();
-    assertThat("Service iterator empty.", iterator.hasNext());
-    while (iterator.hasNext()) {
-      Object object = iterator.next();
-      if (object instanceof HadoopGroupProviderDeploymentContributor) {
-        return;
-      }
-    }
-    fail("Failed to find "
-        + HadoopGroupProviderDeploymentContributor.class.getName()
-        + " via service loader.");
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilterTest.java b/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilterTest.java
deleted file mode 100644
index c8305fa..0000000
--- a/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilterTest.java
+++ /dev/null
@@ -1,218 +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.hadoop.gateway.identityasserter.hadoop.groups.filter;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-import java.security.Principal;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Vector;
-
-import javax.security.auth.Subject;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.apache.hadoop.security.LdapGroupsMapping;
-import org.apache.hadoop.security.ShellBasedUnixGroupsMapping;
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-/**
- * Test for {@link HadoopGroupProviderFilter}
- * 
- * @since 0.11.0
- */
-public class HadoopGroupProviderFilterTest {
-
-  /**
-   * System username
-   */
-  private static final String failUsername = "highly_unlikely_username_to_have";
-
-  /**
-   * System username
-   */
-  private static final String username = System.getProperty("user.name");
-
-  /**
-   * Configuration object needed by for hadoop classes
-   */
-
-  /**
-   * Hadoop Groups implementation.
-   */
-
-  /* create an instance */
-  public HadoopGroupProviderFilterTest() {
-    super();
-  }
-
-  /**
-   * Test that valid groups are retrieved for a legitimate user.
-   * 
-   * @throws ServletException
-   */
-  @Test
-  public void testGroups() throws ServletException {
-
-    final FilterConfig config = EasyMock.createNiceMock(FilterConfig.class);
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    final HadoopGroupProviderFilter filter = new HadoopGroupProviderFilter();
-
-    final Subject subject = new Subject();
-    subject.getPrincipals().add(new PrimaryPrincipal(username));
-
-    filter.init(config);
-    final String principal = filter.mapUserPrincipal(
-        ((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0])
-            .getName());
-    final String[] groups = filter.mapGroupPrincipals(principal, subject);
-
-    assertThat(principal, is(username));
-    assertThat(
-        "No groups assosciated with the user, most likely this is a failure, it is only OK when 'bash -c groups' command returns 0 groups. ",
-        groups.length > 0);
-
-  }
-
-  /**
-   * Test that no groups are retrieved for a dummy user.
-   * 
-   * @throws ServletException
-   */
-  @Test
-  public void testUnknownUser() throws ServletException {
-
-    final FilterConfig config = EasyMock.createNiceMock(FilterConfig.class);
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    final HadoopGroupProviderFilter filter = new HadoopGroupProviderFilter();
-
-    final Subject subject = new Subject();
-    subject.getPrincipals().add(new PrimaryPrincipal(failUsername));
-
-    filter.init(config);
-    final String principal = filter.mapUserPrincipal(
-        ((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0])
-            .getName());
-    final String[] groups = filter.mapGroupPrincipals(principal, subject);
-
-    assertThat(principal, is(failUsername));
-    assertThat(
-        "Somehow groups were found for this user, how is it possible ! check 'bash -c groups' command ",
-        groups.length == 0);
-
-  }
-
-  /**
-   * Test for a bad config (nonexistent). This test proves, we are not falling
-   * back on {@link ShellBasedUnixGroupsMapping} because we explicitly use
-   * {@link LdapGroupsMapping} and in case of bad config we get empty groups
-   * (Hadoop way).
-   * 
-   * @throws ServletException
-   */
-  @SuppressWarnings({ "unchecked", "rawtypes" })
-  @Test
-  public void badConfigTest() throws ServletException {
-
-    final List<String> keysList = Arrays.asList("hadoop.security.group.mapping",
-        "hadoop.security.group.mapping.ldap.bind.user",
-        "hadoop.security.group.mapping.ldap.bind.password",
-        "hadoop.security.group.mapping.ldap.url",
-        "hadoop.security.group.mapping.ldap.search.filter.group",
-        "hadoop.security.group.mapping.ldap.search.attr.member",
-        "hadoop.security.group.mapping.ldap.search.filter.user");
-
-    final FilterConfig config = EasyMock.createNiceMock(FilterConfig.class);
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-
-    EasyMock.expect(config.getInitParameter("hadoop.security.group.mapping"))
-        .andReturn("org.apache.hadoop.security.LdapGroupsMapping").anyTimes();
-    EasyMock
-        .expect(config
-            .getInitParameter("hadoop.security.group.mapping.ldap.bind.user"))
-        .andReturn("uid=dummy,ou=people,dc=hadoop,dc=apache,dc=org").anyTimes();
-    EasyMock
-        .expect(config.getInitParameter(
-            "hadoop.security.group.mapping.ldap.bind.password"))
-        .andReturn("unbind-me-please").anyTimes();
-    EasyMock
-        .expect(
-            config.getInitParameter("hadoop.security.group.mapping.ldap.url"))
-        .andReturn("ldap://nomansland:33389").anyTimes();
-    EasyMock
-        .expect(config.getInitParameter(
-            "hadoop.security.group.mapping.ldap.search.filter.group"))
-        .andReturn("(objectclass=groupOfNames)").anyTimes();
-    EasyMock
-        .expect(config.getInitParameter(
-            "hadoop.security.group.mapping.ldap.search.attr.member"))
-        .andReturn("member").anyTimes();
-    EasyMock
-        .expect(config.getInitParameter(
-            "hadoop.security.group.mapping.ldap.search.filter.user"))
-        .andReturn(
-            "(&amp;(|(objectclass=person)(objectclass=applicationProcess))(cn={0}))")
-        .anyTimes();
-    EasyMock.expect(config.getInitParameterNames())
-        .andReturn(new Vector(keysList).elements()).anyTimes();
-
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    final HadoopGroupProviderFilter filter = new HadoopGroupProviderFilter();
-
-    final Subject subject = new Subject();
-    subject.getPrincipals().add(new PrimaryPrincipal(username));
-
-    filter.init(config);
-    final String principal = filter.mapUserPrincipal(
-        ((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0])
-            .getName());
-    final String[] groups = filter.mapGroupPrincipals(principal, subject);
-
-    assertThat(principal, is(username));
-
-    /*
-     * Unfortunately, Hadoop does not let us know what went wrong all we get is
-     * empty groups
-     */
-    assertThat(groups.length, is(0));
-
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupsTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupsTest.java b/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupsTest.java
deleted file mode 100644
index fee2438..0000000
--- a/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/hadoop/gateway/identityasserter/hadoop/groups/filter/HadoopGroupsTest.java
+++ /dev/null
@@ -1,85 +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.hadoop.gateway.identityasserter.hadoop.groups.filter;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-
-import java.util.List;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.security.Groups;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * Test Hadoop {@link Groups} class. Basically to make sure that the
- * interface we depend on does not change.
- * 
- * @since 0.11.0
- */
-public class HadoopGroupsTest {
-
-  /**
-   * Use the default group mapping
-   */
-  public static final String GROUP_MAPPING = "org.apache.hadoop.security.JniBasedUnixGroupsMappingWithFallback";
-
-  /**
-   * Username
-   */
-  private String username;
-
-  /**
-   * Configuration object needed by for hadoop classes
-   */
-  private Configuration hadoopConfig;
-
-  /**
-   * Hadoop Groups implementation.
-   */
-  private Groups hadoopGroups;
-
-  /* create instance */
-  public HadoopGroupsTest() {
-    super();
-  }
-
-  @Before
-  public void init() {
-    username = System.getProperty("user.name");
-
-    hadoopConfig = new Configuration(false);
-
-    hadoopConfig.set("hadoop.security.group.mapping", GROUP_MAPPING);
-
-    hadoopGroups = new Groups(hadoopConfig);
-
-  }
-
-  /**
-   * Test Groups on the machine running the unit test.
-   */
-  @Test
-  public void testLocalGroups() throws Exception {
-
-    final List<String> groupList = hadoopGroups.getGroups(username);
-
-    assertThat("No groups found for user " + username, !groupList.isEmpty());
-
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributorTest.java b/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributorTest.java
new file mode 100644
index 0000000..ce86f02
--- /dev/null
+++ b/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributorTest.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.knox.gateway.identityasserter.hadoop.groups.filter;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributor;
+import org.junit.Test;
+
+/**
+ * Test for {@link HadoopGroupProviderDeploymentContributor}
+ * @since 0.11
+ */
+public class HadoopGroupProviderDeploymentContributorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    
+    ServiceLoader<ProviderDeploymentContributor> loader = ServiceLoader
+        .load(ProviderDeploymentContributor.class);
+    
+    Iterator<ProviderDeploymentContributor> iterator = loader.iterator();
+    assertThat("Service iterator empty.", iterator.hasNext());
+    while (iterator.hasNext()) {
+      Object object = iterator.next();
+      if (object instanceof HadoopGroupProviderDeploymentContributor) {
+        return;
+      }
+    }
+    fail("Failed to find "
+        + HadoopGroupProviderDeploymentContributor.class.getName()
+        + " via service loader.");
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilterTest.java b/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilterTest.java
new file mode 100644
index 0000000..d5f5501
--- /dev/null
+++ b/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilterTest.java
@@ -0,0 +1,218 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.identityasserter.hadoop.groups.filter;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import java.security.Principal;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Vector;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.apache.hadoop.security.LdapGroupsMapping;
+import org.apache.hadoop.security.ShellBasedUnixGroupsMapping;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+/**
+ * Test for {@link HadoopGroupProviderFilter}
+ * 
+ * @since 0.11.0
+ */
+public class HadoopGroupProviderFilterTest {
+
+  /**
+   * System username
+   */
+  private static final String failUsername = "highly_unlikely_username_to_have";
+
+  /**
+   * System username
+   */
+  private static final String username = System.getProperty("user.name");
+
+  /**
+   * Configuration object needed by for hadoop classes
+   */
+
+  /**
+   * Hadoop Groups implementation.
+   */
+
+  /* create an instance */
+  public HadoopGroupProviderFilterTest() {
+    super();
+  }
+
+  /**
+   * Test that valid groups are retrieved for a legitimate user.
+   * 
+   * @throws ServletException
+   */
+  @Test
+  public void testGroups() throws ServletException {
+
+    final FilterConfig config = EasyMock.createNiceMock(FilterConfig.class);
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    final HadoopGroupProviderFilter filter = new HadoopGroupProviderFilter();
+
+    final Subject subject = new Subject();
+    subject.getPrincipals().add(new PrimaryPrincipal(username));
+
+    filter.init(config);
+    final String principal = filter.mapUserPrincipal(
+        ((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0])
+            .getName());
+    final String[] groups = filter.mapGroupPrincipals(principal, subject);
+
+    assertThat(principal, is(username));
+    assertThat(
+        "No groups assosciated with the user, most likely this is a failure, it is only OK when 'bash -c groups' command returns 0 groups. ",
+        groups.length > 0);
+
+  }
+
+  /**
+   * Test that no groups are retrieved for a dummy user.
+   * 
+   * @throws ServletException
+   */
+  @Test
+  public void testUnknownUser() throws ServletException {
+
+    final FilterConfig config = EasyMock.createNiceMock(FilterConfig.class);
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    final HadoopGroupProviderFilter filter = new HadoopGroupProviderFilter();
+
+    final Subject subject = new Subject();
+    subject.getPrincipals().add(new PrimaryPrincipal(failUsername));
+
+    filter.init(config);
+    final String principal = filter.mapUserPrincipal(
+        ((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0])
+            .getName());
+    final String[] groups = filter.mapGroupPrincipals(principal, subject);
+
+    assertThat(principal, is(failUsername));
+    assertThat(
+        "Somehow groups were found for this user, how is it possible ! check 'bash -c groups' command ",
+        groups.length == 0);
+
+  }
+
+  /**
+   * Test for a bad config (nonexistent). This test proves, we are not falling
+   * back on {@link ShellBasedUnixGroupsMapping} because we explicitly use
+   * {@link LdapGroupsMapping} and in case of bad config we get empty groups
+   * (Hadoop way).
+   * 
+   * @throws ServletException
+   */
+  @SuppressWarnings({ "unchecked", "rawtypes" })
+  @Test
+  public void badConfigTest() throws ServletException {
+
+    final List<String> keysList = Arrays.asList("hadoop.security.group.mapping",
+        "hadoop.security.group.mapping.ldap.bind.user",
+        "hadoop.security.group.mapping.ldap.bind.password",
+        "hadoop.security.group.mapping.ldap.url",
+        "hadoop.security.group.mapping.ldap.search.filter.group",
+        "hadoop.security.group.mapping.ldap.search.attr.member",
+        "hadoop.security.group.mapping.ldap.search.filter.user");
+
+    final FilterConfig config = EasyMock.createNiceMock(FilterConfig.class);
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+
+    EasyMock.expect(config.getInitParameter("hadoop.security.group.mapping"))
+        .andReturn("org.apache.hadoop.security.LdapGroupsMapping").anyTimes();
+    EasyMock
+        .expect(config
+            .getInitParameter("hadoop.security.group.mapping.ldap.bind.user"))
+        .andReturn("uid=dummy,ou=people,dc=hadoop,dc=apache,dc=org").anyTimes();
+    EasyMock
+        .expect(config.getInitParameter(
+            "hadoop.security.group.mapping.ldap.bind.password"))
+        .andReturn("unbind-me-please").anyTimes();
+    EasyMock
+        .expect(
+            config.getInitParameter("hadoop.security.group.mapping.ldap.url"))
+        .andReturn("ldap://nomansland:33389").anyTimes();
+    EasyMock
+        .expect(config.getInitParameter(
+            "hadoop.security.group.mapping.ldap.search.filter.group"))
+        .andReturn("(objectclass=groupOfNames)").anyTimes();
+    EasyMock
+        .expect(config.getInitParameter(
+            "hadoop.security.group.mapping.ldap.search.attr.member"))
+        .andReturn("member").anyTimes();
+    EasyMock
+        .expect(config.getInitParameter(
+            "hadoop.security.group.mapping.ldap.search.filter.user"))
+        .andReturn(
+            "(&amp;(|(objectclass=person)(objectclass=applicationProcess))(cn={0}))")
+        .anyTimes();
+    EasyMock.expect(config.getInitParameterNames())
+        .andReturn(new Vector(keysList).elements()).anyTimes();
+
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    final HadoopGroupProviderFilter filter = new HadoopGroupProviderFilter();
+
+    final Subject subject = new Subject();
+    subject.getPrincipals().add(new PrimaryPrincipal(username));
+
+    filter.init(config);
+    final String principal = filter.mapUserPrincipal(
+        ((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0])
+            .getName());
+    final String[] groups = filter.mapGroupPrincipals(principal, subject);
+
+    assertThat(principal, is(username));
+
+    /*
+     * Unfortunately, Hadoop does not let us know what went wrong all we get is
+     * empty groups
+     */
+    assertThat(groups.length, is(0));
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupsTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupsTest.java b/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupsTest.java
new file mode 100644
index 0000000..fa5e48c
--- /dev/null
+++ b/gateway-provider-identity-assertion-hadoop-groups/src/test/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupsTest.java
@@ -0,0 +1,85 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.identityasserter.hadoop.groups.filter;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import java.util.List;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.security.Groups;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Test Hadoop {@link Groups} class. Basically to make sure that the
+ * interface we depend on does not change.
+ * 
+ * @since 0.11.0
+ */
+public class HadoopGroupsTest {
+
+  /**
+   * Use the default group mapping
+   */
+  public static final String GROUP_MAPPING = "org.apache.hadoop.security.JniBasedUnixGroupsMappingWithFallback";
+
+  /**
+   * Username
+   */
+  private String username;
+
+  /**
+   * Configuration object needed by for hadoop classes
+   */
+  private Configuration hadoopConfig;
+
+  /**
+   * Hadoop Groups implementation.
+   */
+  private Groups hadoopGroups;
+
+  /* create instance */
+  public HadoopGroupsTest() {
+    super();
+  }
+
+  @Before
+  public void init() {
+    username = System.getProperty("user.name");
+
+    hadoopConfig = new Configuration(false);
+
+    hadoopConfig.set("hadoop.security.group.mapping", GROUP_MAPPING);
+
+    hadoopGroups = new Groups(hadoopConfig);
+
+  }
+
+  /**
+   * Test Groups on the machine running the unit test.
+   */
+  @Test
+  public void testLocalGroups() throws Exception {
+
+    final List<String> groupList = hadoopGroups.getGroups(username);
+
+    assertThat("No groups found for user " + username, !groupList.isEmpty());
+
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/IdentityAsserterMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/IdentityAsserterMessages.java b/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/IdentityAsserterMessages.java
deleted file mode 100644
index c4ada6b..0000000
--- a/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/IdentityAsserterMessages.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-import org.apache.hadoop.gateway.i18n.messages.StackTrace;
-
-@Messages(logger="org.apache.hadoop.gateway")
-public interface IdentityAsserterMessages {
-
-  @Message( level = MessageLevel.WARN, text = "Skipping unencodable parameter {0}={1}, {2}: {3}" )
-  void skippingUnencodableParameter( String name, String value, String encoding, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/identityasserter/filter/DefaultIdentityAsserterDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/identityasserter/filter/DefaultIdentityAsserterDeploymentContributor.java b/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/identityasserter/filter/DefaultIdentityAsserterDeploymentContributor.java
deleted file mode 100644
index bd4343e..0000000
--- a/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/identityasserter/filter/DefaultIdentityAsserterDeploymentContributor.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.hadoop.gateway.identityasserter.filter;
-
-/**
- * This class renames the Pseudo identity asserter to Default
- * while still providing backward compatibility.
- */
-public class DefaultIdentityAsserterDeploymentContributor extends
-    IdentityAsserterDeploymentContributor {
-
-  @Override
-  public String getName() {
-    return "Default";
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/identityasserter/filter/IdentityAsserterDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/identityasserter/filter/IdentityAsserterDeploymentContributor.java b/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/identityasserter/filter/IdentityAsserterDeploymentContributor.java
deleted file mode 100644
index b261138..0000000
--- a/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/identityasserter/filter/IdentityAsserterDeploymentContributor.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.hadoop.gateway.identityasserter.filter;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.identityasserter.common.filter.AbstractIdentityAsserterDeploymentContributor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-import java.util.List;
-
-public class IdentityAsserterDeploymentContributor extends AbstractIdentityAsserterDeploymentContributor {
-
-  private static final String FILTER_CLASSNAME = IdentityAsserterFilter.class.getName();
-  private static final String PRINCIPAL_MAPPING_PARAM_NAME = "principal.mapping";
-  private static final String GROUP_PRINCIPAL_MAPPING_PARAM_NAME = "group.principal.mapping";
-
-  @Override
-  public String getName() {
-    return "Pseudo";
-  }
-
-  @Override
-  public void contributeProvider( DeploymentContext context, Provider provider ) {
-    super.contributeProvider(context, provider);
-    String mappings = provider.getParams().get(PRINCIPAL_MAPPING_PARAM_NAME);
-    String groupMappings = provider.getParams().get(GROUP_PRINCIPAL_MAPPING_PARAM_NAME);
-
-    context.getWebAppDescriptor().createContextParam().paramName(PRINCIPAL_MAPPING_PARAM_NAME).paramValue(mappings);
-    context.getWebAppDescriptor().createContextParam().paramName(GROUP_PRINCIPAL_MAPPING_PARAM_NAME).paramValue(groupMappings);
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.identityasserter.common.filter.AbstractIdentityAsserterDeploymentContributor#getFilterClassname()
-   */
-  @Override
-  protected String getFilterClassname() {
-    return FILTER_CLASSNAME;
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/identityasserter/filter/IdentityAsserterFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/identityasserter/filter/IdentityAsserterFilter.java b/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/identityasserter/filter/IdentityAsserterFilter.java
deleted file mode 100644
index 8f82481..0000000
--- a/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/hadoop/gateway/identityasserter/filter/IdentityAsserterFilter.java
+++ /dev/null
@@ -1,42 +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.hadoop.gateway.identityasserter.filter;
-
-
-import javax.security.auth.Subject;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import org.apache.hadoop.gateway.identityasserter.common.filter.CommonIdentityAssertionFilter;
-
-public class IdentityAsserterFilter extends CommonIdentityAssertionFilter {
-
-  @Override
-  public void init(FilterConfig filterConfig) throws ServletException {
-    super.init(filterConfig);
-  }
-
-  @Override
-  public String[] mapGroupPrincipals(String mappedPrincipalName, Subject subject) {
-    return mapGroupPrincipalsBase(mappedPrincipalName, subject);
-  }
-
-  @Override
-  public String mapUserPrincipal(String principalName) {
-    return mapUserPrincipalBase(principalName);
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java b/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java
new file mode 100644
index 0000000..e614c25
--- /dev/null
+++ b/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway;
+
+import org.apache.knox.gateway.i18n.messages.Message;
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.Messages;
+import org.apache.knox.gateway.i18n.messages.StackTrace;
+
+@Messages(logger="org.apache.hadoop.gateway")
+public interface IdentityAsserterMessages {
+
+  @Message( level = MessageLevel.WARN, text = "Skipping unencodable parameter {0}={1}, {2}: {3}" )
+  void skippingUnencodableParameter( String name, String value, String encoding, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/identityasserter/filter/DefaultIdentityAsserterDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/identityasserter/filter/DefaultIdentityAsserterDeploymentContributor.java b/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/identityasserter/filter/DefaultIdentityAsserterDeploymentContributor.java
new file mode 100644
index 0000000..44299a4
--- /dev/null
+++ b/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/identityasserter/filter/DefaultIdentityAsserterDeploymentContributor.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.knox.gateway.identityasserter.filter;
+
+/**
+ * This class renames the Pseudo identity asserter to Default
+ * while still providing backward compatibility.
+ */
+public class DefaultIdentityAsserterDeploymentContributor extends
+    IdentityAsserterDeploymentContributor {
+
+  @Override
+  public String getName() {
+    return "Default";
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/identityasserter/filter/IdentityAsserterDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/identityasserter/filter/IdentityAsserterDeploymentContributor.java b/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/identityasserter/filter/IdentityAsserterDeploymentContributor.java
new file mode 100644
index 0000000..49993b4
--- /dev/null
+++ b/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/identityasserter/filter/IdentityAsserterDeploymentContributor.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.knox.gateway.identityasserter.filter;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.identityasserter.common.filter.AbstractIdentityAsserterDeploymentContributor;
+import org.apache.knox.gateway.topology.Provider;
+
+public class IdentityAsserterDeploymentContributor extends AbstractIdentityAsserterDeploymentContributor {
+
+  private static final String FILTER_CLASSNAME = IdentityAsserterFilter.class.getName();
+  private static final String PRINCIPAL_MAPPING_PARAM_NAME = "principal.mapping";
+  private static final String GROUP_PRINCIPAL_MAPPING_PARAM_NAME = "group.principal.mapping";
+
+  @Override
+  public String getName() {
+    return "Pseudo";
+  }
+
+  @Override
+  public void contributeProvider( DeploymentContext context, Provider provider ) {
+    super.contributeProvider(context, provider);
+    String mappings = provider.getParams().get(PRINCIPAL_MAPPING_PARAM_NAME);
+    String groupMappings = provider.getParams().get(GROUP_PRINCIPAL_MAPPING_PARAM_NAME);
+
+    context.getWebAppDescriptor().createContextParam().paramName(PRINCIPAL_MAPPING_PARAM_NAME).paramValue(mappings);
+    context.getWebAppDescriptor().createContextParam().paramName(GROUP_PRINCIPAL_MAPPING_PARAM_NAME).paramValue(groupMappings);
+  }
+
+  /* (non-Javadoc)
+   * @see AbstractIdentityAsserterDeploymentContributor#getFilterClassname()
+   */
+  @Override
+  protected String getFilterClassname() {
+    return FILTER_CLASSNAME;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/identityasserter/filter/IdentityAsserterFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/identityasserter/filter/IdentityAsserterFilter.java b/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/identityasserter/filter/IdentityAsserterFilter.java
new file mode 100644
index 0000000..18cec8f
--- /dev/null
+++ b/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/identityasserter/filter/IdentityAsserterFilter.java
@@ -0,0 +1,42 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.identityasserter.filter;
+
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import org.apache.knox.gateway.identityasserter.common.filter.CommonIdentityAssertionFilter;
+
+public class IdentityAsserterFilter extends CommonIdentityAssertionFilter {
+
+  @Override
+  public void init(FilterConfig filterConfig) throws ServletException {
+    super.init(filterConfig);
+  }
+
+  @Override
+  public String[] mapGroupPrincipals(String mappedPrincipalName, Subject subject) {
+    return mapGroupPrincipalsBase(mappedPrincipalName, subject);
+  }
+
+  @Override
+  public String mapUserPrincipal(String principalName) {
+    return mapUserPrincipalBase(principalName);
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-pseudo/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-pseudo/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-identity-assertion-pseudo/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index d5b3601..0000000
--- a/gateway-provider-identity-assertion-pseudo/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,20 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.identityasserter.filter.IdentityAsserterDeploymentContributor
-org.apache.hadoop.gateway.identityasserter.filter.DefaultIdentityAsserterDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-pseudo/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-pseudo/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-identity-assertion-pseudo/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..e825a77
--- /dev/null
+++ b/gateway-provider-identity-assertion-pseudo/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,20 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.identityasserter.filter.IdentityAsserterDeploymentContributor
+org.apache.knox.gateway.identityasserter.filter.DefaultIdentityAsserterDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-pseudo/src/test/java/org/apache/hadoop/gateway/identityasserter/filter/DefaultIdentityAssertionFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-pseudo/src/test/java/org/apache/hadoop/gateway/identityasserter/filter/DefaultIdentityAssertionFilterTest.java b/gateway-provider-identity-assertion-pseudo/src/test/java/org/apache/hadoop/gateway/identityasserter/filter/DefaultIdentityAssertionFilterTest.java
deleted file mode 100644
index 9795a99..0000000
--- a/gateway-provider-identity-assertion-pseudo/src/test/java/org/apache/hadoop/gateway/identityasserter/filter/DefaultIdentityAssertionFilterTest.java
+++ /dev/null
@@ -1,173 +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.hadoop.gateway.identityasserter.filter;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.security.Principal;
-
-import javax.security.auth.Subject;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-
-import org.apache.hadoop.gateway.security.GroupPrincipal;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-/**
- *
- */
-public class DefaultIdentityAssertionFilterTest {
-
-  @Test
-  public void testInitParameters() throws Exception {
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    IdentityAsserterFilter filter = new IdentityAsserterFilter();
-    Subject subject = new Subject();
-    
-    subject.getPrincipals().add(new PrimaryPrincipal("lmccay"));
-    subject.getPrincipals().add(new GroupPrincipal("users"));
-    subject.getPrincipals().add(new GroupPrincipal("admin"));
-    
-    filter.init(config);
-    String username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    String[] groups = filter.mapGroupPrincipals(username, subject);
-    assertEquals("lmccay", username);
-    assertNull(groups); // means for the caller to use the existing subject groups
-    
-    config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "lmccay,kminder=hdfs;newuser=mapred" ).anyTimes();
-    EasyMock.expect(config.getInitParameter("group.principal.mapping") ).andReturn( "kminder=group1;lmccay=mrgroup,mrducks" ).anyTimes();
-    context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.replay( config );
-    filter.init(config);
-    username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    String[] mappedGroups = filter.mapGroupPrincipals(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName(), subject);
-    assertEquals("hdfs", username);
-    assertTrue("mrgroup not found in groups: " + mappedGroups, groupFoundIn("mrgroup", mappedGroups));
-    assertTrue("mrducks not found in groups: " + mappedGroups, groupFoundIn("mrducks", mappedGroups));
-    assertFalse("group1 WAS found in groups: " + mappedGroups, groupFoundIn("group1", mappedGroups));
-
-    subject = new Subject();
-    
-    subject.getPrincipals().add(new PrimaryPrincipal("kminder"));
-    subject.getPrincipals().add(new GroupPrincipal("users"));
-    subject.getPrincipals().add(new GroupPrincipal("admin"));
-    
-    config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "lmccay,kminder=hdfs;newuser=mapred" ).anyTimes();
-    EasyMock.expect(config.getInitParameter("group.principal.mapping") ).andReturn( "kminder=group1;lmccay=mrgroup,mrducks" ).anyTimes();
-    context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.replay( config );
-    filter.init(config);
-    username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    mappedGroups = filter.mapGroupPrincipals(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName(), subject);
-    assertEquals("hdfs", username);
-    assertTrue("group1 not found in groups: " + mappedGroups, groupFoundIn("group1", mappedGroups));
-  }
-
-  /**
-   * @param string
-   * @return
-   */
-  private boolean groupFoundIn(String expected, String[] mappedGroups) {
-    if (mappedGroups == null) return false;
-    for(int i = 0; i < mappedGroups.length; i++) {
-      if (mappedGroups[i].equals(expected)) {
-        return true;
-      }
-    }
-    return false;
-  }
-
-  @Test
-  public void testContextParameters() throws Exception {
-    // for backward compatibility of old deployment contributor's method
-    // of adding init params to the servlet context instead of to the filter.
-    // There is the possibility that previously deployed topologies will have
-    // init params in web.xml at the context level instead of the filter level.
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    IdentityAsserterFilter filter = new IdentityAsserterFilter();
-    Subject subject = new Subject();
-    
-    subject.getPrincipals().add(new PrimaryPrincipal("lmccay"));
-    subject.getPrincipals().add(new GroupPrincipal("users"));
-    subject.getPrincipals().add(new GroupPrincipal("admin"));
-    
-    filter.init(config);
-    String username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    String[] groups = filter.mapGroupPrincipals(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName(), subject);
-//    String[] groups = filter.mapGroupPrincipals(username, subject);
-    assertEquals("lmccay", username);
-    assertNull(groups); // means for the caller to use the existing subject groups
-    
-    config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "lmccay,kminder=hdfs;newuser=mapred" ).anyTimes();
-    EasyMock.expect(context.getInitParameter("group.principal.mapping") ).andReturn( "kminder=group1;lmccay=mrgroup,mrducks" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-    filter.init(config);
-    username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    groups = filter.mapGroupPrincipals(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName(), subject);
-    assertEquals("hdfs", username);
-    assertTrue("mrgroup not found in groups: " + groups, groupFoundIn("mrgroup", groups));
-    assertTrue("mrducks not found in groups: " + groups, groupFoundIn("mrducks", groups));
-    assertFalse("group1 WAS found in groups: " + groups, groupFoundIn("group1", groups));
-
-    subject = new Subject();
-    
-    subject.getPrincipals().add(new PrimaryPrincipal("kminder"));
-    subject.getPrincipals().add(new GroupPrincipal("users"));
-    subject.getPrincipals().add(new GroupPrincipal("admin"));
-    
-    config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "lmccay,kminder=hdfs;newuser=mapred" ).anyTimes();
-    EasyMock.expect(context.getInitParameter("group.principal.mapping") ).andReturn( "kminder=group1;lmccay=mrgroup,mrducks" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-    filter.init(config);
-    username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    assertEquals("hdfs", username);
-  }
-
-}


[03/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/TestFilterChain.java
----------------------------------------------------------------------
diff --git a/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/TestFilterChain.java b/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/TestFilterChain.java
deleted file mode 100644
index 1ab8e22..0000000
--- a/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/TestFilterChain.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.hadoop.gateway.filter;
-
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import java.io.IOException;
-import java.util.Stack;
-
-public class TestFilterChain extends Stack<Filter> implements FilterChain {
-  @Override
-  public void doFilter( ServletRequest request, ServletResponse response ) throws IOException, ServletException {
-    if( !isEmpty() ) pop().doFilter( request, response, this );
-  }
-}
-
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/XForwardHeaderFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/XForwardHeaderFilterTest.java b/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/XForwardHeaderFilterTest.java
deleted file mode 100644
index d1d1a99..0000000
--- a/gateway-server-xforwarded-filter/src/test/java/org/apache/hadoop/gateway/filter/XForwardHeaderFilterTest.java
+++ /dev/null
@@ -1,108 +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.hadoop.gateway.filter;
-
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-public class XForwardHeaderFilterTest {
-
-  public static class AssertXForwardedHeaders extends TestFilterAdapter {
-    @Override
-    public void doFilter( HttpServletRequest request, HttpServletResponse response, FilterChain chain ) throws IOException, ServletException {
-      assertThat( request.getHeader( "X-Forwarded-For" ), is( "127.0.0.1" ) );
-      assertThat( request.getHeader( "X-Forwarded-Proto" ), is( "http" ) );
-      assertThat( request.getHeader( "X-Forwarded-Port" ), is( "8888" ) );
-      assertThat( request.getHeader( "X-Forwarded-Host" ), is( "localhost:8888" ) );
-      assertThat( request.getHeader( "X-Forwarded-Server" ), is( "localhost" ) );
-      assertThat( request.getHeader( "X-Forwarded-Context" ), is( "/context" ) );
-    }
-  }
-
-  @Test
-  public void testXForwardHeaders() throws ServletException, IOException {
-    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
-    EasyMock.expect( request.getRemoteAddr() ).andReturn( "127.0.0.1" ).anyTimes();
-    EasyMock.expect( request.isSecure() ).andReturn( false ).anyTimes();
-    EasyMock.expect( request.getLocalPort() ).andReturn( 8888 ).anyTimes();
-    EasyMock.expect( request.getHeader( "Host" ) ).andReturn( "localhost:8888" ).anyTimes();
-    EasyMock.expect( request.getServerName() ).andReturn( "localhost" ).anyTimes();
-    EasyMock.expect( request.getContextPath() ).andReturn( "/context" ).anyTimes();
-    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
-    EasyMock.replay( request, response );
-
-    TestFilterChain chain = new TestFilterChain();
-
-    XForwardedHeaderFilter filter = new XForwardedHeaderFilter();
-
-    chain.push( new AssertXForwardedHeaders() );
-    chain.push( filter );
-    chain.doFilter( request, response );
-  }
-
-  public static class AssertProxiedXForwardedHeaders extends TestFilterAdapter {
-    @Override
-    public void doFilter( HttpServletRequest request, HttpServletResponse response, FilterChain chain ) throws IOException, ServletException {
-      assertThat( request.getHeader( "X-Forwarded-For" ), is( "127.0.0.0,127.0.0.1" ) );
-      assertThat( request.getHeader( "X-Forwarded-Proto" ), is( "https" ) );
-      assertThat( request.getHeader( "X-Forwarded-Port" ), is( "9999" ) );
-      assertThat( request.getHeader( "X-Forwarded-Host" ), is( "remotehost:9999" ) );
-      assertThat( request.getHeader( "X-Forwarded-Server" ), is( "localhost" ) );
-      assertThat( request.getHeader( "X-Forwarded-Context" ), is( "/upstream/context" ) );
-    }
-  }
-
-  @Test
-  public void testProxiedXForwardHeaders() throws ServletException, IOException {
-    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
-
-    EasyMock.expect( request.getHeader( "X-Forwarded-For" ) ).andReturn( "127.0.0.0" ).anyTimes();
-    EasyMock.expect( request.getHeader( "X-Forwarded-Proto" ) ).andReturn( "https" ).anyTimes();
-    EasyMock.expect( request.getHeader( "X-Forwarded-Port" ) ).andReturn( "9999" ).anyTimes();
-    EasyMock.expect( request.getHeader( "X-Forwarded-Host" ) ).andReturn( "remotehost:9999" ).anyTimes();
-    EasyMock.expect( request.getHeader( "X-Forwarded-Server" ) ).andReturn( "remotehost" ).anyTimes();
-    EasyMock.expect( request.getHeader( "X-Forwarded-Context" ) ).andReturn( "/upstream" ).anyTimes();
-
-    EasyMock.expect( request.getRemoteAddr() ).andReturn( "127.0.0.1" ).anyTimes();
-    EasyMock.expect( request.isSecure() ).andReturn( false ).anyTimes();
-    EasyMock.expect( request.getLocalPort() ).andReturn( 8888 ).anyTimes();
-    EasyMock.expect( request.getHeader( "Host" ) ).andReturn( "localhost:8888" ).anyTimes();
-    EasyMock.expect( request.getServerName() ).andReturn( "localhost" ).anyTimes();
-    EasyMock.expect( request.getContextPath() ).andReturn( "/context" ).anyTimes();
-
-    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
-    EasyMock.replay( request, response );
-
-    TestFilterChain chain = new TestFilterChain();
-
-    XForwardedHeaderFilter filter = new XForwardedHeaderFilter();
-
-    chain.push( new AssertProxiedXForwardedHeaders() );
-    chain.push( filter );
-    chain.doFilter( request, response );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/CompositeEnumerationTest.java
----------------------------------------------------------------------
diff --git a/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/CompositeEnumerationTest.java b/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/CompositeEnumerationTest.java
new file mode 100644
index 0000000..25e9d5e
--- /dev/null
+++ b/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/CompositeEnumerationTest.java
@@ -0,0 +1,117 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter;
+
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.NoSuchElementException;
+
+import static junit.framework.TestCase.fail;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public class CompositeEnumerationTest {
+
+  @Test
+  public void testBasics() {
+
+    String[] a = new String[]{ "1", "2" };
+    Enumeration<String> ea = Collections.enumeration( Arrays.asList( a ) );
+
+    String[] b = new String[]{ "3", "4" };
+    Enumeration<String> eb = Collections.enumeration( Arrays.asList( b ) );
+
+    CompositeEnumeration<String> ce = new CompositeEnumeration<String>( ea, eb );
+
+    assertThat( ce.nextElement(), is( "1" ) );
+    assertThat( ce.nextElement(), is( "2" ) );
+    assertThat( ce.nextElement(), is( "3" ) );
+    assertThat( ce.nextElement(), is( "4" ) );
+    assertThat( ce.hasMoreElements(), is( false ) );
+
+  }
+
+  @Test
+  public void testSingleValues() {
+    String[] a = new String[]{ "1" };
+    Enumeration<String> ea = Collections.enumeration( Arrays.asList( a ) );
+
+    String[] b = new String[]{ "2" };
+    Enumeration<String> eb = Collections.enumeration( Arrays.asList( b ) );
+
+    CompositeEnumeration<String> ce = new CompositeEnumeration<String>( ea, eb );
+
+    assertThat( ce.nextElement(), is( "1" ) );
+    assertThat( ce.nextElement(), is( "2" ) );
+    assertThat( ce.hasMoreElements(), is( false ) );
+  }
+
+  @Test
+  public void testEmptyEnumerations() {
+
+    String[] a = new String[]{ "1", "2" };
+    String[] b = new String[]{ "3", "4" };
+    String[] c = new String[]{};
+
+    Enumeration<String> e1 = Collections.enumeration( Arrays.asList( a ) );
+    Enumeration<String> e2 = Collections.enumeration( Arrays.asList( c ) );
+    CompositeEnumeration<String> ce = new CompositeEnumeration<String>( e1, e2 );
+    assertThat( ce.nextElement(), is( "1" ) );
+    assertThat( ce.nextElement(), is( "2" ) );
+    assertThat( ce.hasMoreElements(), is( false ) );
+
+    e1 = Collections.enumeration( Arrays.asList( c ) );
+    e2 = Collections.enumeration( Arrays.asList( a ) );
+    ce = new CompositeEnumeration<String>( e1, e2 );
+    assertThat( ce.nextElement(), is( "1" ) );
+    assertThat( ce.nextElement(), is( "2" ) );
+    assertThat( ce.hasMoreElements(), is( false ) );
+
+    e1 = Collections.enumeration( Arrays.asList( c ) );
+    e2 = Collections.enumeration( Arrays.asList( c ) );
+    ce = new CompositeEnumeration<String>( e1, e2 );
+    assertThat( ce.hasMoreElements(), is( false ) );
+  }
+
+  @Test
+  public void testEmpty() {
+    CompositeEnumeration<String> ce = new CompositeEnumeration<String>();
+    assertThat( ce.hasMoreElements(), is( false ) );
+
+    try {
+      ce.nextElement();
+      fail( "Should have throws NoSuchElementExcpetion" );
+    } catch( NoSuchElementException e ) {
+      // Expected.
+    }
+  }
+
+  @Test
+  public void testNulls() {
+    try {
+      CompositeEnumeration<String> ce = new CompositeEnumeration<String>( null );
+      fail( "Expected IllegalArgumentException" );
+    } catch( IllegalArgumentException e ) {
+      // Expected.
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/TestFilterAdapter.java
----------------------------------------------------------------------
diff --git a/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/TestFilterAdapter.java b/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/TestFilterAdapter.java
new file mode 100644
index 0000000..88a1e29
--- /dev/null
+++ b/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/TestFilterAdapter.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.knox.gateway.filter;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+public abstract class TestFilterAdapter implements Filter {
+
+  public abstract void doFilter( HttpServletRequest request, HttpServletResponse response, FilterChain chain ) throws IOException, ServletException;
+
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {}
+
+  @Override
+  public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException {
+    doFilter( (HttpServletRequest)request, (HttpServletResponse)response, chain );
+  }
+
+  @Override
+  public void destroy() {}
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/TestFilterChain.java
----------------------------------------------------------------------
diff --git a/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/TestFilterChain.java b/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/TestFilterChain.java
new file mode 100644
index 0000000..385bf58
--- /dev/null
+++ b/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/TestFilterChain.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.knox.gateway.filter;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import java.io.IOException;
+import java.util.Stack;
+
+public class TestFilterChain extends Stack<Filter> implements FilterChain {
+  @Override
+  public void doFilter( ServletRequest request, ServletResponse response ) throws IOException, ServletException {
+    if( !isEmpty() ) pop().doFilter( request, response, this );
+  }
+}
+
+

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/XForwardHeaderFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/XForwardHeaderFilterTest.java b/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/XForwardHeaderFilterTest.java
new file mode 100644
index 0000000..1d9c64c
--- /dev/null
+++ b/gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/XForwardHeaderFilterTest.java
@@ -0,0 +1,108 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter;
+
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public class XForwardHeaderFilterTest {
+
+  public static class AssertXForwardedHeaders extends TestFilterAdapter {
+    @Override
+    public void doFilter( HttpServletRequest request, HttpServletResponse response, FilterChain chain ) throws IOException, ServletException {
+      assertThat( request.getHeader( "X-Forwarded-For" ), is( "127.0.0.1" ) );
+      assertThat( request.getHeader( "X-Forwarded-Proto" ), is( "http" ) );
+      assertThat( request.getHeader( "X-Forwarded-Port" ), is( "8888" ) );
+      assertThat( request.getHeader( "X-Forwarded-Host" ), is( "localhost:8888" ) );
+      assertThat( request.getHeader( "X-Forwarded-Server" ), is( "localhost" ) );
+      assertThat( request.getHeader( "X-Forwarded-Context" ), is( "/context" ) );
+    }
+  }
+
+  @Test
+  public void testXForwardHeaders() throws ServletException, IOException {
+    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
+    EasyMock.expect( request.getRemoteAddr() ).andReturn( "127.0.0.1" ).anyTimes();
+    EasyMock.expect( request.isSecure() ).andReturn( false ).anyTimes();
+    EasyMock.expect( request.getLocalPort() ).andReturn( 8888 ).anyTimes();
+    EasyMock.expect( request.getHeader( "Host" ) ).andReturn( "localhost:8888" ).anyTimes();
+    EasyMock.expect( request.getServerName() ).andReturn( "localhost" ).anyTimes();
+    EasyMock.expect( request.getContextPath() ).andReturn( "/context" ).anyTimes();
+    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
+    EasyMock.replay( request, response );
+
+    TestFilterChain chain = new TestFilterChain();
+
+    XForwardedHeaderFilter filter = new XForwardedHeaderFilter();
+
+    chain.push( new AssertXForwardedHeaders() );
+    chain.push( filter );
+    chain.doFilter( request, response );
+  }
+
+  public static class AssertProxiedXForwardedHeaders extends TestFilterAdapter {
+    @Override
+    public void doFilter( HttpServletRequest request, HttpServletResponse response, FilterChain chain ) throws IOException, ServletException {
+      assertThat( request.getHeader( "X-Forwarded-For" ), is( "127.0.0.0,127.0.0.1" ) );
+      assertThat( request.getHeader( "X-Forwarded-Proto" ), is( "https" ) );
+      assertThat( request.getHeader( "X-Forwarded-Port" ), is( "9999" ) );
+      assertThat( request.getHeader( "X-Forwarded-Host" ), is( "remotehost:9999" ) );
+      assertThat( request.getHeader( "X-Forwarded-Server" ), is( "localhost" ) );
+      assertThat( request.getHeader( "X-Forwarded-Context" ), is( "/upstream/context" ) );
+    }
+  }
+
+  @Test
+  public void testProxiedXForwardHeaders() throws ServletException, IOException {
+    HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
+
+    EasyMock.expect( request.getHeader( "X-Forwarded-For" ) ).andReturn( "127.0.0.0" ).anyTimes();
+    EasyMock.expect( request.getHeader( "X-Forwarded-Proto" ) ).andReturn( "https" ).anyTimes();
+    EasyMock.expect( request.getHeader( "X-Forwarded-Port" ) ).andReturn( "9999" ).anyTimes();
+    EasyMock.expect( request.getHeader( "X-Forwarded-Host" ) ).andReturn( "remotehost:9999" ).anyTimes();
+    EasyMock.expect( request.getHeader( "X-Forwarded-Server" ) ).andReturn( "remotehost" ).anyTimes();
+    EasyMock.expect( request.getHeader( "X-Forwarded-Context" ) ).andReturn( "/upstream" ).anyTimes();
+
+    EasyMock.expect( request.getRemoteAddr() ).andReturn( "127.0.0.1" ).anyTimes();
+    EasyMock.expect( request.isSecure() ).andReturn( false ).anyTimes();
+    EasyMock.expect( request.getLocalPort() ).andReturn( 8888 ).anyTimes();
+    EasyMock.expect( request.getHeader( "Host" ) ).andReturn( "localhost:8888" ).anyTimes();
+    EasyMock.expect( request.getServerName() ).andReturn( "localhost" ).anyTimes();
+    EasyMock.expect( request.getContextPath() ).andReturn( "/context" ).anyTimes();
+
+    HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
+    EasyMock.replay( request, response );
+
+    TestFilterChain chain = new TestFilterChain();
+
+    XForwardedHeaderFilter filter = new XForwardedHeaderFilter();
+
+    chain.push( new AssertProxiedXForwardedHeaders() );
+    chain.push( filter );
+    chain.doFilter( request, response );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayCommandLine.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayCommandLine.java b/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayCommandLine.java
deleted file mode 100644
index a7e2ebc..0000000
--- a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayCommandLine.java
+++ /dev/null
@@ -1,86 +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.hadoop.gateway;
-
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.HelpFormatter;
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.Options;
-import org.apache.commons.cli.ParseException;
-import org.apache.commons.cli.PosixParser;
-import org.apache.hadoop.gateway.i18n.resources.ResourcesFactory;
-
-import java.io.PrintWriter;
-
-import static org.apache.commons.cli.HelpFormatter.*;
-
-public class GatewayCommandLine {
-
-  public static CommandLine parse( String[] args ) throws ParseException {
-    CommandLineParser parser = new PosixParser();
-    CommandLine commandLine = parser.parse( createCommandLine(), args );
-    return commandLine;
-  }
-
-  public static void printUsage() {
-    PrintWriter printer = new PrintWriter( System.err );
-    new HelpFormatter().printUsage( printer, LINE_WIDTH, COMMAND_NAME, createCommandLine() );
-    printer.flush();
-  }
-
-  public static void printHelp() {
-    PrintWriter printer = new PrintWriter( System.err );
-    new HelpFormatter().printHelp(printer, LINE_WIDTH, COMMAND_NAME, null, createCommandLine(), DEFAULT_LEFT_PAD, DEFAULT_DESC_PAD, null);
-    printer.flush();
-  }
-
-  /** default number of characters per line */
-  public static final int LINE_WIDTH = 80;
-  /** Name of the command to use in the command line */
-  public static final String COMMAND_NAME= "knox";
-
-  public static final String HELP_LONG = "help";
-  public static final String HELP_SHORT = "h";
-
-  public static final String VERSION_LONG = "version";
-  public static final String VERSION_SHORT = "v";
-
-  public static final String PERSIST_LONG = "persist-master";
-  public static final String PERSIST_SHORT = "pm";
-
-  public static final String NOSTART_LONG = "nostart";
-  public static final String NOSTART_SHORT = "ns";
-
-  public static final String REDEPLOY_LONG = "redeploy";
-  public static final String REDEPLOY_SHORT = "rd";
-
-  private static Options createCommandLine() {
-    Options options = new Options();
-    options.addOption( HELP_SHORT, HELP_LONG, false, res.helpMessage() );
-    options.addOption( VERSION_SHORT, VERSION_LONG, false, res.versionHelpMessage() );
-    Option redeploy = new Option( REDEPLOY_SHORT, REDEPLOY_LONG, true, res.redeployHelpMessage() );
-    redeploy.setOptionalArg( true );
-    options.addOption( redeploy );
-    options.addOption( PERSIST_SHORT, PERSIST_LONG, false, res.persistMasterHelpMessage() );
-    options.addOption( NOSTART_SHORT, NOSTART_LONG, false, res.nostartHelpMessage() );
-    return options;
-  }
-
-  private static GatewayResources res = ResourcesFactory.get( GatewayResources.class );
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayFactory.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayFactory.java b/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayFactory.java
deleted file mode 100644
index f813b44..0000000
--- a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayFactory.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.hadoop.gateway;
-
-import org.apache.hadoop.gateway.descriptor.FilterDescriptor;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.GatewayDescriptor;
-import org.apache.hadoop.gateway.descriptor.GatewayParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceParamDescriptor;
-
-import java.net.URISyntaxException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- *
- */
-public class GatewayFactory {
-
-//  public static GatewayFilter create( Config gatewayConfig ) throws URISyntaxException {
-//    GatewayFilter gateway = new GatewayFilter();
-//    for( Config service : gatewayConfig.getChildren().values() ) {
-//      addService( gateway, service );
-//    }
-//    return gateway;
-//  }
-//
-//  private static void addService( GatewayFilter gateway, Config serviceConfig ) throws URISyntaxException {
-//    for( Config filterConfig : serviceConfig.getChildren().values() ) {
-//      addFilter( gateway, filterConfig );
-//    }
-//  }
-//
-//  private static void addFilter( GatewayFilter gateway, Config filterConfig ) throws URISyntaxException {
-//    String source = filterConfig.get( "pattern" );
-//    String name = filterConfig.get( "name" );
-//    String clazz = filterConfig.get( "class" );
-//    gateway.addFilter( source, name, clazz, filterConfig );
-//  }
-
-  public static GatewayFilter create( GatewayDescriptor descriptor ) throws URISyntaxException {
-    GatewayFilter filter = new GatewayFilter();
-    for( ResourceDescriptor resource : descriptor.resources() ) {
-      addResource( filter, resource );
-    }
-    return filter;
-  }
-
-  private static void addResource( GatewayFilter gateway, ResourceDescriptor resource ) throws URISyntaxException {
-    for( FilterDescriptor filter : resource.filters() ) {
-      addFilter( gateway, filter );
-    }
-  }
-
-  private static void addFilter( GatewayFilter gateway, FilterDescriptor filter ) throws URISyntaxException {
-    String name = filter.name();
-    if( name == null ) {
-      name = filter.role();
-    }
-    gateway.addFilter( filter.up().pattern(), name, filter.impl(), createParams( filter ), filter.up().role() );
-  }
-
-  private static Map<String, String> createParams( FilterDescriptor filter ) {
-    Map<String, String> paramMap = new HashMap<>();
-    ResourceDescriptor resource = filter.up();
-    GatewayDescriptor gateway = resource.up();
-    for( GatewayParamDescriptor param : gateway.params() ) {
-      paramMap.put( param.name(), param.value() );
-    }
-    for( ResourceParamDescriptor param : resource.params() ) {
-      paramMap.put( param.name(), param.value() );
-    }
-    //TODO: Should all elements of the resource and gateway descriptor somehow be added to the filter params?
-    //TODO: Should we use some composite params object instead of copying all these name value pairs?
-    paramMap.put( "pattern", resource.pattern() );
-    List<FilterParamDescriptor> paramList = filter.params();
-    for( FilterParamDescriptor param : paramList ) {
-      paramMap.put( param.name(), param.value() );
-    }
-    return paramMap;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayFilter.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayFilter.java b/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayFilter.java
deleted file mode 100644
index c92ebfe..0000000
--- a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayFilter.java
+++ /dev/null
@@ -1,390 +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.hadoop.gateway;
-
-import org.apache.hadoop.gateway.audit.api.Action;
-import org.apache.hadoop.gateway.audit.api.ActionOutcome;
-import org.apache.hadoop.gateway.audit.api.AuditContext;
-import org.apache.hadoop.gateway.audit.api.AuditService;
-import org.apache.hadoop.gateway.audit.api.AuditServiceFactory;
-import org.apache.hadoop.gateway.audit.api.Auditor;
-import org.apache.hadoop.gateway.audit.api.CorrelationContext;
-import org.apache.hadoop.gateway.audit.api.CorrelationServiceFactory;
-import org.apache.hadoop.gateway.audit.api.ResourceType;
-import org.apache.hadoop.gateway.audit.log4j.audit.AuditConstants;
-import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.i18n.resources.ResourcesFactory;
-import org.apache.hadoop.gateway.util.urltemplate.Matcher;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
-
-/**
- *
- */
-public class GatewayFilter implements Filter {
-
-  private static final FilterChain EMPTY_CHAIN = new FilterChain() {
-    public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse ) throws IOException, ServletException {
-    }
-  };
-  
-  private static final GatewayMessages LOG = MessagesFactory.get( GatewayMessages.class );
-  private static final GatewayResources RES = ResourcesFactory.get( GatewayResources.class );
-  private static AuditService auditService = AuditServiceFactory.getAuditService();
-  private static Auditor auditor = auditService.getAuditor(
-      AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
-      AuditConstants.KNOX_COMPONENT_NAME );
-
-  private Set<Holder> holders;
-  private Matcher<Chain> chains;
-  private FilterConfig config;
-
-  public GatewayFilter() {
-    holders = new HashSet<>();
-    chains = new Matcher<Chain>();
-  }
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-    this.config = filterConfig;
-  }
-
-  @Override
-  public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) throws IOException, ServletException {
-    doFilter( servletRequest, servletResponse );
-    if( filterChain != null ) {
-      filterChain.doFilter( servletRequest, servletResponse );
-    }
-  }
-
-  @SuppressWarnings("unchecked")
-  public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse ) throws IOException, ServletException {
-    HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
-    HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;
-
-    //TODO: The resulting pathInfo + query needs to be added to the servlet context somehow so that filters don't need to rebuild it.  This is done in HttpClientDispatch right now for example.
-    String servlet = httpRequest.getServletPath();
-    String path = httpRequest.getPathInfo();
-    String query = httpRequest.getQueryString();
-    String requestPath = ( servlet == null ? "" : servlet ) + ( path == null ? "" : path );
-    String requestPathWithQuery = requestPath + ( query == null ? "" : "?" + query );
-
-    Template pathWithQueryTemplate;
-    try {
-      pathWithQueryTemplate = Parser.parseLiteral( requestPathWithQuery );
-    } catch( URISyntaxException e ) {
-      throw new ServletException( e );
-    }
-    String contextWithPathAndQuery = httpRequest.getContextPath() + requestPathWithQuery;
-    LOG.receivedRequest( httpRequest.getMethod(), requestPath );
-
-    servletRequest.setAttribute(
-        AbstractGatewayFilter.SOURCE_REQUEST_URL_ATTRIBUTE_NAME, pathWithQueryTemplate );
-    servletRequest.setAttribute(
-        AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME, contextWithPathAndQuery );
-
-    Matcher<Chain>.Match match = chains.match( pathWithQueryTemplate );
-    
-    assignCorrelationRequestId();
-    // Populate Audit/correlation parameters
-    AuditContext auditContext = auditService.getContext();
-    auditContext.setTargetServiceName( match == null ? null : match.getValue().getResourceRole() );
-    auditContext.setRemoteIp( getRemoteAddress(servletRequest) );
-    auditContext.setRemoteHostname( servletRequest.getRemoteHost() );
-    auditor.audit(
-        Action.ACCESS, contextWithPathAndQuery, ResourceType.URI,
-        ActionOutcome.UNAVAILABLE, RES.requestMethod(((HttpServletRequest)servletRequest).getMethod()));
-    
-    if( match != null ) {
-      Chain chain = match.getValue();
-      servletRequest.setAttribute( AbstractGatewayFilter.TARGET_SERVICE_ROLE, chain.getResourceRole() );
-      try {
-        chain.doFilter( servletRequest, servletResponse );
-      } catch( IOException e ) {
-        LOG.failedToExecuteFilter( e );
-        auditor.audit( Action.ACCESS, contextWithPathAndQuery, ResourceType.URI, ActionOutcome.FAILURE );
-        throw e;
-      } catch( ServletException e ) {
-        LOG.failedToExecuteFilter( e );
-        auditor.audit( Action.ACCESS, contextWithPathAndQuery, ResourceType.URI, ActionOutcome.FAILURE );
-        throw e;
-      } catch( RuntimeException e ) {
-        LOG.failedToExecuteFilter( e );
-        auditor.audit( Action.ACCESS, contextWithPathAndQuery, ResourceType.URI, ActionOutcome.FAILURE );
-        throw e;
-      } catch( ThreadDeath e ) {
-        LOG.failedToExecuteFilter( e );
-        auditor.audit( Action.ACCESS, contextWithPathAndQuery, ResourceType.URI, ActionOutcome.FAILURE );
-        throw e;
-      } catch( Throwable e ) {
-        LOG.failedToExecuteFilter( e );
-        auditor.audit( Action.ACCESS, contextWithPathAndQuery, ResourceType.URI, ActionOutcome.FAILURE );
-        throw new ServletException( e );
-      }
-    } else {
-      LOG.failedToMatchPath( requestPath );
-      httpResponse.setStatus( HttpServletResponse.SC_NOT_FOUND );
-    }
-    //KAM[ Don't do this or the Jetty default servlet will overwrite any response setup by the filter.
-    // filterChain.doFilter( servletRequest, servletResponse );
-    //]
-  }
-
-  private String getRemoteAddress(ServletRequest servletRequest) {
-    GatewayConfig gatewayConfig =
-        (GatewayConfig) servletRequest.getServletContext().
-        getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
-
-    String addrHeaderName = gatewayConfig.getHeaderNameForRemoteAddress();
-    String addr = ((HttpServletRequest)servletRequest).getHeader(addrHeaderName);
-    if (addr == null || addr.trim().isEmpty()) {
-      addr = servletRequest.getRemoteAddr();
-    }
-    return addr;
-  }
-
-  @Override
-  public void destroy() {
-    for( Holder holder : holders ) {
-      holder.destroy();
-    }
-  }
-
-  private void addHolder( Holder holder ) {
-    holders.add( holder );
-    Chain chain = chains.get( holder.template );
-    if( chain == null ) {
-      chain = new Chain();
-      chain.setResourceRole( holder.getResourceRole() );
-      chains.add( holder.template, chain );
-    }
-    chain.chain.add( holder );
-  }
-
-  public void addFilter( String path, String name, Filter filter, Map<String,String> params, String resourceRole ) throws URISyntaxException {
-    Holder holder = new Holder( path, name, filter, params, resourceRole );
-    addHolder( holder );
-  }
-
-//  public void addFilter( String path, String name, Class<RegexDirFilter> clazz, Map<String,String> params ) throws URISyntaxException {
-//    Holder holder = new Holder( path, name, clazz, params );
-//    addHolder( holder );
-//  }
-
-  public void addFilter( String path, String name, String clazz, Map<String,String> params, String resourceRole ) throws URISyntaxException {
-    Holder holder = new Holder( path, name, clazz, params, resourceRole );
-    addHolder( holder );
-  }
-
-  // Now creating the correlation context only if required since it may be created upstream in the CorrelationHandler.
-  private void assignCorrelationRequestId() {
-    CorrelationContext correlationContext = CorrelationServiceFactory.getCorrelationService().getContext();
-    if( correlationContext == null ) {
-      correlationContext = CorrelationServiceFactory.getCorrelationService().createContext();
-    }
-    String requestId = correlationContext.getRequestId();
-    if( requestId == null ) {
-      correlationContext.setRequestId( UUID.randomUUID().toString() );
-    }
-  }
-
-  private class Chain implements FilterChain {
-
-    private List<Holder> chain;
-    private String resourceRole; 
-
-    private Chain() {
-      this.chain = new ArrayList<Holder>();
-    }
-
-    private Chain( List<Holder> chain ) {
-      this.chain = chain;
-    }
-
-    public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse ) throws IOException, ServletException {
-      if( chain != null && !chain.isEmpty() ) {
-        final Filter filter = chain.get( 0 );
-        final FilterChain chain = subChain();
-        filter.doFilter( servletRequest, servletResponse, chain );
-      }
-    }
-
-    private FilterChain subChain() {
-      if( chain != null && chain.size() > 1 ) {
-        return new Chain( chain.subList( 1, chain.size() ) );
-      } else {
-        return EMPTY_CHAIN;
-      }
-    }
-
-    private String getResourceRole() {
-      return resourceRole;
-    }
-
-    private void setResourceRole( String resourceRole ) {
-      this.resourceRole = resourceRole;
-    }
-
-  }
-
-  private class Holder implements Filter, FilterConfig {
-//    private String path;
-    private Template template;
-    private String name;
-    private Map<String,String> params;
-    private Filter instance;
-    private Class<? extends Filter> clazz;
-    private String type;
-    private String resourceRole;
-
-    private Holder( String path, String name, Filter filter, Map<String,String> params, String resourceRole ) throws URISyntaxException {
-//      this.path = path;
-      this.template = Parser.parseTemplate( path );
-      this.name = name;
-      this.params = params;
-      this.instance = filter;
-      this.clazz = filter.getClass();
-      this.type = clazz.getCanonicalName();
-      this.resourceRole = resourceRole;
-    }
-
-//    private Holder( String path, String name, Class<RegexDirFilter> clazz, Map<String,String> params ) throws URISyntaxException {
-//      this.path = path;
-//      this.template = Parser.parse( path );
-//      this.name = name;
-//      this.params = params;
-//      this.instance = null;
-//      this.clazz = clazz;
-//      this.type = clazz.getCanonicalName();
-//    }
-
-    private Holder( String path, String name, String clazz, Map<String,String> params, String resourceRole ) throws URISyntaxException {
-//      this.path = path;
-      this.template = Parser.parseTemplate( path );
-      this.name = name;
-      this.params = params;
-      this.instance = null;
-      this.clazz = null;
-      this.type = clazz;
-      this.resourceRole = resourceRole;
-    }
-
-    @Override
-    public String getFilterName() {
-      return name;
-    }
-
-    @Override
-    public ServletContext getServletContext() {
-      return GatewayFilter.this.config.getServletContext();
-    }
-
-    @Override
-    public String getInitParameter( String name ) {
-      String value = null;
-      if( params != null ) {
-        value = params.get( name );
-      }
-      return value;
-    }
-
-    @Override
-    public Enumeration<String> getInitParameterNames() {
-      Enumeration<String> names = null;
-      if( params != null ) {
-        names = Collections.enumeration( params.keySet() );
-      }
-      return names;
-    }
-
-    @Override
-    public void init( FilterConfig filterConfig ) throws ServletException {
-      getInstance().init( filterConfig );
-    }
-
-    @Override
-    public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) throws IOException, ServletException {
-      final Filter filter = getInstance();
-      filter.doFilter( servletRequest, servletResponse, filterChain );
-    }
-
-    @Override
-    public void destroy() {
-      if( instance != null ) {
-        instance.destroy();
-        instance = null;
-      }
-    }
-
-    @SuppressWarnings("unchecked")
-    private Class<? extends Filter> getClazz() throws ClassNotFoundException {
-      if( clazz == null ) {
-        ClassLoader loader = Thread.currentThread().getContextClassLoader();
-        if( loader == null ) {
-          loader = this.getClass().getClassLoader();
-        }
-        clazz = (Class)loader.loadClass( type );
-      }
-      return clazz;
-    }
-
-    private Filter getInstance() throws ServletException {
-      if( instance == null ) {
-        try {
-          if( clazz == null ) {
-            clazz = getClazz();
-          }
-          instance = clazz.newInstance();
-          instance.init( this );
-        } catch( Exception e ) {
-          throw new ServletException( e );
-        }
-      }
-      return instance;
-    }
-    
-    private String getResourceRole() {
-      return resourceRole;
-    }
-
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayForwardingServlet.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayForwardingServlet.java b/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayForwardingServlet.java
deleted file mode 100644
index f2d21be..0000000
--- a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayForwardingServlet.java
+++ /dev/null
@@ -1,141 +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.hadoop.gateway;
-
-import org.apache.hadoop.gateway.audit.api.*;
-import org.apache.hadoop.gateway.audit.log4j.audit.AuditConstants;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.i18n.resources.ResourcesFactory;
-
-import java.io.*;
-
-import javax.servlet.*;
-import javax.servlet.http.*;
-
-public class GatewayForwardingServlet extends HttpServlet{
-
-  private static final long serialVersionUID = 1L;
-
-  private static final String AUDIT_ACTION = "forward";
-
-  private static final GatewayResources RES = ResourcesFactory.get( GatewayResources.class );
-  private static final GatewayMessages LOG = MessagesFactory.get( GatewayMessages.class );
-
-  private static AuditService auditService = AuditServiceFactory.getAuditService();
-  private static Auditor auditor = AuditServiceFactory.getAuditService()
-          .getAuditor( AuditConstants.DEFAULT_AUDITOR_NAME,
-                  AuditConstants.KNOX_SERVICE_NAME, AuditConstants.KNOX_COMPONENT_NAME );
-
-  private String redirectToContext = null;
-
-  @Override
-  protected void doHead(HttpServletRequest req, HttpServletResponse resp)
-      throws ServletException, IOException {
-    doGet(req, resp);
-  }
-
-  @Override
-  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
-      throws ServletException, IOException {
-    doGet(req, resp);
-  }
-
-  @Override
-  protected void doPut(HttpServletRequest req, HttpServletResponse resp)
-      throws ServletException, IOException {
-    doGet(req, resp);
-  }
-
-  @Override
-  protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
-      throws ServletException, IOException {
-    doGet(req, resp);
-  }
-
-  @Override
-  protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
-      throws ServletException, IOException {
-    doGet(req, resp);
-  }
-
-  @Override
-  public void init(ServletConfig config) throws ServletException {
-    super.init(config);
-
-    redirectToContext = config.getInitParameter("redirectTo");
-  }
-
-  public void doGet(HttpServletRequest request,
-                    HttpServletResponse response)
-            throws ServletException, IOException
-  {
-    String origPath = getRequestPath( request );
-    try {
-      auditService.createContext();
-
-      String origRequest = getRequestLine( request );
-
-      auditor.audit(
-              AUDIT_ACTION, origPath, ResourceType.URI,
-              ActionOutcome.UNAVAILABLE, RES.forwardToDefaultTopology( request.getMethod(), redirectToContext ) );
-
-      // Perform cross context dispatch to the configured topology context
-      ServletContext ctx = getServletContext().getContext(redirectToContext);
-      RequestDispatcher dispatcher = ctx.getRequestDispatcher(origRequest);
-
-      dispatcher.forward(request, response);
-
-      auditor.audit(
-              AUDIT_ACTION, origPath, ResourceType.URI,
-              ActionOutcome.SUCCESS, RES.responseStatus( response.getStatus() ) );
-
-    } catch( ServletException | IOException | RuntimeException e ) {
-      auditor.audit(
-              AUDIT_ACTION, origPath, ResourceType.URI,
-              ActionOutcome.FAILURE );
-      throw e;
-    } catch( Throwable e ) {
-      auditor.audit(
-              AUDIT_ACTION, origPath, ResourceType.URI,
-              ActionOutcome.FAILURE );
-      throw new ServletException(e);
-    } finally {
-      auditService.detachContext();
-    }
-  }
-
-  private static final String getRequestPath( final HttpServletRequest request ) {
-    final String path = request.getPathInfo();
-    if( path == null ) {
-      return "";
-    } else {
-      return path;
-    }
-  }
-
-  private static final String getRequestLine( final HttpServletRequest request ) {
-    final String path = getRequestPath( request );
-    final String query = request.getQueryString();
-    if( query == null ) {
-      return path;
-    } else {
-      return path + "?" + query;
-    }
-  }
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayMessages.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayMessages.java b/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayMessages.java
deleted file mode 100644
index 1f94584..0000000
--- a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayMessages.java
+++ /dev/null
@@ -1,516 +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.hadoop.gateway;
-
-import org.apache.commons.cli.ParseException;
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-import org.apache.hadoop.gateway.i18n.messages.StackTrace;
-import org.apache.hadoop.gateway.services.security.KeystoreServiceException;
-
-import java.io.File;
-import java.net.URI;
-import java.util.Date;
-import java.util.Map;
-import java.util.Set;
-
-/**
- *
- */
-@Messages(logger="org.apache.hadoop.gateway")
-public interface GatewayMessages {
-
-  @Message( level = MessageLevel.FATAL, text = "Failed to parse command line: {0}" )
-  void failedToParseCommandLine( @StackTrace( level = MessageLevel.DEBUG ) ParseException e );
-
-  @Message( level = MessageLevel.INFO, text = "Starting gateway..." )
-  void startingGateway();
-
-  @Message( level = MessageLevel.FATAL, text = "Failed to start gateway: {0}" )
-  void failedToStartGateway( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.INFO, text = "Started gateway on port {0}." )
-  void startedGateway( int port );
-
-  @Message( level = MessageLevel.INFO, text = "Stopping gateway..." )
-  void stoppingGateway();
-
-  @Message( level = MessageLevel.INFO, text = "Stopped gateway." )
-  void stoppedGateway();
-
-  @Message( level = MessageLevel.INFO, text = "Loading configuration resource {0}" )
-  void loadingConfigurationResource( String res );
-
-  @Message( level = MessageLevel.INFO, text = "Loading configuration file {0}" )
-  void loadingConfigurationFile( String file );
-
-  @Message( level = MessageLevel.WARN, text = "Failed to load configuration file {0}: {1}" )
-  void failedToLoadConfig( String path, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.INFO, text = "Using {1} as GATEWAY_HOME via {0}." )
-  void settingGatewayHomeDir( String location, String home );
-
-  @Message( level = MessageLevel.INFO, text = "Loading topologies from directory: {0}" )
-  void loadingTopologiesFromDirectory( String topologiesDir );
-
-  @Message( level = MessageLevel.DEBUG, text = "Loading topology file: {0}" )
-  void loadingTopologyFile( String fileName );
-
-  @Message( level = MessageLevel.INFO, text = "Monitoring topologies in directory: {0}" )
-  void monitoringTopologyChangesInDirectory( String topologiesDir );
-
-  @Message( level = MessageLevel.INFO, text = "Deploying topology {0} to {1}" )
-  void deployingTopology( String clusterName, String warDirName );
-
-  @Message( level = MessageLevel.DEBUG, text = "Deployed topology {0}." )
-  void deployedTopology( String clusterName );
-
-  @Message( level = MessageLevel.INFO, text = "Loading topology {0} from {1}" )
-  void redeployingTopology( String clusterName, String warDirName );
-
-  @Message( level = MessageLevel.DEBUG, text = "Redeployed topology {0}." )
-  void redeployedTopology( String clusterName );
-
-  @Message( level = MessageLevel.INFO, text = "Activating topology {0}" )
-  void activatingTopology( String name );
-
-  @Message( level = MessageLevel.INFO, text = "Activating topology {0} archive {1}" )
-  void activatingTopologyArchive( String topology, String archive );
-
-  @Message( level = MessageLevel.INFO, text = "Deactivating topology {0}" )
-  void deactivatingTopology( String name );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to deploy topology {0}: {1}" )
-  void failedToDeployTopology( String name, @StackTrace(level=MessageLevel.DEBUG) Throwable e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to redeploy topology {0}" )
-  void failedToRedeployTopology( String name );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to redeploy topology {0}: {1}" )
-  void failedToRedeployTopology( String name, @StackTrace(level=MessageLevel.DEBUG) Throwable e );
-
-  @Message(level = MessageLevel.ERROR, text = "Failed to load topology {0}: Topology configuration is invalid!")
-  void failedToLoadTopology(String fileName);
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to redeploy topologies: {0}" )
-  void failedToRedeployTopologies( @StackTrace(level=MessageLevel.DEBUG) Throwable e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to undeploy topology {0}: {1}" )
-  void failedToUndeployTopology( String name, @StackTrace(level=MessageLevel.DEBUG) Exception e );
-
-  @Message( level = MessageLevel.INFO, text = "Deleting topology {0}" )
-  void deletingTopology( String topologyName );
-
-  @Message( level = MessageLevel.INFO, text = "Deleting deployed topology {0}" )
-  void deletingDeployment( String warDirName );
-
-  @Message( level = MessageLevel.DEBUG, text = "Purge backups of deployed topology {0}" )
-  void cleanupDeployments( String topologyName );
-
-  @Message( level = MessageLevel.INFO, text = "Deleting backup deployed topology {0}" )
-  void cleanupDeployment( String absolutePath );
-
-  @Message( level = MessageLevel.INFO, text = "Creating gateway home directory: {0}" )
-  void creatingGatewayHomeDir( File homeDir );
-
-  @Message( level = MessageLevel.INFO, text = "Creating gateway deployment directory: {0}" )
-  void creatingGatewayDeploymentDir( File topologiesDir );
-
-  @Message( level = MessageLevel.INFO, text = "Creating default gateway configuration file: {0}" )
-  void creatingDefaultConfigFile( File defaultConfigFile );
-
-  @Message( level = MessageLevel.INFO, text = "Creating sample topology file: {0}" )
-  void creatingDefaultTopologyFile( File defaultConfigFile );
-
-  @Message( level = MessageLevel.WARN, text = "Ignoring service deployment contributor with invalid null name: {0}" )
-  void ignoringServiceContributorWithMissingName( String className );
-
-  @Message( level = MessageLevel.WARN, text = "Ignoring service deployment contributor with invalid null role: {0}" )
-  void ignoringServiceContributorWithMissingRole( String className );
-
-  @Message( level = MessageLevel.WARN, text = "Ignoring service deployment contributor with invalid null version: {0}" )
-  void ignoringServiceContributorWithMissingVersion( String className );
-
-  @Message( level = MessageLevel.WARN, text = "Ignoring provider deployment contributor with invalid null name: {0}" )
-  void ignoringProviderContributorWithMissingName( String className );
-
-  @Message( level = MessageLevel.WARN, text = "Ignoring provider deployment contributor with invalid null role: {0}" )
-  void ignoringProviderContributorWithMissingRole( String className );
-
-  @Message( level = MessageLevel.INFO, text = "Loaded logging configuration: {0}" )
-  void loadedLoggingConfig( String fileName );
-
-  @Message( level = MessageLevel.WARN, text = "Failed to load logging configuration: {0}" )
-  void failedToLoadLoggingConfig( String fileName );
-
-  @Message( level = MessageLevel.INFO, text = "Creating credential store for the gateway instance." )
-  void creatingCredentialStoreForGateway();
-
-  @Message( level = MessageLevel.INFO, text = "Credential store for the gateway instance found - no need to create one." )
-  void credentialStoreForGatewayFoundNotCreating();
-
-  @Message( level = MessageLevel.INFO, text = "Creating keystore for the gateway instance." )
-  void creatingKeyStoreForGateway();
-
-  @Message( level = MessageLevel.INFO, text = "Keystore for the gateway instance found - no need to create one." )
-  void keyStoreForGatewayFoundNotCreating();
-
-  @Message( level = MessageLevel.INFO, text = "Creating credential store for the cluster: {0}" )
-  void creatingCredentialStoreForCluster(String clusterName);
-
-  @Message( level = MessageLevel.INFO, text = "Credential store found for the cluster: {0} - no need to create one." )
-  void credentialStoreForClusterFoundNotCreating(String clusterName);
-
-  @Message( level = MessageLevel.DEBUG, text = "Received request: {0} {1}" )
-  void receivedRequest( String method, String uri );
-
-  @Message( level = MessageLevel.DEBUG, text = "Dispatch request: {0} {1}" )
-  void dispatchRequest( String method, URI uri );
-  
-  @Message( level = MessageLevel.WARN, text = "Connection exception dispatching request: {0} {1}" )
-  void dispatchServiceConnectionException( URI uri, @StackTrace(level=MessageLevel.WARN) Exception e );
-
-  @Message( level = MessageLevel.DEBUG, text = "Signature verified: {0}" )
-  void signatureVerified( boolean verified );
-
-  @Message( level = MessageLevel.DEBUG, text = "Apache Knox Gateway {0} ({1})" )
-  void gatewayVersionMessage( String version, String hash );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to inject service {0}: {1}" )
-  void failedToInjectService( String serviceName, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to finalize contribution: {0}" )
-  void failedToFinalizeContribution( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to contribute service [role={1}, name={0}]: {2}" )
-  void failedToContributeService( String name, String role, @StackTrace( level = MessageLevel.ERROR ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to contribute provider [role={1}, name={0}]: {2}" )
-  void failedToContributeProvider( String name, String role, @StackTrace( level = MessageLevel.ERROR ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to initialize contribution: {0}" )
-  void failedToInitializeContribution( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to initialize servlet instance: {0}" )
-  void failedToInitializeServletInstace( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Gateway processing failed: {0}" )
-  void failedToExecuteFilter( @StackTrace( level = MessageLevel.INFO ) Throwable t );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to load topology {0}: {1}")
-  void failedToLoadTopology( String fileName, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to load topology {0}, retrying after {1}ms: {2}")
-  void failedToLoadTopologyRetrying( String friendlyURI, String delay, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to handle topology events: {0}" )
-  void failedToHandleTopologyEvents( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to reload topologies: {0}" )
-  void failedToReloadTopologies( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.FATAL, text = "Unsupported encoding: {0}" )
-  void unsupportedEncoding( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to persist master secret: {0}" )
-  void failedToPersistMasterSecret( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to encrypt master secret: {0}" )
-  void failedToEncryptMasterSecret( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to initialize master service from persistent master {0}: {1}" )
-  void failedToInitializeFromPersistentMaster( String masterFileName, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to encode passphrase: {0}" )
-  void failedToEncodePassphrase( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to verify signature: {0}")
-  void failedToVerifySignature( @StackTrace(level=MessageLevel.DEBUG) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to sign the data: {0}")
-  void failedToSignData( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to decrypt password for cluster {0}: {1}" )
-  void failedToDecryptPasswordForCluster( String clusterName, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to encrypt password for cluster {0}: {1}")
-  void failedToEncryptPasswordForCluster( String clusterName, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-  
-  @Message( level = MessageLevel.ERROR, text = "Failed to create keystore [filename={0}, type={1}]: {2}" )
-  void failedToCreateKeystore( String fileName, String keyStoreType, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to load keystore [filename={0}, type={1}]: {2}" )
-  void failedToLoadKeystore( String fileName, String keyStoreType, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to add key for cluster {0}: {1}" )
-  void failedToAddKeyForCluster( String clusterName, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to add credential for cluster {0}: {1}" )
-  void failedToAddCredentialForCluster( String clusterName, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-  
-  @Message( level = MessageLevel.ERROR, text = "Failed to get key for Gateway {0}: {1}" )
-  void failedToGetKeyForGateway( String alias, @StackTrace( level=MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to get credential for cluster {0}: {1}" )
-  void failedToGetCredentialForCluster( String clusterName, @StackTrace(level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to get key for cluster {0}: {1}" )
-  void failedToGetKeyForCluster( String clusterName, @StackTrace(level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to add self signed certificate for Gateway {0}: {1}" )
-  void failedToAddSeflSignedCertForGateway( String alias, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to generate secret key from password: {0}" )
-  void failedToGenerateKeyFromPassword( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to establish connection to {0}: {1}" )
-  void failedToEstablishConnectionToUrl( String url, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to interpret property \"{0}\": {1}")
-  void failedToInterpretProperty( String property, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to instantiate the internal gateway services." )
-  void failedToInstantiateGatewayServices();
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to serialize map to Json string {0}: {1}" )
-  void failedToSerializeMapToJSON( Map<String, Object> map, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to get map from Json string {0}: {1}" )
-  void failedToGetMapFromJsonString( String json, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-  
-  @Message( level = MessageLevel.DEBUG, text = "Successful Knox->Hadoop SPNegotiation authentication for URL: {0}" )
-  void successfulSPNegoAuthn(String uri);
-  
-  @Message( level = MessageLevel.ERROR, text = "Failed Knox->Hadoop SPNegotiation authentication for URL: {0}" )
-  void failedSPNegoAuthn(String uri);
-
-  @Message( level = MessageLevel.DEBUG, text = "Dispatch response status: {0}" )
-  void dispatchResponseStatusCode(int statusCode);
-
-  @Message( level = MessageLevel.DEBUG, text = "Dispatch response status: {0}, Location: {1}" )
-  void dispatchResponseCreatedStatusCode( int statusCode, String location );
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to decrypt cipher text for cluster {0}: due to inability to retrieve the password." )
-  void failedToDecryptCipherForClusterNullPassword(String clusterName);
-
-  @Message( level = MessageLevel.DEBUG, text = "Gateway services have not been initialized." )
-  void gatewayServicesNotInitialized();
-
-  @Message( level = MessageLevel.INFO, text = "The Gateway SSL certificate is issued to hostname: {0}." )
-  void certificateHostNameForGateway(String cn);
-
-  @Message( level = MessageLevel.INFO, text = "The Gateway SSL certificate is valid between: {0} and {1}." )
-  void certificateValidityPeriod(Date notBefore, Date notAfter);
-
-  @Message( level = MessageLevel.ERROR, text = "Unable to retrieve certificate for Gateway: {0}." )
-  void unableToRetrieveCertificateForGateway(Exception e);
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to generate alias for cluster: {0} {1}." )
-  void failedToGenerateAliasForCluster(String clusterName, KeystoreServiceException e);
-
-  @Message( level = MessageLevel.DEBUG, text = "Key passphrase not found in credential store - using master secret." )
-  void assumingKeyPassphraseIsMaster();
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to remove alias for cluster: {0} {1}." )
-  void failedToRemoveCredentialForCluster(String clusterName, Exception e);
-
-  @Message( level = MessageLevel.WARN, text = "Failed to match path {0}" )
-  void failedToMatchPath( String path );
-  
-  @Message( level = MessageLevel.ERROR, text = "Failed to get system ldap connection: {0}" )
-  void failedToGetSystemLdapConnection( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-  
-  @Message( level = MessageLevel.WARN, text = "Value not found for cluster:{0}, alias: {1}" )
-  void aliasValueNotFound( String cluster, String alias );
-
-  @Message( level = MessageLevel.INFO, text = "Computed userDn: {0} using dnTemplate for principal: {1}" )
-  void computedUserDn(String userDn, String principal);
-
-  @Message( level = MessageLevel.DEBUG, text = "Searching from {0} where {1} scope {2}" )
-  void searchBaseFilterScope( String searchBase, String searchFilter, String searchScope );
-
-  @Message( level = MessageLevel.INFO, text = "Computed userDn: {0} using ldapSearch for principal: {1}" )
-  void searchedAndFoundUserDn(String userDn, String principal);
-
-  @Message( level = MessageLevel.INFO, text = "Computed roles/groups: {0} for principal: {1}" )
-  void lookedUpUserRoles(Set<String> roleNames, String userName);
-
-  @Message( level = MessageLevel.DEBUG, text = "Initialize provider: {1}/{0}" )
-  void initializeProvider( String name, String role );
-
-  @Message( level = MessageLevel.DEBUG, text = "Initialize service: {1}/{0}" )
-  void initializeService( String name, String role );
-
-  @Message( level = MessageLevel.DEBUG, text = "Contribute provider: {1}/{0}" )
-  void contributeProvider( String name, String role );
-
-  @Message( level = MessageLevel.DEBUG, text = "Contribute service: {1}/{0}" )
-  void contributeService( String name, String role );
-
-  @Message( level = MessageLevel.DEBUG, text = "Finalize provider: {1}/{0}" )
-  void finalizeProvider( String name, String role );
-
-  @Message( level = MessageLevel.DEBUG, text = "Finalize service: {1}/{0}" )
-  void finalizeService( String name, String role );
-
-  @Message( level = MessageLevel.DEBUG, text = "Configured services directory is {0}" )
-  void usingServicesDirectory(String path);
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to unmarshall service definition file {0} file : {1}" )
-  void failedToLoadServiceDefinition(String fileName, @StackTrace( level = MessageLevel.DEBUG ) Exception e);
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to find service definition file {0} file : {1}" )
-  void failedToFindServiceDefinitionFile(String fileName, @StackTrace( level = MessageLevel.DEBUG ) Exception e);
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to find rewrite file {0} file : {1}" )
-  void failedToFindRewriteFile(String fileName, @StackTrace( level = MessageLevel.DEBUG ) Exception e);
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to unmarshall rewrite file {0} file : {1}" )
-  void failedToLoadRewriteFile(String fileName, @StackTrace( level = MessageLevel.DEBUG ) Exception e);
-
-  @Message( level = MessageLevel.DEBUG, text = "No rewrite file found in service directory {0}" )
-  void noRewriteFileFound(String path);
-
-  @Message( level = MessageLevel.DEBUG, text = "Added Service definition name: {0}, role : {1}, version : {2}" )
-  void addedServiceDefinition(String serviceName, String serviceRole, String version);
-
-  @Message( level = MessageLevel.INFO, text = "System Property: {0}={1}" )
-  void logSysProp( String name, String property );
-
-  @Message( level = MessageLevel.ERROR, text = "Unable to get password: {0}" )
-  void unableToGetPassword(@StackTrace( level = MessageLevel.DEBUG ) Exception e);
-
-  @Message( level = MessageLevel.DEBUG, text = "Initialize application: {0}" )
-  void initializeApplication( String name );
-
-  @Message( level = MessageLevel.DEBUG, text = "Contribute application: {0}" )
-  void contributeApplication( String name );
-
-  @Message( level = MessageLevel.DEBUG, text = "Finalize application: {0}" )
-  void finalizeApplication( String name );
-
-  @Message( level = MessageLevel.INFO, text = "Default topology {0} at {1}" )
-  void defaultTopologySetup( String defaultTopologyName, String redirectContext );
-
-  @Message( level = MessageLevel.DEBUG, text = "Default topology forward from {0} to {1}" )
-  void defaultTopologyForward( String oldTarget, String newTarget );
-
-  @Message( level = MessageLevel.ERROR, text = "Unable to setup PagedResults" )
-  void unableToSetupPagedResults();
-
-  @Message( level = MessageLevel.INFO, text = "Ignoring PartialResultException" )
-  void ignoringPartialResultException();
-
-  @Message( level = MessageLevel.WARN, text = "Only retrieved first {0} groups due to SizeLimitExceededException." )
-  void sizeLimitExceededOnlyRetrieved(int numResults);
-
-  @Message( level = MessageLevel.DEBUG, text = "Failed to parse path into Template: {0} : {1}" )
-  void failedToParsePath( String path, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
-
-  @Message( level = MessageLevel.DEBUG, text = "Failed to initialize metrics reporter {0}  : {1}" )
-  void failedToInitializeReporter( String name,  @StackTrace( level = MessageLevel.DEBUG ) Exception e);
-
-  @Message( level = MessageLevel.DEBUG, text = "Failed to start metrics reporter {0}  : {1}" )
-  void failedToStartReporter( String name,  @StackTrace( level = MessageLevel.DEBUG ) Exception e);
-
-  @Message( level = MessageLevel.DEBUG, text = "Failed to stop metrics reporter {0}  : {1}" )
-  void failedToStopReporter( String name,  @StackTrace( level = MessageLevel.DEBUG ) Exception e);
-
-  @Message( level = MessageLevel.INFO, text = "Cookie scoping feature enabled: {0}" )
-  void cookieScopingFeatureEnabled( boolean enabled );
-
-  /**
-   * Log whether Topology port mapping feature is enabled/disabled.
-   *
-   * @param enabled
-   */
-  @Message(level = MessageLevel.INFO,
-           text = "Topology port mapping feature enabled: {0}")
-  void gatewayTopologyPortMappingEnabled(final boolean enabled);
-
-  /**
-   * @param topology
-   * @param port
-   */
-  @Message(level = MessageLevel.DEBUG,
-           text = "Creating a connector for topology {0} listening on port {1}.")
-  void createJettyConnector(final String topology, final int port);
-
-  /**
-   * @param topology
-   */
-  @Message(level = MessageLevel.DEBUG,
-           text = "Creating a handler for topology {0}.")
-  void createJettyHandler(final String topology);
-
-  /**
-   * @param oldTarget
-   * @param newTarget
-   */
-  @Message(level = MessageLevel.INFO,
-           text = "Updating request context from {0} to {1}")
-  void topologyPortMappingAddContext(final String oldTarget,
-      final String newTarget);
-
-  /**
-   * @param oldTarget
-   * @param newTarget
-   */
-  @Message(level = MessageLevel.DEBUG,
-           text = "Updating request target from {0} to {1}")
-  void topologyPortMappingUpdateRequest(final String oldTarget,
-      final String newTarget);
-
-  /**
-   * Messages for Topology Port Mapping
-   *
-   * @param port
-   * @param topology
-   */
-  @Message(level = MessageLevel.ERROR,
-           text = "Port {0} configured for Topology - {1} is already in use.")
-  void portAlreadyInUse(final int port, final String topology);
-
-  /**
-   * Messages for Topology Port Mapping
-   *
-   * @param port
-   */
-  @Message(level = MessageLevel.ERROR,
-           text = "Port {0} is already in use.")
-  void portAlreadyInUse(final int port);
-
-  /**
-   * Log topology and port
-   *
-   * @param topology
-   * @param port
-   */
-  @Message(level = MessageLevel.INFO,
-           text = "Started gateway, topology \"{0}\" listening on port \"{1}\".")
-  void startedGateway(final String topology, final int port);
-
-  @Message(level = MessageLevel.ERROR,
-           text =
-               " Could not find topology \"{0}\" mapped to port \"{1}\" configured in gateway-config.xml. "
-                   + "This invalid topology mapping will be ignored by the gateway. "
-                   + "Gateway restart will be required if in the future \"{0}\" topology is added.")
-  void topologyPortMappingCannotFindTopology(final String topology,
-      final int port);
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayResources.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayResources.java b/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayResources.java
deleted file mode 100644
index ca73279..0000000
--- a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayResources.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.hadoop.gateway;
-
-import org.apache.hadoop.gateway.i18n.resources.Resource;
-import org.apache.hadoop.gateway.i18n.resources.Resources;
-
-/**
- *
- */
-@Resources
-public interface GatewayResources {
-
-  @Resource( text="Apache Knox Gateway {0} ({1})" )
-  String gatewayVersionMessage( String version, String hash );
-
-  @Resource( text="Apache Knox Gateway" )
-  String gatewayServletInfo();
-
-  @Resource( text="Service connectivity error." )
-  String dispatchConnectionError();
-
-  @Resource( text="Display command line help." )
-  String helpMessage();
-
-  @Resource( text="This parameter causes the server to exit before starting to service requests. This is typically used with the -persist-master parameter." )
-  String nostartHelpMessage();
-
-  @Resource( text="This parameter causes the provider master secret to be persisted. This prevents the server from prompting for a master secret on subsequent starts." )
-  String persistMasterHelpMessage();
-
-  @Resource( text="This parameter causes the existing topologies to be redeployed. A single topology may be specified via an optional parameter.  The server will not be started." )
-  String redeployHelpMessage();
-
-  @Resource( text="Display server version information." )
-  String versionHelpMessage();
-
-  @Resource( text="Topology is required." )
-  String topologyIsRequiredError();
-
-  @Resource( text="Provider is required." )
-  String providerIsRequiredError();
-
-  @Resource( text="Unsupported property''s token: {0}" )
-  String unsupportedPropertyTokenError(String token);
-
-  @Resource( text="Failed to build topology: wrong data format." )
-  String wrongTopologyDataFormatError();
-
-  @Resource( text="Provider parameter name is required." )
-  String providerParameterNameIsRequiredError();
-
-  @Resource( text="Provider parameter value is required." )
-  String providerParameterValueIsRequiredError();
-
-  @Resource( text="Service parameter name is required." )
-  String serviceParameterNameIsRequiredError();
-
-  @Resource( text="Service parameter value is required." )
-  String serviceParameterValueIsRequiredError();
-
-  @Resource( text="Failed to create keystore directory: {0}" )
-  String failedToCreateKeyStoreDirectory( String name );
-
-  @Resource( text="Response status: {0}" )
-  String responseStatus( int status );
-
-  @Resource( text="Request method: {0}" )
-  String requestMethod( String method );
-
-  @Resource( text="Forward method: {0} to default context: {1}" )
-  String forwardToDefaultTopology(String method, String context );
-}


[28/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRulesDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRulesDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRulesDescriptorImpl.java
deleted file mode 100644
index 9e08bcb..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteRulesDescriptorImpl.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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class UrlRewriteRulesDescriptorImpl implements UrlRewriteRulesDescriptor {
-
-  private Map<String,UrlRewriteFunctionDescriptor> funcMap = new HashMap<>();
-  private List<UrlRewriteFunctionDescriptor> funcList = new ArrayList<UrlRewriteFunctionDescriptor>();
-  private List<UrlRewriteRuleDescriptor> ruleList = new ArrayList<UrlRewriteRuleDescriptor>();
-  private Map<String,UrlRewriteRuleDescriptor> ruleMap = new HashMap<>();
-  private List<UrlRewriteFilterDescriptor> filterList = new ArrayList<UrlRewriteFilterDescriptor>();
-  private Map<String,UrlRewriteFilterDescriptor> filterMap = new HashMap<>();
-
-  @Override
-  public void addRules( UrlRewriteRulesDescriptor rules ) {
-    for( UrlRewriteRuleDescriptor rule : rules.getRules() ) {
-      addRule( rule );
-    }
-    for( UrlRewriteFilterDescriptor filter : rules.getFilters() ) {
-      addFilter( filter  );
-    }
-  }
-
-  @Override
-  public UrlRewriteRuleDescriptor getRule( String name ) {
-    return ruleMap.get( name );
-  }
-
-  @Override
-  public List<UrlRewriteRuleDescriptor> getRules() {
-    return ruleList;
-  }
-
-  @Override
-  public UrlRewriteRuleDescriptor addRule( String name ) {
-    UrlRewriteRuleDescriptor rule = newRule();
-    rule.name( name );
-    addRule( rule );
-    return rule;
-  }
-
-  @Override
-  public UrlRewriteRuleDescriptor newRule() {
-    return new UrlRewriteRuleDescriptorImpl();
-  }
-
-  @Override
-  public void addRule( UrlRewriteRuleDescriptor rule ) {
-    ruleList.add( rule );
-    String name = rule.name();
-    if( name != null && name.length() > 0 ) {
-      ruleMap.put( rule.name(), rule );
-    }
-  }
-
-  @Override
-  public List<UrlRewriteFunctionDescriptor> getFunctions() {
-    return funcList;
-  }
-
-  @Override
-  @SuppressWarnings("unchecked")
-  public <T extends UrlRewriteFunctionDescriptor<?>> T getFunction( String name ) {
-    T descriptor = (T)funcMap.get( name );
-    return (T)descriptor;
-  }
-
-  @Override
-  @SuppressWarnings("unchecked")
-  public <T extends UrlRewriteFunctionDescriptor<?>> T addFunction( String name ) {
-    T descriptor = (T)newFunction( name );
-    addFunction( descriptor );
-    return (T)descriptor;
-  }
-
-  @SuppressWarnings("unchecked")
-  protected <T extends UrlRewriteFunctionDescriptor<?>> T newFunction( String name ) {
-    T descriptor = (T)UrlRewriteFunctionDescriptorFactory.create( name );
-    return (T)descriptor;
-  }
-
-  protected void addFunction( UrlRewriteFunctionDescriptor descriptor ) {
-    funcList.add( descriptor );
-    funcMap.put( descriptor.name(), descriptor );
-  }
-
-
-  @Override
-  public List<UrlRewriteFilterDescriptor> getFilters() {
-    return filterList;
-  }
-
-  @Override
-  public UrlRewriteFilterDescriptor getFilter( String name ) {
-    return filterMap.get( name );
-  }
-
-  @Override
-  public UrlRewriteFilterDescriptor newFilter() {
-    return new UrlRewriteFilterDescriptorImpl();
-  }
-
-  @Override
-  public UrlRewriteFilterDescriptor addFilter( String name ) {
-    UrlRewriteFilterDescriptor filter = newFilter();
-    filter.name( name );
-    addFilter( filter );
-    return filter;
-  }
-
-  @Override
-  public void addFilter( UrlRewriteFilterDescriptor descriptor ) {
-    filterList.add( descriptor );
-    filterMap.put( descriptor.name(), descriptor );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorFactory.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorFactory.java
deleted file mode 100644
index 27f7f9f..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorFactory.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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
-
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.ServiceLoader;
-
-public abstract class UrlRewriteStepProcessorFactory {
-
-  private static final Map<Class<? extends UrlRewriteStepDescriptor>,Map<String,Class<? extends UrlRewriteStepProcessor>>> MAP
-      = loadStepProcessors();
-
-  private UrlRewriteStepProcessorFactory() {
-  }
-
-  public static UrlRewriteStepProcessor create( UrlRewriteStepDescriptor descriptor ) throws IllegalAccessException, InstantiationException {
-    UrlRewriteStepProcessor processor;
-    Map<String,Class<? extends UrlRewriteStepProcessor>> typeMap;
-    typeMap = MAP.get( descriptor.getClass() );
-    if( typeMap == null ) {
-      Class<? extends UrlRewriteStepDescriptor> descriptorInterface = getDescriptorInterface( descriptor );
-      typeMap = MAP.get( descriptorInterface );
-    }
-    if( typeMap == null ) {
-      throw new IllegalArgumentException( descriptor.getClass().getName() );
-    } else {
-      String type = descriptor.type();
-      Class<? extends UrlRewriteStepProcessor> processorClass = typeMap.get( type );
-      if( processorClass == null ) {
-        throw new IllegalArgumentException( type );
-      } else {
-        processor = processorClass.newInstance();
-      }
-    }
-    return processor;
-  }
-
-  private static Map<Class<? extends UrlRewriteStepDescriptor>,Map<String,Class<? extends UrlRewriteStepProcessor>>> loadStepProcessors() {
-    Map<Class<? extends UrlRewriteStepDescriptor>,Map<String,Class<? extends UrlRewriteStepProcessor>>> descriptorMap
-        = new HashMap<>();
-    ServiceLoader<UrlRewriteStepProcessor> processors = ServiceLoader.load( UrlRewriteStepProcessor.class );
-    for( UrlRewriteStepProcessor processor : processors ) {
-      Class<? extends UrlRewriteStepDescriptor> descriptorInterface = getDescriptorInterface( processor );
-      Map<String,Class<? extends UrlRewriteStepProcessor>> typeMap = descriptorMap.get( descriptorInterface );
-      if( typeMap == null ) {
-        typeMap = new HashMap<>();
-        descriptorMap.put( descriptorInterface, typeMap );
-      }
-      String processorType = processor.getType();
-      typeMap.put( processorType, processor.getClass() );
-    }
-    return descriptorMap;
-  }
-
-  private static Class<? extends UrlRewriteStepDescriptor> getDescriptorInterface( UrlRewriteStepDescriptor descriptor ) {
-    Class<? extends UrlRewriteStepDescriptor> descriptorClass = null;
-    for( Type interfaceType : descriptor.getClass().getGenericInterfaces() ) {
-      Class genericClass = (Class)interfaceType;
-      if( UrlRewriteStepDescriptor.class.isAssignableFrom( genericClass ) ) {
-        descriptorClass = uncheckedStepDescriptorClassCast( genericClass );
-        break;
-      }
-    }
-    return descriptorClass;
-  }
-
-  private static Class<? extends UrlRewriteStepDescriptor> getDescriptorInterface( UrlRewriteStepProcessor processor ) {
-    Class<? extends UrlRewriteStepDescriptor> descriptorClass = null;
-    Class<? extends UrlRewriteStepProcessor> processorClass = processor.getClass();
-    for( Type interfaceType : processorClass.getGenericInterfaces() ) {
-      if( UrlRewriteStepProcessor.class.isAssignableFrom( (Class)((ParameterizedType)interfaceType).getRawType() ) ) {
-        ParameterizedType interfaceClass = (ParameterizedType)interfaceType;
-        descriptorClass = uncheckedStepDescriptorClassCast( interfaceClass.getActualTypeArguments()[ 0 ] );
-        break;
-      }
-    }
-    return descriptorClass;
-  }
-
-  @SuppressWarnings("unchecked")
-  private static Class<? extends UrlRewriteStepDescriptor> uncheckedStepDescriptorClassCast( Type type ) {
-    return (Class<? extends UrlRewriteStepDescriptor>)type;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorHolder.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorHolder.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorHolder.java
deleted file mode 100644
index b365bc0..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorHolder.java
+++ /dev/null
@@ -1,233 +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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFlowDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepFlow;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-public class UrlRewriteStepProcessorHolder implements UrlRewriteStepProcessor {
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-
-  private boolean isCondition;
-  private UrlRewriteStepDescriptor descriptor;
-  private UrlRewriteStepProcessor processor;
-  private List<UrlRewriteStepProcessorHolder> childProcessors;
-
-  @Override
-  public String getType() {
-    return "system";
-  }
-
-  public boolean isCondition() {
-    return isCondition;
-  }
-
-  public boolean isAction() {
-    return !isCondition;
-  }
-
-  @Override
-  @SuppressWarnings( "unchecked" )
-  public void initialize( UrlRewriteEnvironment environment, UrlRewriteStepDescriptor descriptor ) throws Exception {
-    UrlRewriteStepProcessor processor = UrlRewriteStepProcessorFactory.create( descriptor );
-    processor.initialize( environment, descriptor );
-    initialize( environment, descriptor, processor );
-  }
-
-  // For unit testing.
-  @SuppressWarnings("unchecked")
-  void initialize( UrlRewriteEnvironment environment, UrlRewriteStepDescriptor descriptor, UrlRewriteStepProcessor processor ) throws Exception {
-    this.descriptor = descriptor;
-    this.processor = processor;
-    this.isCondition = descriptor instanceof UrlRewriteFlowDescriptor;
-    this.childProcessors = new ArrayList<UrlRewriteStepProcessorHolder>();
-    if( isCondition ) {
-      UrlRewriteFlowDescriptor flowDescriptor = (UrlRewriteFlowDescriptor)descriptor;
-      List<UrlRewriteStepDescriptor> stepList = flowDescriptor.steps();
-      if( stepList != null && !stepList.isEmpty() ) {
-        Iterator<UrlRewriteStepDescriptor> stepIterator = stepList.iterator();
-        while( stepIterator.hasNext() ) {
-          UrlRewriteStepDescriptor stepDescriptor = stepIterator.next();
-          UrlRewriteStepProcessorHolder stepProcessor = new UrlRewriteStepProcessorHolder();
-          stepProcessor.initialize( environment, stepDescriptor );
-          childProcessors.add( stepProcessor );
-        }
-      }
-    }
-  }
-
-  // For unit testing.
-  UrlRewriteStepDescriptor getDescriptor() {
-    return descriptor;
-  }
-
-  // For unit testing.
-  UrlRewriteStepProcessor getProcessor() {
-    return processor;
-  }
-
-  @Override
-  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
-    UrlRewriteStepStatus status = UrlRewriteStepStatus.SUCCESS;
-    // If initialization failed then fail processing
-    if( processor != null ) {
-      status = processor.process( context );
-      if( UrlRewriteStepStatus.SUCCESS == status &&
-          descriptor instanceof UrlRewriteFlowDescriptor &&
-          !childProcessors.isEmpty() ) {
-        UrlRewriteFlowDescriptor flowDescriptor = (UrlRewriteFlowDescriptor)descriptor;
-        UrlRewriteStepFlow flow = flowDescriptor.flow();
-        if( flow == null ) {
-          flow = UrlRewriteStepFlow.AND;
-        }
-        switch( flow ) {
-          case ALL:
-            return processAllFlow( context );
-          case AND:
-            return processAndFlow( context );
-          case OR:
-            return processOrFlow( context );
-        }
-      }
-    }
-    return status;
-  }
-
-  private UrlRewriteStepStatus processAllFlow( UrlRewriteContext context ) throws Exception {
-    UrlRewriteStepProcessorState state = new UrlRewriteStepProcessorState( childProcessors.iterator() );
-    UrlRewriteStepStatus stepStatus = UrlRewriteStepStatus.SUCCESS;
-    UrlRewriteStepProcessorHolder step;
-    while( state.hasNext() ) {
-      while( state.hasNextCondition() ) {
-        step = state.nextCondition( stepStatus );
-        stepStatus = step.process( context );
-        if( stepStatus == UrlRewriteStepStatus.FINISHED ) {
-          return stepStatus;
-        }
-      }
-      stepStatus = processActions( context, state );
-      if( stepStatus == UrlRewriteStepStatus.FINISHED ) {
-        return stepStatus;
-      }
-    }
-    return UrlRewriteStepStatus.SUCCESS;
-  }
-
-  // All conditions proceeding a set of one or more actions must succeed for the actions to be executed.
-  private UrlRewriteStepStatus processAndFlow( UrlRewriteContext context ) throws Exception {
-    UrlRewriteStepProcessorState state = new UrlRewriteStepProcessorState( childProcessors.iterator() );
-    UrlRewriteStepStatus stepStatus = UrlRewriteStepStatus.SUCCESS;
-    UrlRewriteStepProcessorHolder step;
-    while( state.hasNext() ) {
-      while( state.hasNextCondition() ) {
-        step = state.nextCondition( stepStatus );
-        stepStatus = step.process( context );
-        if( !( stepStatus == UrlRewriteStepStatus.SUCCESS ) ) {
-          return stepStatus;
-        }
-      }
-      stepStatus = processActions( context, state );
-      if( !( stepStatus == UrlRewriteStepStatus.SUCCESS ) ) {
-        return stepStatus;
-      }
-    }
-    return UrlRewriteStepStatus.SUCCESS;
-  }
-
-  // At least one condition proceeding a set of one or more actions must succedd for the actions to be executed.
-  private UrlRewriteStepStatus processOrFlow( UrlRewriteContext context ) throws Exception {
-    UrlRewriteStepProcessorState state = new UrlRewriteStepProcessorState( childProcessors.iterator() );
-    UrlRewriteStepStatus status = UrlRewriteStepStatus.SUCCESS;
-    UrlRewriteStepProcessorHolder step;
-    while( state.hasNext() ) {
-      UrlRewriteStepStatus flowStatus = UrlRewriteStepStatus.FAILURE;
-      while( state.hasNextCondition() ) {
-        step = state.nextCondition( status );
-        if( flowStatus == UrlRewriteStepStatus.FAILURE ) {
-          status = step.process( context );
-          switch( status ) {
-            case SUCCESS:
-              flowStatus = UrlRewriteStepStatus.SUCCESS;
-              continue;
-            case FINISHED:
-              return status;
-          }
-        }
-      }
-      status = processActions( context, state );
-      if( status != UrlRewriteStepStatus.SUCCESS ) {
-        return status;
-      }
-    }
-    return UrlRewriteStepStatus.SUCCESS;
-  }
-
-  private UrlRewriteStepStatus processActions( UrlRewriteContext context, UrlRewriteStepProcessorState state )
-      throws Exception {
-    UrlRewriteStepStatus flowStatus = UrlRewriteStepStatus.SUCCESS;
-    while( state.hasNextAction() ) {
-      if( flowStatus == UrlRewriteStepStatus.SUCCESS ) {
-        UrlRewriteStepStatus stepStatus = UrlRewriteStepStatus.SUCCESS;
-        UrlRewriteStepProcessorHolder step = state.nextAction( stepStatus );
-        stepStatus = step.process( context );
-        switch( stepStatus ) {
-          case FAILURE:
-            flowStatus = UrlRewriteStepStatus.FAILURE;
-            continue;
-          case FINISHED:
-            return stepStatus;
-        }
-      }
-    }
-    return flowStatus;
-  }
-
-  @Override
-  public void destroy() throws Exception {
-    destroy( processor );
-    if( descriptor instanceof UrlRewriteFlowDescriptor ) {
-      for( UrlRewriteStepProcessorHolder childProcessor : childProcessors ) {
-        destroy( childProcessor );
-      }
-    }
-  }
-
-  public void destroy( UrlRewriteStepProcessor processor ) {
-    if( processor != null ) {
-      try {
-        processor.destroy();
-      } catch( Exception e ) {
-        // Maybe it makes sense to throw exception
-        LOG.failedToDestroyRewriteStepProcessor( e );
-      }
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorState.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorState.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorState.java
deleted file mode 100644
index b8c4f7c..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteStepProcessorState.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.hadoop.gateway.filter.rewrite.impl;
-
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-
-import java.util.Iterator;
-
-class UrlRewriteStepProcessorState {
-
-  private UrlRewriteStepStatus status;
-  private UrlRewriteStepProcessorHolder next;
-  private Iterator<UrlRewriteStepProcessorHolder> steps;
-
-  UrlRewriteStepProcessorState( Iterator<UrlRewriteStepProcessorHolder> steps ) {
-    this.status = UrlRewriteStepStatus.SUCCESS;
-    this.next = null;
-    this.steps = steps;
-  }
-
-  private UrlRewriteStepProcessorHolder peek() {
-    if( next == null && steps.hasNext() ) {
-      next = steps.next();
-      return next;
-    } else if ( next != null ) {
-      return next;
-    } else {
-      return null;
-    }
-  }
-
-  public boolean hasNextCondition() {
-    UrlRewriteStepProcessorHolder curr = peek();
-    return curr != null && curr.isCondition();
-  }
-
-  public boolean hasNextAction() {
-    UrlRewriteStepProcessorHolder curr = peek();
-    return curr != null && curr.isAction();
-  }
-
-  private UrlRewriteStepProcessorHolder take( UrlRewriteStepStatus lastStatus ) {
-    UrlRewriteStepProcessorHolder step = peek();
-    status = lastStatus;
-    next = null;
-    return step;
-  }
-
-  public UrlRewriteStepProcessorHolder nextCondition( UrlRewriteStepStatus lastStatus ){
-    if( hasNextCondition() ) {
-      return take( lastStatus );
-    } else {
-      return null;
-    }
-  }
-
-  public UrlRewriteStepProcessorHolder nextAction( UrlRewriteStepStatus lastStatus ){
-    if( hasNextAction() ) {
-      return take( lastStatus );
-    } else {
-      return null;
-    }
-  }
-
-  public UrlRewriteStepStatus status(){
-    return status;
-  }
-
-  public boolean hasNext() {
-      return next != null || steps.hasNext();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteUtil.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteUtil.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteUtil.java
deleted file mode 100644
index 720b392..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/UrlRewriteUtil.java
+++ /dev/null
@@ -1,92 +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.hadoop.gateway.filter.rewrite.impl;
-
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
-
-import javax.activation.MimeType;
-
-public class UrlRewriteUtil {
-
-  public static String pickFirstRuleWithEqualsIgnoreCasePathMatch( UrlRewriteFilterContentDescriptor config, String name ) {
-    String rule = "*";
-    if( config != null && !config.getSelectors().isEmpty() && name != null ) {
-      rule = "";
-      for( UrlRewriteFilterPathDescriptor selector : config.getSelectors() ) {
-        if( name.equalsIgnoreCase( selector.path() ) ) {
-          if( selector instanceof UrlRewriteFilterApplyDescriptor ) {
-            rule = ((UrlRewriteFilterApplyDescriptor)selector).rule();
-          }
-          break;
-        }
-      }
-    }
-    return rule;
-  }
-
-  public static UrlRewriteFilterContentDescriptor getRewriteFilterConfig(
-      UrlRewriteRulesDescriptor config, String filterName, MimeType mimeType ) {
-    UrlRewriteFilterContentDescriptor filterContentConfig = null;
-    if( config != null ) {
-      UrlRewriteFilterDescriptor filterConfig = config.getFilter( filterName );
-      if( filterConfig != null ) {
-        filterContentConfig = filterConfig.getContent( mimeType );
-      }
-    }
-    return filterContentConfig;
-  }
-
-  public static String filterJavaScript( String inputValue, UrlRewriteFilterContentDescriptor config,
-      UrlRewriteFilterReader filterReader, UrlRewriteFilterPathDescriptor.Compiler<Pattern> regexCompiler ) {
-    StringBuffer tbuff = new StringBuffer();
-    StringBuffer sbuff = new StringBuffer();
-    sbuff.append( inputValue );
-    if( config != null && !config.getSelectors().isEmpty() ) {
-      for( UrlRewriteFilterPathDescriptor selector : config.getSelectors() ) {
-        if ( selector instanceof UrlRewriteFilterApplyDescriptor ) {
-          UrlRewriteFilterApplyDescriptor apply = (UrlRewriteFilterApplyDescriptor)selector;
-          Matcher matcher = apply.compiledPath( regexCompiler ).matcher( sbuff );
-          int index = 0;
-          while ( matcher.find() ) {
-            int start = matcher.start();
-            int end = matcher.end();
-            if ( start != -1 && end != -1 ) {
-              tbuff.append( sbuff, index, start );
-              String value = matcher.group();
-              value = filterReader.filterValueString( null, value, apply.rule() );
-              tbuff.append(value);
-              index = end;
-            }
-          }
-          tbuff.append( sbuff, index, sbuff.length() );
-          sbuff.setLength( 0 );
-          sbuff.append( tbuff );
-          tbuff.setLength( 0 );
-        }
-      }
-    }
-    return sbuff.toString();
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormFilterReader.java
deleted file mode 100644
index 57d11ce..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormFilterReader.java
+++ /dev/null
@@ -1,105 +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.hadoop.gateway.filter.rewrite.impl.form;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteUtil;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringWriter;
-
-public class FormFilterReader extends Reader {
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-
-  private int offset;
-  private StringWriter writer;
-  private StringBuffer buffer;
-  private Reader reader;
-  private FormReader parser;
-  private FormWriter generator;
-  private UrlRewriteFilterContentDescriptor config;
-
-  public FormFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException {
-    this.reader = reader;
-    this.config = config;
-    parser = new FormReader( reader );
-    writer = new StringWriter();
-    buffer = writer.getBuffer();
-    offset = 0;
-    generator = new FormWriter( writer );
-  }
-
-  @Override
-  public int read( char[] destBuffer, int destOffset, int destCount ) throws IOException {
-    int count = 0;
-    int available = buffer.length() - offset;
-
-    if( available == 0 ) {
-      FormPair pair = parser.getNextPair();
-      if( pair == null ) {
-        count = -1;
-      } else {
-        processPair();
-        available = buffer.length() - offset;
-      }
-    }
-
-    if( available > 0 ) {
-      count = Math.min( destCount, available );
-      buffer.getChars( offset, offset+count, destBuffer, destOffset );
-      offset += count;
-      if( offset == buffer.length() ) {
-        offset = 0;
-        buffer.setLength( 0 );
-      }
-    }
-
-    return count;
-  }
-
-  private void processPair() throws IOException {
-    FormPair pair = parser.getCurrentPair();
-    String name = pair.getName();
-    String value = pair.getValue();
-    String rule = UrlRewriteUtil.pickFirstRuleWithEqualsIgnoreCasePathMatch( config, name );
-    try {
-      value = filterValue( name, pair.getValue(), rule );
-      pair.setValue( value );
-    } catch( Exception e ) {
-      LOG.failedToFilterValue( pair.getValue(), rule, e );
-      // Write original value.
-    }
-    generator.writePair( pair );
-  }
-
-  protected String filterValue( String name, String value, String rule ) {
-    return value;
-  }
-
-  @Override
-  public void close() throws IOException {
-    writer.close();
-    reader.close();
-  }
-
-}
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormPair.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormPair.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormPair.java
deleted file mode 100644
index d39f8f0..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormPair.java
+++ /dev/null
@@ -1,51 +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.hadoop.gateway.filter.rewrite.impl.form;
-
-public class FormPair {
-
-  String name;
-  String value;
-
-  public FormPair() {
-    this.name = null;
-    this.value = null;
-  }
-
-  public FormPair( String name, String value ) {
-    this.name = name;
-    this.value = value;
-  }
-
-  public String getName() {
-    return name;
-  }
-
-  public void setName( String name ) {
-    this.name = name;
-  }
-
-  public String getValue() {
-    return value;
-  }
-
-  public void setValue( String value ) {
-    this.value = value;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormReader.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormReader.java
deleted file mode 100644
index d7d36ca..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormReader.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.hadoop.gateway.filter.rewrite.impl.form;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.UnsupportedEncodingException;
-import java.net.URLDecoder;
-
-public class FormReader {
-
-  private static final String DEFFAULT_FORM_ENCODING = "UTF-8";
-
-  private static final int DEFAULT_BUFFER_SIZE = 1024;
-
-  private Reader reader;
-  private FormPair current;
-  private StringBuilder buffer;
-  private int sepIndex;
-
-  public FormReader( Reader reader ) {
-    this.reader = reader;
-    this.current = null;
-    this.buffer = new StringBuilder( DEFAULT_BUFFER_SIZE );
-    this.sepIndex = -1;
-  }
-
-  public FormPair getNextPair() throws IOException {
-    while( true ) {
-      int c = reader.read();
-      switch( c ) {
-        case '=':
-          sepIndex = buffer.length();
-          break;
-        case '&':
-          // Ignore adjacent &s.
-          if( buffer.length() == 0 ) {
-            sepIndex = -1;
-            continue;
-          } else {
-            return createCurrentPair();
-          }
-        case -1:
-          // Ignore adjacent &s.
-          if( buffer.length() == 0 ) {
-            sepIndex = -1;
-            return null;
-          } else {
-            return createCurrentPair();
-          }
-        default:
-          buffer.append( (char)c );
-          break;
-      }
-    }
-  }
-
-  private FormPair createCurrentPair() throws UnsupportedEncodingException {
-    String name;
-    String value;
-    if( sepIndex >= 0 ) {
-      name = buffer.substring( 0, sepIndex );
-      value = buffer.substring( sepIndex );
-    } else {
-      name = buffer.toString();
-      value = "";
-    }
-    name = URLDecoder.decode( name, DEFFAULT_FORM_ENCODING );
-    value = URLDecoder.decode( value, DEFFAULT_FORM_ENCODING );
-    FormPair pair = new FormPair( name, value );
-    current = pair;
-    buffer.setLength( 0 );
-    sepIndex = -1;
-    return pair;
-  }
-
-  public FormPair getCurrentPair() {
-    return current;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormUrlRewriteFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormUrlRewriteFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormUrlRewriteFilterReader.java
deleted file mode 100644
index 70e2173..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormUrlRewriteFilterReader.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.hadoop.gateway.filter.rewrite.impl.form;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.net.URISyntaxException;
-
-public class FormUrlRewriteFilterReader extends FormFilterReader {
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-
-  private Resolver resolver;
-  private UrlRewriter rewriter;
-  private UrlRewriter.Direction direction;
-
-  public FormUrlRewriteFilterReader( Reader reader, UrlRewriter rewriter, Resolver resolver, UrlRewriter.Direction direction, UrlRewriteFilterContentDescriptor config  ) throws IOException {
-    super( reader, config );
-    this.resolver = resolver;
-    this.rewriter = rewriter;
-    this.direction = direction;
-  }
-
-  //TODO: Need to limit which values are attempted to be filtered by the name.
-  @Override
-  protected String filterValue( String name, String value, String rule ) {
-    try {
-      Template input = Parser.parseLiteral( value );
-      Template output = rewriter.rewrite( resolver, input, direction, rule );
-      value = output.getPattern();
-    } catch( URISyntaxException e ) {
-      LOG.failedToParseValueForUrlRewrite( value );
-    }
-    return value;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormUrlRewriteStreamFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormUrlRewriteStreamFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormUrlRewriteStreamFilter.java
deleted file mode 100644
index 35f8318..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormUrlRewriteStreamFilter.java
+++ /dev/null
@@ -1,59 +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.hadoop.gateway.filter.rewrite.impl.form;
-
-import org.apache.commons.io.input.ReaderInputStream;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStreamFilter;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-
-public class FormUrlRewriteStreamFilter implements UrlRewriteStreamFilter {
-
-  private static String[] TYPES = new String[]{ "application/x-www-form-urlencoded", "*/x-www-form-urlencoded" };
-  private static String[] NAMES = new String[]{ null };
-
-  @Override
-  public String[] getTypes() {
-    return TYPES;
-  }
-
-  @Override
-  public String[] getNames() {
-    return NAMES;
-  }
-
-  @Override
-  public InputStream filter(
-      InputStream stream,
-      String encoding,
-      UrlRewriter rewriter,
-      Resolver resolver,
-      UrlRewriter.Direction direction,
-      UrlRewriteFilterContentDescriptor config )
-          throws IOException {
-    return new ReaderInputStream(
-        new FormUrlRewriteFilterReader(
-            new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormWriter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormWriter.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormWriter.java
deleted file mode 100644
index c130d89..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/form/FormWriter.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.hadoop.gateway.filter.rewrite.impl.form;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.net.URLEncoder;
-
-public class FormWriter {
-
-  private static final String DEFFAULT_FORM_ENCODING = "UTF-8";
-
-  private Writer writer;
-  boolean first;
-
-  public FormWriter( Writer writer ) {
-    this.writer = writer;
-    this.first = true;
-  }
-
-  public void writePair( FormPair pair ) throws IOException {
-    if( first ) {
-      first = false;
-    } else {
-      writer.write( "&" );
-    }
-    writer.write( URLEncoder.encode( pair.getName(), DEFFAULT_FORM_ENCODING ) );
-    writer.write( "=" );
-    writer.write( URLEncoder.encode( pair.getValue(), DEFFAULT_FORM_ENCODING ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlFilterReader.java
deleted file mode 100644
index c61553e..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlFilterReader.java
+++ /dev/null
@@ -1,61 +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.hadoop.gateway.filter.rewrite.impl.html;
-
-import javax.xml.namespace.QName;
-import javax.xml.parsers.ParserConfigurationException;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-
-import java.io.IOException;
-import java.io.Reader;
-
-//map.put( "meta", buildTagPattern( ".*url\\s*=\\s*['\"]?(.*?)[;\\s'\"\\/>].*" ) );
-//map.put( "link", buildTagPattern( ".*href\\s*=\\s*['\"]?(.*?)['\"\\>].*" ) );
-//map.put( "a", buildTagPattern( ".*href\\s*=\\s*['\"]?(.*?)['\"\\>].*" ) );
-//map.put( "th", buildTagPattern( ".*window.document.location\\s*=\\s*['\"]?(.*?)['\"\\>].*" ) );
-//    assertMatch( pattern, "<meta HTTP-EQUIV=\"REFRESH\" content=\"0;url=dfshealth.jsp\"/>", "meta" );
-//String markup = "<link href=\"/static/org.apache.hadoop.css\" rel=\"stylesheet\" type=\"text/css\" >";
-//String markup = "<a href=\"dfsnodelist.jsp?whatNodes=DECOMMISSIONING\">";
-//String markup = "th class=headerASC onClick=\"window.document.location='/dfsnodelist.jsp?whatNodes=LIVE&sorter/field=name&sorter/order=DSC'\" title=\"sort on this column\">";
-
-public abstract class HtmlFilterReader extends HtmlFilterReaderBase {
-
-  public HtmlFilterReader( Reader reader ) throws IOException, ParserConfigurationException {
-    super( reader );
-  }
-
-  public HtmlFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException, ParserConfigurationException {
-    super( reader, config );
-  }
-
-  protected abstract String filterAttribute( String tagName, String attributeName, String attributeValue, String ruleName );
-
-  protected abstract String filterText( String tagName, String text, String ruleName );
-
-  @Override
-  protected final String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
-    return filterAttribute( elementName.getLocalPart(), attributeName.getLocalPart(), attributeValue, ruleName );
-  }
-
-  @Override
-  protected final String filterText( QName elementName, String text, String ruleName ) {
-    return filterText( elementName.getLocalPart(), text, ruleName );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlFilterReaderBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlFilterReaderBase.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlFilterReaderBase.java
deleted file mode 100644
index 6be7010..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlFilterReaderBase.java
+++ /dev/null
@@ -1,326 +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.hadoop.gateway.filter.rewrite.impl.html;
-
-import net.htmlparser.jericho.Attribute;
-import net.htmlparser.jericho.Attributes;
-import net.htmlparser.jericho.EndTag;
-import net.htmlparser.jericho.Segment;
-import net.htmlparser.jericho.StartTag;
-import net.htmlparser.jericho.StreamedSource;
-import net.htmlparser.jericho.Tag;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteFilterReader;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteUtil;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.util.XmlUtils;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import javax.xml.namespace.QName;
-import javax.xml.parsers.ParserConfigurationException;
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringWriter;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Stack;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public abstract class HtmlFilterReaderBase extends Reader implements UrlRewriteFilterReader {
-
-  private static final String SCRIPTTAG = "script";
-  private static final UrlRewriteFilterPathDescriptor.Compiler<Pattern> REGEX_COMPILER = new RegexCompiler();
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-
-  private Document document;
-  private Stack<Level> stack;
-  private Reader reader;
-  private StreamedSource parser;
-  private Iterator<Segment> iterator;
-  private int lastSegEnd;
-  private int offset;
-  private StringWriter writer;
-  private StringBuffer buffer;
-  private UrlRewriteFilterContentDescriptor config = null;
-
-  protected HtmlFilterReaderBase( Reader reader ) throws IOException, ParserConfigurationException {
-    this.reader = reader;
-    document = XmlUtils.createDocument( false );
-    stack = new Stack<Level>();
-    parser = new StreamedSource( reader );
-    iterator = parser.iterator();
-    writer = new StringWriter();
-    buffer = writer.getBuffer();
-    offset = 0;
-  }
-
-  protected HtmlFilterReaderBase( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException, ParserConfigurationException {
-    this(reader);
-    this.config = config;
-  }
-
-  protected abstract String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName );
-
-  protected abstract String filterText( QName elementName, String text, String ruleName );
-
-  @Override
-  public int read( char[] destBuffer, int destOffset, int destCount ) throws IOException {
-    int count = 0;
-    int available = buffer.length() - offset;
-
-    if( available == 0 ) {
-      if( iterator.hasNext() ) {
-        iterator.next();
-        processCurrentSegment();
-        available = buffer.length() - offset;
-      } else {
-        count = -1;
-      }
-    }
-
-    if( available > 0 ) {
-      count = Math.min( destCount, available );
-      buffer.getChars( offset, offset + count, destBuffer, destOffset );
-      offset += count;
-      if( offset == buffer.length() ) {
-        offset = 0;
-        buffer.setLength( 0 );
-      }
-    }
-
-    return count;
-  }
-
-  private void processCurrentSegment() {
-    Segment segment = parser.getCurrentSegment();
-    // If this tag is inside the previous tag (e.g. a server tag) then
-    // ignore it as it was already output along with the previous tag.
-    if( segment.getEnd() <= lastSegEnd ) {
-      return;
-    }
-    lastSegEnd = segment.getEnd();
-    if( segment instanceof Tag ) {
-      if( segment instanceof StartTag ) {
-        processStartTag( (StartTag)segment );
-      } else if ( segment instanceof EndTag ) {
-        processEndTag( (EndTag)segment );
-      } else {
-        writer.write( segment.toString() );
-      }
-    } else {
-      processText( segment );
-    }
-  }
-
-  private void processEndTag( EndTag tag ) {
-    while( !stack.isEmpty() ) {
-      Level popped = stack.pop();
-      if( popped.getTag().getName().equalsIgnoreCase( tag.getName() ) ) {
-        break;
-      }
-    }
-    writer.write( tag.toString() );
-  }
-
-  private void processStartTag( StartTag tag ) {
-    if( "<".equals( tag.getTagType().getStartDelimiter() ) ) {
-      Element e = document.createElement( tag.getNameSegment().toString() );
-      stack.push( new Level( tag ) );
-      writer.write( "<" );
-      writer.write( tag.getNameSegment().toString() );
-      Attributes attributes = tag.getAttributes();
-      if( !attributes.isEmpty() ) {
-        for( Attribute attribute : attributes ) {
-          processAttribute( attribute );
-        }
-      }
-      if( tag.toString().trim().endsWith( "/>" ) || tag.isEmptyElementTag() ) {
-        stack.pop();
-        writer.write( "/>" );
-      } else {
-        writer.write( ">" );
-      }
-    } else {
-      writer.write( tag.toString() );
-    }
-  }
-
-  private void processAttribute( Attribute attribute ) {
-    writer.write( " " );
-    writer.write( attribute.getName() );
-    if(attribute.hasValue()) {
-      /*
-       * non decoded value, return the raw value of the attribute as it appears
-       * in the source document, without decoding, see KNOX-791.
-       */
-      String inputValue = attribute.getValueSegment().toString();
-      String outputValue = inputValue;
-      try {
-        Level tag = stack.peek();
-        String name = getRuleName(inputValue);
-        outputValue = filterAttribute( tag.getQName(), tag.getQName( attribute.getName() ), inputValue, name );
-        if( outputValue == null ) {
-          outputValue = inputValue;
-        }
-      } catch ( Exception e ) {
-        LOG.failedToFilterAttribute( attribute.getName(), e );
-      }
-      writer.write( "=" );
-      writer.write( attribute.getQuoteChar() );
-      writer.write( outputValue );
-      writer.write( attribute.getQuoteChar() );
-    }
-  }
-
-  private String getRuleName(String inputValue) {
-    if( config != null && !config.getSelectors().isEmpty() ) {
-      for( UrlRewriteFilterPathDescriptor selector : config.getSelectors() ) {
-        if ( selector instanceof UrlRewriteFilterApplyDescriptor ) {
-          UrlRewriteFilterApplyDescriptor apply = (UrlRewriteFilterApplyDescriptor)selector;
-          Matcher matcher = apply.compiledPath( REGEX_COMPILER ).matcher( inputValue );
-            if (matcher.matches()) {
-              return apply.rule();
-            }
-          }
-        }
-      }
-      return null;
-    }
-
-  private void processText( Segment segment ) {
-    String inputValue = segment.toString();
-    String outputValue = inputValue;
-    try {
-      if( stack.isEmpty() ) {
-        // This can happen for whitespace outside of the root element.
-        //outputValue = filterText( null, inputValue );
-      } else {
-        String tagName = stack.peek().getTag().getName();
-        if (SCRIPTTAG.equals(tagName) && config != null && !config.getSelectors().isEmpty() ) {
-          // embedded javascript content
-          outputValue = UrlRewriteUtil.filterJavaScript( inputValue, config, this, REGEX_COMPILER );
-        } else {
-          outputValue = filterText( stack.peek().getQName(), inputValue, getRuleName(inputValue) );
-        }
-      }
-      if( outputValue == null ) {
-        outputValue = inputValue;
-      }
-    } catch ( Exception e ) {
-      LOG.failedToFilterValue( inputValue, null, e );
-    }
-    writer.write( outputValue );
-  }
-
-  @Override
-  public void close() throws IOException {
-    parser.close();
-    reader.close();
-    writer.close();
-    stack.clear();
-  }
-
-  private String getNamespace( String prefix ) {
-    String namespace = null;
-    for( Level level : stack ) {
-      namespace = level.getNamespace( prefix );
-      if( namespace != null ) {
-        break;
-      }
-    }
-    return namespace;
-  }
-
-  private static class Level {
-    private StartTag tag;
-    private QName name;
-    private Map<String,String> namespaces;
-
-    private Level( StartTag tag ) {
-      this.tag = tag;
-      this.name = null;
-      this.namespaces = null;
-    }
-
-    private StartTag getTag() {
-      return tag;
-    }
-
-    private QName getQName() {
-      if( name == null ) {
-        name = getQName( tag.getName() );
-      }
-      return name;
-    }
-
-    private String getNamespace( String prefix ) {
-      return getNamespaces().get( prefix );
-    }
-
-    private QName getQName( String name ) {
-      String prefix;
-      String local;
-      int colon = ( name == null ? -1 : name.indexOf( ':' ) );
-      if( colon < 0 ) {
-        prefix = "";
-        local = name;
-      } else {
-        prefix = name.substring( 0, colon );
-        local = ( colon + 1 < name.length() ? name.substring( colon + 1 ) : "" );
-      }
-      String namespace = getNamespace( prefix );
-      return new QName( namespace, local, prefix );
-    }
-
-    private Map<String,String> getNamespaces() {
-      if( namespaces == null ) {
-        namespaces = new HashMap<>();
-        parseNamespaces();
-      }
-      return namespaces;
-    }
-
-    private void parseNamespaces() {
-      Attributes attributes = tag.getAttributes();
-      if( attributes != null ) {
-        for( Attribute attribute : tag.getAttributes() ) {
-          String name = attribute.getName();
-          if( name.toLowerCase().startsWith( "xmlns" ) ) {
-            int colon = name.indexOf( ":", 5 );
-            String prefix;
-            if( colon <= 0 ) {
-              prefix = "";
-            } else {
-              prefix = name.substring( colon );
-            }
-            namespaces.put( prefix, attribute.getValue() );
-          }
-        }
-      }
-    }
-
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlImportFunctionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlImportFunctionDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlImportFunctionDescriptor.java
deleted file mode 100644
index e5bddfd..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlImportFunctionDescriptor.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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.filter.rewrite.impl.html;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-public class HtmlImportFunctionDescriptor implements UrlRewriteFunctionDescriptor<HtmlImportFunctionDescriptor> {
-
-  public static final String FUNCTION_NAME = "import";
-
-  @Override
-  public String name() {
-    return FUNCTION_NAME;
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessor.java
deleted file mode 100644
index 27d6ef5..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessor.java
+++ /dev/null
@@ -1,89 +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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.filter.rewrite.impl.html;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.FrontendFunctionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteFunctionProcessorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * This function enhances the 'frontend' function with the ability to add a prefix to the rewritten frontend portion
- * along with the '@import' literal. This is a workaround for the requirement to provide the ability to rewrite
- * a portion of html content that contains a tag like the following
- *
- * <head> <style type=\"text/css\">@import "pretty.css";</style></head>
- *
- * and needs to be rewritten to something like
- *
- * <head> <style type=\"text/css\">@import "http://localhost:8443/sandbox/service/pretty.css";</style></head>
- *
- * The rewrite rule could then contain the $import function that would delegate to the frontend function.
- *
- * If there are more than one params passed, the first one is used as a prefix to the value of the frontend function.
- *
- */
-public class HtmlImportFunctionProcessor implements UrlRewriteFunctionProcessor<HtmlImportFunctionDescriptor> {
-
-  private static final String IMPORT_LITERAL = "@import";
-
-  private UrlRewriteFunctionProcessor frontend;
-
-  @Override
-  public void initialize(UrlRewriteEnvironment environment, HtmlImportFunctionDescriptor descriptor) throws Exception {
-    UrlRewriteFunctionDescriptor frontendDescriptor = UrlRewriteFunctionDescriptorFactory.create(FrontendFunctionDescriptor.FUNCTION_NAME);
-    frontend = UrlRewriteFunctionProcessorFactory.create(FrontendFunctionDescriptor.FUNCTION_NAME, frontendDescriptor);
-    frontend.initialize(environment, frontendDescriptor);
-  }
-
-  @Override
-  public void destroy() throws Exception {
-    frontend.destroy();
-  }
-
-  @Override
-  public List<String> resolve(UrlRewriteContext context, List<String> parameters) throws Exception {
-    String prefix = "";
-    if ( parameters != null && parameters.size() > 1 ) {
-      prefix = parameters.get(0);
-      parameters = parameters.subList(1, parameters.size());
-    }
-    List<String> frontendValues = frontend.resolve(context, parameters);
-    StringBuffer buffer = new StringBuffer(IMPORT_LITERAL);
-    buffer.append(" ");
-    buffer.append(prefix);
-    if ( frontendValues != null && frontendValues.size() > 0 ) {
-      for ( String value : frontendValues ) {
-        buffer.append(value);
-      }
-    }
-    return Arrays.asList(buffer.toString());
-  }
-
-  @Override
-  public String name() {
-    return HtmlImportFunctionDescriptor.FUNCTION_NAME;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlPrefixDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlPrefixDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlPrefixDescriptor.java
deleted file mode 100644
index f0386a1..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlPrefixDescriptor.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package org.apache.hadoop.gateway.filter.rewrite.impl.html;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with this
- * work for additional information regarding copyright ownership.  The ASF
- * licenses this file to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-/**
- * {@link UrlRewriteFunctionDescriptor} for the variable {@link
- * HtmlPrefixDescriptor#FUNCTION_NAME}
- *
- * @since 0.14.0
- */
-public class HtmlPrefixDescriptor
-    implements UrlRewriteFunctionDescriptor<HtmlPrefixDescriptor> {
-
-  /**
-   * variable name used in rewrite.xml
-   */
-  public static final String FUNCTION_NAME = "prefix";
-
-  /**
-   * Create an instance
-   */
-  public HtmlPrefixDescriptor() {
-    super();
-  }
-
-  @Override
-  public String name() {
-    return FUNCTION_NAME;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlPrefixProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlPrefixProcessor.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlPrefixProcessor.java
deleted file mode 100644
index 8ded069..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlPrefixProcessor.java
+++ /dev/null
@@ -1,104 +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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * 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.hadoop.gateway.filter.rewrite.impl.html;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.FrontendFunctionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteFunctionProcessorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * This function enhances the 'frontend' function with the ability to add a
- * prefix to the rewritten frontend portion along with the literals
- * provided as an argument.
- * <p>
- * <div ng-include src=\"'components/navbar/navbar.html?v=1498928142479'\"></div>
- * <p>
- * and needs to be rewritten to something like
- * <p>
- * <div ng-include src=\"'http://localhost:8443/sandbox/service/components/navbar/navbar.html?v=1498928142479'\"></div>
- * <p>
- * The rewrite rule could then contain the $prefix function that would delegate
- * to the frontend function.
- * <p>
- * The parameter to the function would be the symbol used as a prefix.
- */
-
-public class HtmlPrefixProcessor
-    implements UrlRewriteFunctionProcessor<HtmlPrefixDescriptor> {
-
-  private UrlRewriteFunctionProcessor frontend;
-
-  /**
-   * Create an instance
-   */
-  public HtmlPrefixProcessor() {
-    super();
-  }
-
-  @Override
-  public void initialize(final UrlRewriteEnvironment environment,
-      final HtmlPrefixDescriptor descriptor) throws Exception {
-
-    final UrlRewriteFunctionDescriptor frontendDescriptor = UrlRewriteFunctionDescriptorFactory
-        .create(FrontendFunctionDescriptor.FUNCTION_NAME);
-
-    frontend = UrlRewriteFunctionProcessorFactory
-        .create(FrontendFunctionDescriptor.FUNCTION_NAME, frontendDescriptor);
-
-    frontend.initialize(environment, frontendDescriptor);
-  }
-
-  @Override
-  public String name() {
-    return HtmlPrefixDescriptor.FUNCTION_NAME;
-  }
-
-  @Override
-  public void destroy() throws Exception {
-    frontend.destroy();
-  }
-
-  @Override
-  public List<String> resolve(UrlRewriteContext context,
-      List<String> parameters) throws Exception {
-    String prefix = "";
-
-    if ((parameters != null) && (parameters.size() > 1)) {
-      prefix = parameters.get(0);
-      parameters = parameters.subList(1, parameters.size());
-    }
-
-    final List<String> frontendValues = frontend.resolve(context, parameters);
-
-    final StringBuffer buffer = new StringBuffer();
-    buffer.append(prefix);
-    if (frontendValues != null && frontendValues.size() > 0) {
-      for (final String value : frontendValues) {
-        buffer.append(value);
-      }
-    }
-
-    return Arrays.asList(buffer.toString());
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlUrlRewriteFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlUrlRewriteFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlUrlRewriteFilterReader.java
deleted file mode 100644
index 76b7c38..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlUrlRewriteFilterReader.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.hadoop.gateway.filter.rewrite.impl.html;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import javax.xml.parsers.ParserConfigurationException;
-import java.io.IOException;
-import java.io.Reader;
-import java.net.URISyntaxException;
-
-public class HtmlUrlRewriteFilterReader extends HtmlFilterReader {
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-  
-  private Resolver resolver;
-  private UrlRewriter rewriter;
-  private UrlRewriter.Direction direction;
-
-  public HtmlUrlRewriteFilterReader( Reader reader, UrlRewriter rewriter, Resolver resolver, UrlRewriter.Direction direction, UrlRewriteFilterContentDescriptor config )
-      throws IOException, ParserConfigurationException {
-    super( reader, config );
-    this.resolver = resolver;
-    this.rewriter = rewriter;
-    this.direction = direction;
-  }
-
-  //TODO: Need to limit which values are attempted to be filtered by the name.
-  @Override
-  public String filterValueString( String name, String value, String rule ) {
-    try {
-      Template input = Parser.parseLiteral( value );
-      Template output = rewriter.rewrite( resolver, input, direction, rule );
-      if( output != null ) {
-        value = output.getPattern();
-      }
-    } catch( URISyntaxException e ) {
-      LOG.failedToParseValueForUrlRewrite( value );
-    }
-    return value;
-  }
-
-  @Override
-  protected String filterAttribute( String tagName, String attributeName, String attributeValue, String ruleName ) {
-    return filterValueString( attributeName, attributeValue, ruleName );
-  }
-
-  @Override
-  protected String filterText( String tagName, String text, String ruleName ) {
-    return filterValueString( tagName, text, ruleName );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlUrlRewriteStreamFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlUrlRewriteStreamFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlUrlRewriteStreamFilter.java
deleted file mode 100644
index b51a328..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlUrlRewriteStreamFilter.java
+++ /dev/null
@@ -1,64 +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.hadoop.gateway.filter.rewrite.impl.html;
-
-import org.apache.commons.io.input.ReaderInputStream;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStreamFilter;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-
-import javax.xml.parsers.ParserConfigurationException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-
-public class HtmlUrlRewriteStreamFilter implements UrlRewriteStreamFilter {
-
-  private static String[] TYPES = new String[]{ "application/html", "text/html", "*/html" };
-  private static String[] NAMES = new String[]{ null };
-
-  @Override
-  public String[] getTypes() {
-    return TYPES;
-  }
-
-  @Override
-  public String[] getNames() {
-    return NAMES;
-  }
-
-  @Override
-  public InputStream filter(
-      InputStream stream,
-      String encoding,
-      UrlRewriter rewriter,
-      Resolver resolver,
-      UrlRewriter.Direction direction,
-      UrlRewriteFilterContentDescriptor config )
-          throws IOException {
-    try {
-      return new ReaderInputStream(
-          new HtmlUrlRewriteFilterReader(
-              new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
-    } catch( ParserConfigurationException e ) {
-      throw new IOException( e );
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReader.java
deleted file mode 100644
index 46e630a..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReader.java
+++ /dev/null
@@ -1,91 +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.hadoop.gateway.filter.rewrite.impl.javascript;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteFilterReader;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteUtil;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringWriter;
-import java.util.regex.Pattern;
-
-public abstract class JavaScriptFilterReader extends Reader implements UrlRewriteFilterReader {
-
-  private static final UrlRewriteFilterPathDescriptor.Compiler<Pattern> REGEX_COMPILER = new RegexCompiler();
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-
-  private BufferedReader reader;
-  private int offset;
-  private StringWriter writer;
-  private StringBuffer buffer;
-  private UrlRewriteFilterContentDescriptor config;
-
-  protected JavaScriptFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException {
-    this.reader = new BufferedReader( reader );
-    this.config = config;
-    writer = new StringWriter();
-    buffer = writer.getBuffer();
-    offset = 0;
-  }
-
-  @Override
-  public abstract String filterValueString( String name, String value, String rule );
-
-  @Override
-  public int read( char[] destBuffer, int destOffset, int destCount ) throws IOException {
-    int count = 0;
-    int available = buffer.length() - offset;
-    String cbuff;
-    if( available == 0 ) {
-      cbuff = reader.readLine();
-      if( cbuff != null ) {
-        count = cbuff.length();
-        writer.write( UrlRewriteUtil.filterJavaScript( cbuff, config, this, REGEX_COMPILER ) );
-        writer.write( '\n' );
-        available = buffer.length() - offset;
-      } else {
-        count = -1;
-      }
-    }
-
-    if( available > 0 ) {
-      count = Math.min( destCount, available );
-      buffer.getChars( offset, offset + count, destBuffer, destOffset );
-      offset += count;
-      if( offset == buffer.length() ) {
-        offset = 0;
-        buffer.setLength( 0 );
-      }
-    }
-
-    return count;
-  }
-
-  @Override
-  public void close() throws IOException {
-    reader.close();
-    writer.close();
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteFilterReader.java
deleted file mode 100644
index af9a36f..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteFilterReader.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.hadoop.gateway.filter.rewrite.impl.javascript;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.net.URISyntaxException;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-public class JavaScriptUrlRewriteFilterReader extends JavaScriptFilterReader {
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-
-  private Resolver resolver;
-  private UrlRewriter rewriter;
-  private UrlRewriter.Direction direction;
-
-  public JavaScriptUrlRewriteFilterReader( Reader reader, UrlRewriter rewriter, Resolver resolver, UrlRewriter.Direction direction, UrlRewriteFilterContentDescriptor config )
-      throws IOException {
-    super( reader, config );
-    this.resolver = resolver;
-    this.rewriter = rewriter;
-    this.direction = direction;
-  }
-
-  @Override
-  public String filterValueString( String name, String value, String rule ) {
-    try {
-      Template input = Parser.parseLiteral( value );
-      Template output = rewriter.rewrite( resolver, input, direction, rule );
-      if( output != null ) {
-        value = output.getPattern();
-      }
-    } catch( URISyntaxException e ) {
-      LOG.failedToParseValueForUrlRewrite( value );
-    }
-    return value;
-  }
-
-}


[63/64] knox git commit: KNOX-998 - Some more refactoring, making sure all the Unit Tests run and build passes !

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/ambariui/2.2.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/ambariui/2.2.0/service.xml b/gateway-service-definitions/src/main/resources/services/ambariui/2.2.0/service.xml
index ab4ab2b..c6135ae 100644
--- a/gateway-service-definitions/src/main/resources/services/ambariui/2.2.0/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/ambariui/2.2.0/service.xml
@@ -87,6 +87,6 @@
 
         <!-- No need to rewrite Slider View -->
     </routes>
-    <dispatch classname="org.apache.hadoop.gateway.dispatch.PassAllHeadersNoEncodingDispatch"/>
+    <dispatch classname="org.apache.knox.gateway.dispatch.PassAllHeadersNoEncodingDispatch"/>
 </service>
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/atlas-api/0.8.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/atlas-api/0.8.0/service.xml b/gateway-service-definitions/src/main/resources/services/atlas-api/0.8.0/service.xml
index 0711dea..3ae7b24 100644
--- a/gateway-service-definitions/src/main/resources/services/atlas-api/0.8.0/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/atlas-api/0.8.0/service.xml
@@ -28,5 +28,5 @@
         <route path="/atlas/api/**"/>
     </routes>
 
-    <dispatch classname="org.apache.hadoop.gateway.dispatch.PassAllHeadersDispatch"/>
+    <dispatch classname="org.apache.knox.gateway.dispatch.PassAllHeadersDispatch"/>
 </service>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/atlas/0.8.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/atlas/0.8.0/service.xml b/gateway-service-definitions/src/main/resources/services/atlas/0.8.0/service.xml
index ec1376c..6d99f30 100644
--- a/gateway-service-definitions/src/main/resources/services/atlas/0.8.0/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/atlas/0.8.0/service.xml
@@ -46,6 +46,6 @@
 
     </routes>
 
-    <dispatch classname="org.apache.hadoop.gateway.dispatch.PassAllHeadersDispatch"/>
+    <dispatch classname="org.apache.knox.gateway.dispatch.PassAllHeadersDispatch"/>
 
 </service>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/hbase/0.98.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/hbase/0.98.0/service.xml b/gateway-service-definitions/src/main/resources/services/hbase/0.98.0/service.xml
index 181b536..e4e2926 100644
--- a/gateway-service-definitions/src/main/resources/services/hbase/0.98.0/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/hbase/0.98.0/service.xml
@@ -29,7 +29,7 @@
             <rewrite apply="WEBHBASE/webhbase/regions/outbound" to="response.body"/>
         </route>
     </routes>
-    <dispatch classname="org.apache.hadoop.gateway.hbase.HBaseDispatch"/>
+    <dispatch classname="org.apache.knox.gateway.hbase.HBaseDispatch"/>
     <testURLs>
         <testURL>/hbase/version</testURL>
         <testURL>/hbase/version/cluster</testURL>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/hbaseui/1.1.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/hbaseui/1.1.0/service.xml b/gateway-service-definitions/src/main/resources/services/hbaseui/1.1.0/service.xml
index 7a7de1e..09e78ea 100644
--- a/gateway-service-definitions/src/main/resources/services/hbaseui/1.1.0/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/hbaseui/1.1.0/service.xml
@@ -65,5 +65,5 @@
             <rewrite apply="HBASEUI/hbase/outbound/configuration" to="response.body"/>
         </route>
     </routes>
-    <dispatch classname="org.apache.hadoop.gateway.hbase.HBaseDispatch"/>
+    <dispatch classname="org.apache.knox.gateway.hbase.HBaseDispatch"/>
 </service>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/hdfsui/2.7.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/hdfsui/2.7.0/service.xml b/gateway-service-definitions/src/main/resources/services/hdfsui/2.7.0/service.xml
index f33aab6..ac075eb 100644
--- a/gateway-service-definitions/src/main/resources/services/hdfsui/2.7.0/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/hdfsui/2.7.0/service.xml
@@ -35,5 +35,5 @@
 
 
     </routes>
-    <dispatch classname="org.apache.hadoop.gateway.hdfs.dispatch.HdfsHttpClientDispatch" ha-classname="org.apache.hadoop.gateway.hdfs.dispatch.WebHdfsHaDispatch"/>
+    <dispatch classname="org.apache.knox.gateway.hdfs.dispatch.HdfsHttpClientDispatch" ha-classname="org.apache.knox.gateway.hdfs.dispatch.WebHdfsHaDispatch"/>
 </service>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/hive/0.13.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/hive/0.13.0/service.xml b/gateway-service-definitions/src/main/resources/services/hive/0.13.0/service.xml
index 3ea5b20..26875ff 100644
--- a/gateway-service-definitions/src/main/resources/services/hive/0.13.0/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/hive/0.13.0/service.xml
@@ -18,5 +18,5 @@
     <routes>
         <route path="/hive"/>
     </routes>
-    <dispatch classname="org.apache.hadoop.gateway.hive.HiveDispatch" ha-classname="org.apache.hadoop.gateway.hive.HiveHaDispatch"/>
+    <dispatch classname="org.apache.knox.gateway.hive.HiveDispatch" ha-classname="org.apache.knox.gateway.hive.HiveHaDispatch"/>
 </service>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/ranger/0.5.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/ranger/0.5.0/service.xml b/gateway-service-definitions/src/main/resources/services/ranger/0.5.0/service.xml
index 97afc3c..09b3a96 100644
--- a/gateway-service-definitions/src/main/resources/services/ranger/0.5.0/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/ranger/0.5.0/service.xml
@@ -24,6 +24,6 @@
     <routes>
         <route path="/ranger/service/public/**"/>
     </routes>
-    <dispatch classname="org.apache.hadoop.gateway.dispatch.PassAllHeadersDispatch"/>
+    <dispatch classname="org.apache.knox.gateway.dispatch.PassAllHeadersDispatch"/>
 </service>
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/rangerui/0.5.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/rangerui/0.5.0/service.xml b/gateway-service-definitions/src/main/resources/services/rangerui/0.5.0/service.xml
index 852e8fd..2cfbc82 100644
--- a/gateway-service-definitions/src/main/resources/services/rangerui/0.5.0/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/rangerui/0.5.0/service.xml
@@ -38,5 +38,5 @@
             <rewrite apply="RANGERUI/rangerui/outbound/headers" to="response.headers"/>
         </route>
     </routes>
-    <dispatch classname="org.apache.hadoop.gateway.dispatch.PassAllHeadersDispatch"/>
+    <dispatch classname="org.apache.knox.gateway.dispatch.PassAllHeadersDispatch"/>
 </service>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/solr/5.5.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/solr/5.5.0/service.xml b/gateway-service-definitions/src/main/resources/services/solr/5.5.0/service.xml
index e1837c3..9dfeff5 100644
--- a/gateway-service-definitions/src/main/resources/services/solr/5.5.0/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/solr/5.5.0/service.xml
@@ -27,5 +27,5 @@
              <rewrite apply="SOLRAPI/solr/inbound/query" to="request.url"/>
         </route>
     </routes>
-     <dispatch classname="org.apache.hadoop.gateway.dispatch.PassAllHeadersDispatch"/>
+     <dispatch classname="org.apache.knox.gateway.dispatch.PassAllHeadersDispatch"/>
 </service>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/storm/0.9.3/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/storm/0.9.3/service.xml b/gateway-service-definitions/src/main/resources/services/storm/0.9.3/service.xml
index c5f388e..4da358c 100644
--- a/gateway-service-definitions/src/main/resources/services/storm/0.9.3/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/storm/0.9.3/service.xml
@@ -24,7 +24,7 @@
             <rewrite apply="STORM/storm/logs/outbound" to="response.body"/>
         </route>
     </routes>
-    <dispatch classname="org.apache.hadoop.gateway.storm.StormDispatch"/>
+    <dispatch classname="org.apache.knox.gateway.storm.StormDispatch"/>
     <testURLs>
         <testURL>/storm/api/v1/cluster/configuration</testURL>
         <testURL>/storm/api/v1/cluster/summary</testURL>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/webhdfs/2.4.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/webhdfs/2.4.0/service.xml b/gateway-service-definitions/src/main/resources/services/webhdfs/2.4.0/service.xml
index 9d39a32..f4224b9 100644
--- a/gateway-service-definitions/src/main/resources/services/webhdfs/2.4.0/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/webhdfs/2.4.0/service.xml
@@ -36,7 +36,7 @@
             <dispatch contributor-name="http-client" />
         </route>
     </routes>
-    <dispatch classname="org.apache.hadoop.gateway.hdfs.dispatch.HdfsHttpClientDispatch" ha-classname="org.apache.hadoop.gateway.hdfs.dispatch.WebHdfsHaDispatch"/>
+    <dispatch classname="org.apache.knox.gateway.hdfs.dispatch.HdfsHttpClientDispatch" ha-classname="org.apache.knox.gateway.hdfs.dispatch.WebHdfsHaDispatch"/>
     <testURLs>
         <testURL>/webhdfs/v1/?op=LISTSTATUS</testURL>
     </testURLs>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/yarn-rm/2.5.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/yarn-rm/2.5.0/service.xml b/gateway-service-definitions/src/main/resources/services/yarn-rm/2.5.0/service.xml
index beb7967..e7c721d 100644
--- a/gateway-service-definitions/src/main/resources/services/yarn-rm/2.5.0/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/yarn-rm/2.5.0/service.xml
@@ -56,5 +56,5 @@
         <testURL>/resourcemanager/v1/cluster/metrics</testURL>
         <testURL>/resourcemanager/v1/cluster/apps</testURL>
     </testURLs>
-    <dispatch classname="org.apache.hadoop.gateway.dispatch.DefaultDispatch" ha-classname="org.apache.hadoop.gateway.rm.dispatch.RMHaDispatch"/>
+    <dispatch classname="org.apache.knox.gateway.dispatch.DefaultDispatch" ha-classname="org.apache.knox.gateway.rm.dispatch.RMHaDispatch"/>
 </service>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/yarnui/2.7.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/yarnui/2.7.0/service.xml b/gateway-service-definitions/src/main/resources/services/yarnui/2.7.0/service.xml
index 798fd42..cf2109d 100644
--- a/gateway-service-definitions/src/main/resources/services/yarnui/2.7.0/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/yarnui/2.7.0/service.xml
@@ -55,6 +55,6 @@
             <rewrite apply="YARNUI/yarn/outbound/configuration" to="response.body"/>
         </route>
     </routes>
-    <dispatch classname="org.apache.hadoop.gateway.dispatch.DefaultDispatch" ha-classname="org.apache.hadoop.gateway.rm.dispatch.RMUIHaDispatch"/>
+    <dispatch classname="org.apache.knox.gateway.dispatch.DefaultDispatch" ha-classname="org.apache.knox.gateway.rm.dispatch.RMUIHaDispatch"/>
 
 </service>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/zeppelinui/0.6.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/zeppelinui/0.6.0/service.xml b/gateway-service-definitions/src/main/resources/services/zeppelinui/0.6.0/service.xml
index 4b692fe..fcf5cad 100644
--- a/gateway-service-definitions/src/main/resources/services/zeppelinui/0.6.0/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/zeppelinui/0.6.0/service.xml
@@ -83,5 +83,5 @@
     </route>
 
   </routes>
-  <dispatch classname="org.apache.hadoop.gateway.dispatch.PassAllHeadersDispatch"/>
+  <dispatch classname="org.apache.knox.gateway.dispatch.PassAllHeadersDispatch"/>
 </service>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/test/java/org/apache/knox/gateway/service/definition/ServiceDefinitionTest.java
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/test/java/org/apache/knox/gateway/service/definition/ServiceDefinitionTest.java b/gateway-service-definitions/src/test/java/org/apache/knox/gateway/service/definition/ServiceDefinitionTest.java
index 8e21a7f..60f2d70 100644
--- a/gateway-service-definitions/src/test/java/org/apache/knox/gateway/service/definition/ServiceDefinitionTest.java
+++ b/gateway-service-definitions/src/test/java/org/apache/knox/gateway/service/definition/ServiceDefinitionTest.java
@@ -40,7 +40,7 @@ public class ServiceDefinitionTest {
     assertEquals("1.0.0", definition.getVersion());
     assertEquals("custom-client", definition.getDispatch().getContributorName());
     assertEquals("ha-client", definition.getDispatch().getHaContributorName());
-    assertEquals("org.apache.hadoop.gateway.MockHttpClientFactory", definition.getDispatch().getHttpClientFactory());
+    assertEquals("org.apache.knox.gateway.MockHttpClientFactory", definition.getDispatch().getHttpClientFactory());
     List<Policy> policies = definition.getPolicies();
     assertEquals(5, policies.size());
     String[] policyOrder = new String[]{"webappsec", "authentication", "rewrite", "identity-assertion", "authorization"};
@@ -79,12 +79,12 @@ public class ServiceDefinitionTest {
     url = ClassLoader.getSystemResource("services/hbase/0.98.0/service.xml");
     definition = (ServiceDefinition) unmarshaller.unmarshal(url.openStream());
     assertNotNull(definition.getDispatch());
-    assertEquals("org.apache.hadoop.gateway.hbase.HBaseDispatch", definition.getDispatch().getClassName());
+    assertEquals("org.apache.knox.gateway.hbase.HBaseDispatch", definition.getDispatch().getClassName());
     url = ClassLoader.getSystemResource("services/webhdfs/2.4.0/service.xml");
     definition = (ServiceDefinition) unmarshaller.unmarshal(url.openStream());
     assertNotNull(definition.getDispatch());
-    assertEquals("org.apache.hadoop.gateway.hdfs.dispatch.HdfsHttpClientDispatch", definition.getDispatch().getClassName());
-    assertEquals("org.apache.hadoop.gateway.hdfs.dispatch.WebHdfsHaDispatch", definition.getDispatch().getHaClassName());
+    assertEquals("org.apache.knox.gateway.hdfs.dispatch.HdfsHttpClientDispatch", definition.getDispatch().getClassName());
+    assertEquals("org.apache.knox.gateway.hdfs.dispatch.WebHdfsHaDispatch", definition.getDispatch().getHaClassName());
   }
 
 }

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/test/resources/services/foo/1.0.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/test/resources/services/foo/1.0.0/service.xml b/gateway-service-definitions/src/test/resources/services/foo/1.0.0/service.xml
index ab1d966..75ed85d 100644
--- a/gateway-service-definitions/src/test/resources/services/foo/1.0.0/service.xml
+++ b/gateway-service-definitions/src/test/resources/services/foo/1.0.0/service.xml
@@ -35,7 +35,7 @@
             <dispatch contributor-name="http-client" />
         </route>
     </routes>
-    <dispatch contributor-name="custom-client" ha-contributor-name="ha-client" http-client-factory="org.apache.hadoop.gateway.MockHttpClientFactory"/>
+    <dispatch contributor-name="custom-client" ha-contributor-name="ha-client" http-client-factory="org.apache.knox.gateway.MockHttpClientFactory"/>
     <testURLs>
         <testURL>/foo/version</testURL>
         <testURL>/foo/bar/status</testURL>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-health/src/main/java/org/apache/knox/gateway/service/health/HealthServiceMessages.java
----------------------------------------------------------------------
diff --git a/gateway-service-health/src/main/java/org/apache/knox/gateway/service/health/HealthServiceMessages.java b/gateway-service-health/src/main/java/org/apache/knox/gateway/service/health/HealthServiceMessages.java
index 847d45c..e242858 100644
--- a/gateway-service-health/src/main/java/org/apache/knox/gateway/service/health/HealthServiceMessages.java
+++ b/gateway-service-health/src/main/java/org/apache/knox/gateway/service/health/HealthServiceMessages.java
@@ -22,7 +22,7 @@ import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 import org.apache.knox.gateway.i18n.messages.StackTrace;
 
-@Messages(logger = "org.apache.hadoop.gateway.service.health")
+@Messages(logger = "org.apache.knox.gateway.service.health")
 public interface HealthServiceMessages {
   @Message(level = MessageLevel.INFO, text = "{0}")
   void basicInfo(String original);

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-health/src/main/java/org/apache/knox/gateway/service/health/deploy/HealthServiceDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-service-health/src/main/java/org/apache/knox/gateway/service/health/deploy/HealthServiceDeploymentContributor.java b/gateway-service-health/src/main/java/org/apache/knox/gateway/service/health/deploy/HealthServiceDeploymentContributor.java
index f29bb02..a843755 100644
--- a/gateway-service-health/src/main/java/org/apache/knox/gateway/service/health/deploy/HealthServiceDeploymentContributor.java
+++ b/gateway-service-health/src/main/java/org/apache/knox/gateway/service/health/deploy/HealthServiceDeploymentContributor.java
@@ -42,7 +42,7 @@ public class HealthServiceDeploymentContributor extends JerseyServiceDeploymentC
    */
   @Override
   protected String[] getPackages() {
-    return new String[]{"org.apache.hadoop.gateway.service.health"};
+    return new String[]{"org.apache.knox.gateway.service.health"};
   }
 
   /* (non-Javadoc)

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-knoxsso/src/main/java/org/apache/knox/gateway/service/knoxsso/KnoxSSOMessages.java
----------------------------------------------------------------------
diff --git a/gateway-service-knoxsso/src/main/java/org/apache/knox/gateway/service/knoxsso/KnoxSSOMessages.java b/gateway-service-knoxsso/src/main/java/org/apache/knox/gateway/service/knoxsso/KnoxSSOMessages.java
index 13ca1a7..553f614 100644
--- a/gateway-service-knoxsso/src/main/java/org/apache/knox/gateway/service/knoxsso/KnoxSSOMessages.java
+++ b/gateway-service-knoxsso/src/main/java/org/apache/knox/gateway/service/knoxsso/KnoxSSOMessages.java
@@ -22,7 +22,7 @@ import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 import org.apache.knox.gateway.i18n.messages.StackTrace;
 
-@Messages(logger="org.apache.hadoop.gateway.service.knoxsso")
+@Messages(logger="org.apache.knox.gateway.service.knoxsso")
 public interface KnoxSSOMessages {
   @Message( level = MessageLevel.INFO, text = "About to redirect to original URL: {0}")
   void aboutToRedirectToOriginal(String original);

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-knoxsso/src/main/java/org/apache/knox/gateway/service/knoxsso/deploy/KnoxSSOServiceDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-service-knoxsso/src/main/java/org/apache/knox/gateway/service/knoxsso/deploy/KnoxSSOServiceDeploymentContributor.java b/gateway-service-knoxsso/src/main/java/org/apache/knox/gateway/service/knoxsso/deploy/KnoxSSOServiceDeploymentContributor.java
index 37fe6f2..5bcd087 100644
--- a/gateway-service-knoxsso/src/main/java/org/apache/knox/gateway/service/knoxsso/deploy/KnoxSSOServiceDeploymentContributor.java
+++ b/gateway-service-knoxsso/src/main/java/org/apache/knox/gateway/service/knoxsso/deploy/KnoxSSOServiceDeploymentContributor.java
@@ -43,7 +43,7 @@ public class KnoxSSOServiceDeploymentContributor extends
    */
   @Override
   protected String[] getPackages() {
-    return new String[]{ "org.apache.hadoop.gateway.service.knoxsso" };
+    return new String[]{ "org.apache.knox.gateway.service.knoxsso" };
   }
 
   /* (non-Javadoc)

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-knoxssout/src/main/java/org/apache/knox/gateway/service/knoxsso/KnoxSSOutMessages.java
----------------------------------------------------------------------
diff --git a/gateway-service-knoxssout/src/main/java/org/apache/knox/gateway/service/knoxsso/KnoxSSOutMessages.java b/gateway-service-knoxssout/src/main/java/org/apache/knox/gateway/service/knoxsso/KnoxSSOutMessages.java
index 4b08827..076dc3e 100644
--- a/gateway-service-knoxssout/src/main/java/org/apache/knox/gateway/service/knoxsso/KnoxSSOutMessages.java
+++ b/gateway-service-knoxssout/src/main/java/org/apache/knox/gateway/service/knoxsso/KnoxSSOutMessages.java
@@ -21,7 +21,7 @@ import org.apache.knox.gateway.i18n.messages.Message;
 import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 
-@Messages(logger="org.apache.hadoop.gateway.service.knoxsso")
+@Messages(logger="org.apache.knox.gateway.service.knoxsso")
 public interface KnoxSSOutMessages {
   @Message( level = MessageLevel.INFO, text = "There was a problem determining the SSO cookie domain - using default domain.")
   void problemWithCookieDomainUsingDefault();

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-knoxssout/src/main/java/org/apache/knox/gateway/service/knoxsso/deploy/KnoxSSOutServiceDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-service-knoxssout/src/main/java/org/apache/knox/gateway/service/knoxsso/deploy/KnoxSSOutServiceDeploymentContributor.java b/gateway-service-knoxssout/src/main/java/org/apache/knox/gateway/service/knoxsso/deploy/KnoxSSOutServiceDeploymentContributor.java
index 4187f32..de66904 100644
--- a/gateway-service-knoxssout/src/main/java/org/apache/knox/gateway/service/knoxsso/deploy/KnoxSSOutServiceDeploymentContributor.java
+++ b/gateway-service-knoxssout/src/main/java/org/apache/knox/gateway/service/knoxsso/deploy/KnoxSSOutServiceDeploymentContributor.java
@@ -42,7 +42,7 @@ public class KnoxSSOutServiceDeploymentContributor extends JerseyServiceDeployme
    */
   @Override
   protected String[] getPackages() {
-    return new String[]{ "org.apache.hadoop.gateway.service.knoxsso" };
+    return new String[]{ "org.apache.knox.gateway.service.knoxsso" };
   }
 
   /* (non-Javadoc)

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-knoxtoken/src/main/java/org/apache/knox/gateway/service/knoxtoken/TokenServiceMessages.java
----------------------------------------------------------------------
diff --git a/gateway-service-knoxtoken/src/main/java/org/apache/knox/gateway/service/knoxtoken/TokenServiceMessages.java b/gateway-service-knoxtoken/src/main/java/org/apache/knox/gateway/service/knoxtoken/TokenServiceMessages.java
index 609b46f..674f673 100644
--- a/gateway-service-knoxtoken/src/main/java/org/apache/knox/gateway/service/knoxtoken/TokenServiceMessages.java
+++ b/gateway-service-knoxtoken/src/main/java/org/apache/knox/gateway/service/knoxtoken/TokenServiceMessages.java
@@ -22,7 +22,7 @@ import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 import org.apache.knox.gateway.i18n.messages.StackTrace;
 
-@Messages(logger="org.apache.hadoop.gateway.service.knoxsso")
+@Messages(logger="org.apache.knox.gateway.service.knoxsso")
 public interface TokenServiceMessages {
   @Message( level = MessageLevel.INFO, text = "About to redirect to original URL: {0}")
   void aboutToRedirectToOriginal(String original);

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-knoxtoken/src/main/java/org/apache/knox/gateway/service/knoxtoken/deploy/TokenServiceDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-service-knoxtoken/src/main/java/org/apache/knox/gateway/service/knoxtoken/deploy/TokenServiceDeploymentContributor.java b/gateway-service-knoxtoken/src/main/java/org/apache/knox/gateway/service/knoxtoken/deploy/TokenServiceDeploymentContributor.java
index a267f45..8826abd 100644
--- a/gateway-service-knoxtoken/src/main/java/org/apache/knox/gateway/service/knoxtoken/deploy/TokenServiceDeploymentContributor.java
+++ b/gateway-service-knoxtoken/src/main/java/org/apache/knox/gateway/service/knoxtoken/deploy/TokenServiceDeploymentContributor.java
@@ -42,7 +42,7 @@ public class TokenServiceDeploymentContributor extends JerseyServiceDeploymentCo
    */
   @Override
   protected String[] getPackages() {
-    return new String[]{ "org.apache.hadoop.gateway.service.knoxtoken" };
+    return new String[]{ "org.apache.knox.gateway.service.knoxtoken" };
   }
 
   /* (non-Javadoc)

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-rm/src/main/java/org/apache/knox/gateway/rm/i18n/RMMessages.java
----------------------------------------------------------------------
diff --git a/gateway-service-rm/src/main/java/org/apache/knox/gateway/rm/i18n/RMMessages.java b/gateway-service-rm/src/main/java/org/apache/knox/gateway/rm/i18n/RMMessages.java
index 88b0ae7..c2d0b89 100644
--- a/gateway-service-rm/src/main/java/org/apache/knox/gateway/rm/i18n/RMMessages.java
+++ b/gateway-service-rm/src/main/java/org/apache/knox/gateway/rm/i18n/RMMessages.java
@@ -23,7 +23,7 @@ import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 import org.apache.knox.gateway.i18n.messages.StackTrace;
 
-@Messages(logger = "org.apache.hadoop.gateway")
+@Messages(logger = "org.apache.knox.gateway")
 public interface RMMessages extends HaDispatchMessages {
 
   @Message(level = MessageLevel.INFO, text = "Received an error from a node in Standby: {0}")

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-test/src/main/java/org/apache/knox/gateway/service/test/deploy/ServiceTestDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-service-test/src/main/java/org/apache/knox/gateway/service/test/deploy/ServiceTestDeploymentContributor.java b/gateway-service-test/src/main/java/org/apache/knox/gateway/service/test/deploy/ServiceTestDeploymentContributor.java
index ae98ff3..63f9352 100644
--- a/gateway-service-test/src/main/java/org/apache/knox/gateway/service/test/deploy/ServiceTestDeploymentContributor.java
+++ b/gateway-service-test/src/main/java/org/apache/knox/gateway/service/test/deploy/ServiceTestDeploymentContributor.java
@@ -55,7 +55,7 @@ public class ServiceTestDeploymentContributor extends JerseyServiceDeploymentCon
    */
   @Override
   protected String[] getPackages() {
-    return new String[]{ "org.apache.hadoop.gateway.service.test" };
+    return new String[]{ "org.apache.knox.gateway.service.test" };
   }
 
   /* (non-Javadoc)

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-vault/src/main/java/org/apache/knox/gateway/service/vault/deploy/VaultServiceDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-service-vault/src/main/java/org/apache/knox/gateway/service/vault/deploy/VaultServiceDeploymentContributor.java b/gateway-service-vault/src/main/java/org/apache/knox/gateway/service/vault/deploy/VaultServiceDeploymentContributor.java
index 814db02..79b0ade 100644
--- a/gateway-service-vault/src/main/java/org/apache/knox/gateway/service/vault/deploy/VaultServiceDeploymentContributor.java
+++ b/gateway-service-vault/src/main/java/org/apache/knox/gateway/service/vault/deploy/VaultServiceDeploymentContributor.java
@@ -46,7 +46,7 @@ public class VaultServiceDeploymentContributor extends JerseyServiceDeploymentCo
    */
   @Override
   protected String[] getPackages() {
-    return new String[]{ "org.apache.hadoop.gateway.service.vault" };
+    return new String[]{ "org.apache.knox.gateway.service.vault" };
   }
 
   /* (non-Javadoc)

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-webhdfs/src/main/java/org/apache/knox/gateway/hdfs/i18n/WebHdfsMessages.java
----------------------------------------------------------------------
diff --git a/gateway-service-webhdfs/src/main/java/org/apache/knox/gateway/hdfs/i18n/WebHdfsMessages.java b/gateway-service-webhdfs/src/main/java/org/apache/knox/gateway/hdfs/i18n/WebHdfsMessages.java
index bd00b6d..9580f69 100644
--- a/gateway-service-webhdfs/src/main/java/org/apache/knox/gateway/hdfs/i18n/WebHdfsMessages.java
+++ b/gateway-service-webhdfs/src/main/java/org/apache/knox/gateway/hdfs/i18n/WebHdfsMessages.java
@@ -23,7 +23,7 @@ import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 import org.apache.knox.gateway.i18n.messages.StackTrace;
 
-@Messages(logger = "org.apache.hadoop.gateway")
+@Messages(logger = "org.apache.knox.gateway")
 public interface WebHdfsMessages extends HaDispatchMessages {
 
   @Message(level = MessageLevel.INFO, text = "Received an error from a node in Standby: {0}")

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-launcher/src/main/resources/META-INF/launcher.cfg
----------------------------------------------------------------------
diff --git a/gateway-shell-launcher/src/main/resources/META-INF/launcher.cfg b/gateway-shell-launcher/src/main/resources/META-INF/launcher.cfg
index 07d2151..c9cc31d 100644
--- a/gateway-shell-launcher/src/main/resources/META-INF/launcher.cfg
+++ b/gateway-shell-launcher/src/main/resources/META-INF/launcher.cfg
@@ -12,7 +12,7 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-main.class = org.apache.hadoop.gateway.shell.Shell
+main.class = org.apache.knox.gateway.shell.Shell
 class.path = ../lib/*.jar;../dep/*.jar;../ext;../ext/*.jar
 GATEWAY_HOME=${launcher.dir}/..
 log4j.configuration=${GATEWAY_HOME}/conf/${launcher.name}-log4j.properties
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-release/home/bin/knoxshell.sh
----------------------------------------------------------------------
diff --git a/gateway-shell-release/home/bin/knoxshell.sh b/gateway-shell-release/home/bin/knoxshell.sh
index a7031f3..b9721f1 100755
--- a/gateway-shell-release/home/bin/knoxshell.sh
+++ b/gateway-shell-release/home/bin/knoxshell.sh
@@ -63,14 +63,14 @@ function main {
             echo "Illegal number of parameters."
             printHelp
         else
-          $JAVA -cp $APP_JAR org.apache.hadoop.gateway.shell.KnoxSh init --gateway $2 || exit 1
+          $JAVA -cp $APP_JAR org.apache.knox.gateway.shell.KnoxSh init --gateway $2 || exit 1
         fi
          ;;
       list)
-        $JAVA -cp $APP_JAR org.apache.hadoop.gateway.shell.KnoxSh list || exit 1
+        $JAVA -cp $APP_JAR org.apache.knox.gateway.shell.KnoxSh list || exit 1
          ;;
       destroy)
-        $JAVA -cp $APP_JAR org.apache.hadoop.gateway.shell.KnoxSh destroy || exit 1
+        $JAVA -cp $APP_JAR org.apache.knox.gateway.shell.KnoxSh destroy || exit 1
          ;;
       help)
          printHelp

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/ExampleHBase.groovy
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/ExampleHBase.groovy b/gateway-shell-samples/src/main/resources/samples/ExampleHBase.groovy
index 7d20aca..87f362d 100644
--- a/gateway-shell-samples/src/main/resources/samples/ExampleHBase.groovy
+++ b/gateway-shell-samples/src/main/resources/samples/ExampleHBase.groovy
@@ -15,13 +15,13 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.apache.hadoop.gateway.shell.hbase
+package org.apache.knox.gateway.shell.hbase
 
-import org.apache.hadoop.gateway.shell.Hadoop
+import org.apache.knox.gateway.shell.Hadoop
 
 import static java.util.concurrent.TimeUnit.SECONDS
 
-import org.apache.hadoop.gateway.shell.Credentials
+import org.apache.knox.gateway.shell.Credentials
 
 gateway = "https://localhost:8443/gateway/sandbox"
 tableName = "test_table"

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/ExampleOozieWorkflow.groovy
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/ExampleOozieWorkflow.groovy b/gateway-shell-samples/src/main/resources/samples/ExampleOozieWorkflow.groovy
index b6e7e72..f459ddd 100644
--- a/gateway-shell-samples/src/main/resources/samples/ExampleOozieWorkflow.groovy
+++ b/gateway-shell-samples/src/main/resources/samples/ExampleOozieWorkflow.groovy
@@ -17,12 +17,12 @@
  */
 import com.jayway.jsonpath.JsonPath
 import groovy.json.JsonSlurper
-import org.apache.hadoop.gateway.shell.Hadoop
-import org.apache.hadoop.gateway.shell.hdfs.Hdfs
-import org.apache.hadoop.gateway.shell.workflow.Workflow
+import org.apache.knox.gateway.shell.Hadoop
+import org.apache.knox.gateway.shell.hdfs.Hdfs
+import org.apache.knox.gateway.shell.workflow.Workflow
 
 import static java.util.concurrent.TimeUnit.SECONDS
-import org.apache.hadoop.gateway.shell.Credentials
+import org.apache.knox.gateway.shell.Credentials
 
 gateway = "https://localhost:8443/gateway/sandbox"
 inputFile = "LICENSE"

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatJob.groovy
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatJob.groovy b/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatJob.groovy
index b7477b9..b0d593f 100644
--- a/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatJob.groovy
+++ b/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatJob.groovy
@@ -17,12 +17,12 @@
  */
 import com.jayway.jsonpath.JsonPath
 import groovy.json.JsonSlurper
-import org.apache.hadoop.gateway.shell.Hadoop
-import org.apache.hadoop.gateway.shell.hdfs.Hdfs
-import org.apache.hadoop.gateway.shell.job.Job
+import org.apache.knox.gateway.shell.Hadoop
+import org.apache.knox.gateway.shell.hdfs.Hdfs
+import org.apache.knox.gateway.shell.job.Job
 
 import static java.util.concurrent.TimeUnit.SECONDS
-import org.apache.hadoop.gateway.shell.Credentials
+import org.apache.knox.gateway.shell.Credentials
 
 gateway = "https://localhost:8443/gateway/sandbox"
 dataFile = "LICENSE"

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatJobTeragen.groovy
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatJobTeragen.groovy b/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatJobTeragen.groovy
index 3b111a9..a6b88da 100644
--- a/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatJobTeragen.groovy
+++ b/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatJobTeragen.groovy
@@ -17,12 +17,12 @@
  */
 import com.jayway.jsonpath.JsonPath
 import groovy.json.JsonSlurper
-import org.apache.hadoop.gateway.shell.Hadoop
-import org.apache.hadoop.gateway.shell.hdfs.Hdfs
-import org.apache.hadoop.gateway.shell.job.Job
+import org.apache.knox.gateway.shell.Hadoop
+import org.apache.knox.gateway.shell.hdfs.Hdfs
+import org.apache.knox.gateway.shell.job.Job
 
 import static java.util.concurrent.TimeUnit.SECONDS
-import org.apache.hadoop.gateway.shell.Credentials
+import org.apache.knox.gateway.shell.Credentials
 
 gateway = "https://localhost:8443/gateway/sandbox"
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatPig.groovy
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatPig.groovy b/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatPig.groovy
index 8699608..be00d9c 100644
--- a/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatPig.groovy
+++ b/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatPig.groovy
@@ -17,12 +17,12 @@
  */
 import com.jayway.jsonpath.JsonPath
 import groovy.json.JsonSlurper
-import org.apache.hadoop.gateway.shell.Hadoop
-import org.apache.hadoop.gateway.shell.hdfs.Hdfs
-import org.apache.hadoop.gateway.shell.job.Job
+import org.apache.knox.gateway.shell.Hadoop
+import org.apache.knox.gateway.shell.hdfs.Hdfs
+import org.apache.knox.gateway.shell.job.Job
 
 import static java.util.concurrent.TimeUnit.SECONDS
-import org.apache.hadoop.gateway.shell.Credentials
+import org.apache.knox.gateway.shell.Credentials
 
 gateway = "https://localhost:8443/gateway/sandbox"
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatQueue.groovy
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatQueue.groovy b/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatQueue.groovy
index 2517db2..c180e5f 100644
--- a/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatQueue.groovy
+++ b/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatQueue.groovy
@@ -15,11 +15,11 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-import org.apache.hadoop.gateway.shell.Hadoop
-import org.apache.hadoop.gateway.shell.job.Job
+import org.apache.knox.gateway.shell.Hadoop
+import org.apache.knox.gateway.shell.job.Job
 
 import static java.util.concurrent.TimeUnit.SECONDS
-import org.apache.hadoop.gateway.shell.Credentials
+import org.apache.knox.gateway.shell.Credentials
 
 gateway = "https://localhost:8443/gateway/sandbox"
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatSqoop.groovy
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatSqoop.groovy b/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatSqoop.groovy
index a5629e3..b89736f 100644
--- a/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatSqoop.groovy
+++ b/gateway-shell-samples/src/main/resources/samples/ExampleWebHCatSqoop.groovy
@@ -17,12 +17,12 @@
  */
 import com.jayway.jsonpath.JsonPath
 import groovy.json.JsonSlurper
-import org.apache.hadoop.gateway.shell.Hadoop
-import org.apache.hadoop.gateway.shell.hdfs.Hdfs
-import org.apache.hadoop.gateway.shell.job.Job
+import org.apache.knox.gateway.shell.Hadoop
+import org.apache.knox.gateway.shell.hdfs.Hdfs
+import org.apache.knox.gateway.shell.job.Job
 
 import static java.util.concurrent.TimeUnit.SECONDS
-import org.apache.hadoop.gateway.shell.Credentials
+import org.apache.knox.gateway.shell.Credentials
 
 gateway = "https://localhost:8443/gateway/sandbox"
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/ExampleWebHdfsLs.groovy
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/ExampleWebHdfsLs.groovy b/gateway-shell-samples/src/main/resources/samples/ExampleWebHdfsLs.groovy
index d631f33..a142917 100644
--- a/gateway-shell-samples/src/main/resources/samples/ExampleWebHdfsLs.groovy
+++ b/gateway-shell-samples/src/main/resources/samples/ExampleWebHdfsLs.groovy
@@ -17,10 +17,10 @@
  */
 
 import groovy.json.JsonSlurper
-import org.apache.hadoop.gateway.shell.Hadoop
-import org.apache.hadoop.gateway.shell.hdfs.Hdfs
+import org.apache.knox.gateway.shell.Hadoop
+import org.apache.knox.gateway.shell.hdfs.Hdfs
 
-import org.apache.hadoop.gateway.shell.Credentials
+import org.apache.knox.gateway.shell.Credentials
 
 gateway = "https://localhost:8443/gateway/sandbox"
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/ExampleWebHdfsPutGet.groovy
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/ExampleWebHdfsPutGet.groovy b/gateway-shell-samples/src/main/resources/samples/ExampleWebHdfsPutGet.groovy
index 68b5f67..297481f 100644
--- a/gateway-shell-samples/src/main/resources/samples/ExampleWebHdfsPutGet.groovy
+++ b/gateway-shell-samples/src/main/resources/samples/ExampleWebHdfsPutGet.groovy
@@ -15,9 +15,9 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-import org.apache.hadoop.gateway.shell.Hadoop
-import org.apache.hadoop.gateway.shell.hdfs.Hdfs
-import org.apache.hadoop.gateway.shell.Credentials
+import org.apache.knox.gateway.shell.Hadoop
+import org.apache.knox.gateway.shell.hdfs.Hdfs
+import org.apache.knox.gateway.shell.Credentials
 
 gateway = "https://localhost:8443/gateway/sandbox"
 dataFile = "README"

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/SampleComplexCommand.groovy
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/SampleComplexCommand.groovy b/gateway-shell-samples/src/main/resources/samples/SampleComplexCommand.groovy
index 1abfa4a..a80663d 100644
--- a/gateway-shell-samples/src/main/resources/samples/SampleComplexCommand.groovy
+++ b/gateway-shell-samples/src/main/resources/samples/SampleComplexCommand.groovy
@@ -16,9 +16,9 @@
  * limitations under the License.
  */
 import com.jayway.jsonpath.JsonPath
-import org.apache.hadoop.gateway.shell.AbstractRequest
-import org.apache.hadoop.gateway.shell.BasicResponse
-import org.apache.hadoop.gateway.shell.Hadoop
+import org.apache.knox.gateway.shell.AbstractRequest
+import org.apache.knox.gateway.shell.BasicResponse
+import org.apache.knox.gateway.shell.Hadoop
 import org.apache.http.HttpResponse
 import org.apache.http.client.methods.HttpGet
 import org.apache.http.client.utils.URIBuilder

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/SampleScript.groovy
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/SampleScript.groovy b/gateway-shell-samples/src/main/resources/samples/SampleScript.groovy
index 219ea85..56a87ad 100644
--- a/gateway-shell-samples/src/main/resources/samples/SampleScript.groovy
+++ b/gateway-shell-samples/src/main/resources/samples/SampleScript.groovy
@@ -15,8 +15,8 @@
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
-import org.apache.hadoop.gateway.shell.Hadoop
-import org.apache.hadoop.gateway.shell.Credentials
+import org.apache.knox.gateway.shell.Hadoop
+import org.apache.knox.gateway.shell.Credentials
 
 gateway = "https://localhost:8443/gateway/sandbox"
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/SampleService.groovy
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/SampleService.groovy b/gateway-shell-samples/src/main/resources/samples/SampleService.groovy
index 3b1345c..e87834e 100644
--- a/gateway-shell-samples/src/main/resources/samples/SampleService.groovy
+++ b/gateway-shell-samples/src/main/resources/samples/SampleService.groovy
@@ -15,7 +15,7 @@
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
-import org.apache.hadoop.gateway.shell.Hadoop
+import org.apache.knox.gateway.shell.Hadoop
 
 class SampleService {
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/SampleSimpleCommand.groovy
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/SampleSimpleCommand.groovy b/gateway-shell-samples/src/main/resources/samples/SampleSimpleCommand.groovy
index 600113d..1e178c6 100644
--- a/gateway-shell-samples/src/main/resources/samples/SampleSimpleCommand.groovy
+++ b/gateway-shell-samples/src/main/resources/samples/SampleSimpleCommand.groovy
@@ -15,9 +15,9 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-import org.apache.hadoop.gateway.shell.AbstractRequest
-import org.apache.hadoop.gateway.shell.BasicResponse
-import org.apache.hadoop.gateway.shell.Hadoop
+import org.apache.knox.gateway.shell.AbstractRequest
+import org.apache.knox.gateway.shell.BasicResponse
+import org.apache.knox.gateway.shell.Hadoop
 import org.apache.http.client.methods.HttpGet
 import org.apache.http.client.utils.URIBuilder
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/hive/groovy/jdbc/sandbox-with-knox-inside/HiveJDBCSample.groovy
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/hive/groovy/jdbc/sandbox-with-knox-inside/HiveJDBCSample.groovy b/gateway-shell-samples/src/main/resources/samples/hive/groovy/jdbc/sandbox-with-knox-inside/HiveJDBCSample.groovy
index 0e465aa..2e9f72e 100644
--- a/gateway-shell-samples/src/main/resources/samples/hive/groovy/jdbc/sandbox-with-knox-inside/HiveJDBCSample.groovy
+++ b/gateway-shell-samples/src/main/resources/samples/hive/groovy/jdbc/sandbox-with-knox-inside/HiveJDBCSample.groovy
@@ -16,7 +16,7 @@
  * limitations under the License.
  */
 import java.sql.DriverManager
-import org.apache.hadoop.gateway.shell.Credentials
+import org.apache.knox.gateway.shell.Credentials
 
 gatewayHost = "localhost";
 gatewayPort = 8443;

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/hive/groovy/jdbc/sandbox/HiveJDBCSample.groovy
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/hive/groovy/jdbc/sandbox/HiveJDBCSample.groovy b/gateway-shell-samples/src/main/resources/samples/hive/groovy/jdbc/sandbox/HiveJDBCSample.groovy
index bd34edb..d8a3231 100644
--- a/gateway-shell-samples/src/main/resources/samples/hive/groovy/jdbc/sandbox/HiveJDBCSample.groovy
+++ b/gateway-shell-samples/src/main/resources/samples/hive/groovy/jdbc/sandbox/HiveJDBCSample.groovy
@@ -16,7 +16,7 @@
  * limitations under the License.
  */
 import java.sql.DriverManager
-import org.apache.hadoop.gateway.shell.Credentials
+import org.apache.knox.gateway.shell.Credentials
 
 gatewayHost = "localhost";
 gatewayPort = 8443;

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/hive/java/jdbc/sandbox-with-knox-inside/HiveJDBCSample.java
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/hive/java/jdbc/sandbox-with-knox-inside/HiveJDBCSample.java b/gateway-shell-samples/src/main/resources/samples/hive/java/jdbc/sandbox-with-knox-inside/HiveJDBCSample.java
index 2bcf4d0..86f679c 100644
--- a/gateway-shell-samples/src/main/resources/samples/hive/java/jdbc/sandbox-with-knox-inside/HiveJDBCSample.java
+++ b/gateway-shell-samples/src/main/resources/samples/hive/java/jdbc/sandbox-with-knox-inside/HiveJDBCSample.java
@@ -25,7 +25,7 @@ import java.sql.Statement;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
-import org.apache.hadoop.gateway.shell.Credentials;
+import org.apache.knox.gateway.shell.Credentials;
 
 public class HiveJDBCSample {
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/hive/java/jdbc/sandbox/HiveJDBCSample.java
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/hive/java/jdbc/sandbox/HiveJDBCSample.java b/gateway-shell-samples/src/main/resources/samples/hive/java/jdbc/sandbox/HiveJDBCSample.java
index ffa7e58..71f5e13 100644
--- a/gateway-shell-samples/src/main/resources/samples/hive/java/jdbc/sandbox/HiveJDBCSample.java
+++ b/gateway-shell-samples/src/main/resources/samples/hive/java/jdbc/sandbox/HiveJDBCSample.java
@@ -25,7 +25,7 @@ import java.sql.Statement;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
-import org.apache.hadoop.gateway.shell.Credentials;
+import org.apache.knox.gateway.shell.Credentials;
 
 public class HiveJDBCSample {
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-shell-samples/src/main/resources/samples/sandbox-with-knox-inside.xml
----------------------------------------------------------------------
diff --git a/gateway-shell-samples/src/main/resources/samples/sandbox-with-knox-inside.xml b/gateway-shell-samples/src/main/resources/samples/sandbox-with-knox-inside.xml
index 9c92ead..0e392b3 100644
--- a/gateway-shell-samples/src/main/resources/samples/sandbox-with-knox-inside.xml
+++ b/gateway-shell-samples/src/main/resources/samples/sandbox-with-knox-inside.xml
@@ -24,11 +24,11 @@
             <enabled>true</enabled>
             <param>
                 <name>main.ldapRealm</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
                 <name>main.ldapContextFactory</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
                 <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-spi/src/main/java/org/apache/knox/gateway/SpiGatewayMessages.java
----------------------------------------------------------------------
diff --git a/gateway-spi/src/main/java/org/apache/knox/gateway/SpiGatewayMessages.java b/gateway-spi/src/main/java/org/apache/knox/gateway/SpiGatewayMessages.java
index a48b345..ddcc073 100644
--- a/gateway-spi/src/main/java/org/apache/knox/gateway/SpiGatewayMessages.java
+++ b/gateway-spi/src/main/java/org/apache/knox/gateway/SpiGatewayMessages.java
@@ -29,7 +29,7 @@ import java.nio.charset.Charset;
 /**
  *
  */
-@Messages(logger="org.apache.hadoop.gateway")
+@Messages(logger="org.apache.knox.gateway")
 public interface SpiGatewayMessages {
 
   @Message( level = MessageLevel.DEBUG, text = "Dispatch request: {0} {1}" )

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-spi/src/main/java/org/apache/knox/gateway/config/GatewayConfig.java
----------------------------------------------------------------------
diff --git a/gateway-spi/src/main/java/org/apache/knox/gateway/config/GatewayConfig.java b/gateway-spi/src/main/java/org/apache/knox/gateway/config/GatewayConfig.java
index d0aa126..f01bd20 100644
--- a/gateway-spi/src/main/java/org/apache/knox/gateway/config/GatewayConfig.java
+++ b/gateway-spi/src/main/java/org/apache/knox/gateway/config/GatewayConfig.java
@@ -33,7 +33,7 @@ public interface GatewayConfig {
   // Variable name for the location of data files generated by the gateway at runtime.
   static final String GATEWAY_DATA_HOME_VAR = "GATEWAY_DATA_HOME";
 
-  public static final String GATEWAY_CONFIG_ATTRIBUTE = "org.apache.hadoop.gateway.config";
+  public static final String GATEWAY_CONFIG_ATTRIBUTE = "org.apache.knox.gateway.config";
   public static final String HADOOP_KERBEROS_SECURED = "gateway.hadoop.kerberos.secured";
   public static final String KRB5_CONFIG = "java.security.krb5.conf";
   public static final String KRB5_DEBUG = "sun.security.krb5.debug";

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-spi/src/main/java/org/apache/knox/gateway/deploy/ServiceDeploymentContributorBase.java
----------------------------------------------------------------------
diff --git a/gateway-spi/src/main/java/org/apache/knox/gateway/deploy/ServiceDeploymentContributorBase.java b/gateway-spi/src/main/java/org/apache/knox/gateway/deploy/ServiceDeploymentContributorBase.java
index 16632d4..deb994c 100644
--- a/gateway-spi/src/main/java/org/apache/knox/gateway/deploy/ServiceDeploymentContributorBase.java
+++ b/gateway-spi/src/main/java/org/apache/knox/gateway/deploy/ServiceDeploymentContributorBase.java
@@ -92,7 +92,7 @@ public abstract class ServiceDeploymentContributorBase extends DeploymentContrib
     final String XFORWARDED_FILTER_NAME = "XForwardedHeaderFilter";
     final String XFORWARDED_FILTER_ROLE = "xforwardedheaders";
     if (context.getGatewayConfig() != null && context.getGatewayConfig().isXForwardedEnabled()) {
-      resource.addFilter().name(XFORWARDED_FILTER_NAME).role(XFORWARDED_FILTER_ROLE).impl("org.apache.hadoop.gateway.filter.XForwardedHeaderFilter");
+      resource.addFilter().name(XFORWARDED_FILTER_NAME).role(XFORWARDED_FILTER_ROLE).impl("org.apache.knox.gateway.filter.XForwardedHeaderFilter");
     }
   }
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-spi/src/main/java/org/apache/knox/gateway/i18n/GatewaySpiMessages.java
----------------------------------------------------------------------
diff --git a/gateway-spi/src/main/java/org/apache/knox/gateway/i18n/GatewaySpiMessages.java b/gateway-spi/src/main/java/org/apache/knox/gateway/i18n/GatewaySpiMessages.java
index 859c545..243bac3 100644
--- a/gateway-spi/src/main/java/org/apache/knox/gateway/i18n/GatewaySpiMessages.java
+++ b/gateway-spi/src/main/java/org/apache/knox/gateway/i18n/GatewaySpiMessages.java
@@ -22,7 +22,7 @@ import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 import org.apache.knox.gateway.i18n.messages.StackTrace;
 
-@Messages(logger="org.apache.hadoop.gateway")
+@Messages(logger="org.apache.knox.gateway")
 public interface GatewaySpiMessages {
 
   @Message(level = MessageLevel.ERROR, text = "Failed to load the internal principal mapping table: {0}" )

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-spi/src/main/java/org/apache/knox/gateway/security/principal/SimplePrincipalMapper.java
----------------------------------------------------------------------
diff --git a/gateway-spi/src/main/java/org/apache/knox/gateway/security/principal/SimplePrincipalMapper.java b/gateway-spi/src/main/java/org/apache/knox/gateway/security/principal/SimplePrincipalMapper.java
index ecec834..68f63d6 100644
--- a/gateway-spi/src/main/java/org/apache/knox/gateway/security/principal/SimplePrincipalMapper.java
+++ b/gateway-spi/src/main/java/org/apache/knox/gateway/security/principal/SimplePrincipalMapper.java
@@ -29,7 +29,7 @@ public class SimplePrincipalMapper implements PrincipalMapper {
   }
   
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.filter.PrincipalMapper#loadMappingTable(java.lang.String)
+   * @see org.apache.knox.gateway.filter.PrincipalMapper#loadMappingTable(java.lang.String)
    */
   @Override
   public void loadMappingTable(String principalMapping, String groupMapping) throws PrincipalMappingException {
@@ -74,7 +74,7 @@ public class SimplePrincipalMapper implements PrincipalMapper {
   }
   
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.filter.PrincipalMapper#mapPrincipal(java.lang.String)
+   * @see org.apache.knox.gateway.filter.PrincipalMapper#mapPrincipal(java.lang.String)
    */
   @Override
   public String mapUserPrincipal(String principalName) {
@@ -90,7 +90,7 @@ public class SimplePrincipalMapper implements PrincipalMapper {
   }
 
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.filter.PrincipalMapper#mapPrincipal(java.lang.String)
+   * @see org.apache.knox.gateway.filter.PrincipalMapper#mapPrincipal(java.lang.String)
    */
   @Override
   public String[] mapGroupPrincipal(String principalName) {

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-spi/src/main/java/org/apache/knox/gateway/services/GatewayServices.java
----------------------------------------------------------------------
diff --git a/gateway-spi/src/main/java/org/apache/knox/gateway/services/GatewayServices.java b/gateway-spi/src/main/java/org/apache/knox/gateway/services/GatewayServices.java
index 1a12c05..4a30800 100644
--- a/gateway-spi/src/main/java/org/apache/knox/gateway/services/GatewayServices.java
+++ b/gateway-spi/src/main/java/org/apache/knox/gateway/services/GatewayServices.java
@@ -24,8 +24,8 @@ import org.apache.knox.gateway.deploy.ProviderDeploymentContributor;
 public interface GatewayServices extends Service,
     ProviderDeploymentContributor {
 
-  public static final String GATEWAY_CLUSTER_ATTRIBUTE = "org.apache.hadoop.gateway.gateway.cluster";
-  public static final String GATEWAY_SERVICES_ATTRIBUTE = "org.apache.hadoop.gateway.gateway.services";
+  public static final String GATEWAY_CLUSTER_ATTRIBUTE = "org.apache.knox.gateway.gateway.cluster";
+  public static final String GATEWAY_SERVICES_ATTRIBUTE = "org.apache.knox.gateway.gateway.services";
 
   public static final String SSL_SERVICE = "SSLService";
   public static final String CRYPTO_SERVICE = "CryptoService";

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-spi/src/main/java/org/apache/knox/gateway/services/security/token/impl/JWTProviderMessages.java
----------------------------------------------------------------------
diff --git a/gateway-spi/src/main/java/org/apache/knox/gateway/services/security/token/impl/JWTProviderMessages.java b/gateway-spi/src/main/java/org/apache/knox/gateway/services/security/token/impl/JWTProviderMessages.java
index 20f2772..77165f6 100644
--- a/gateway-spi/src/main/java/org/apache/knox/gateway/services/security/token/impl/JWTProviderMessages.java
+++ b/gateway-spi/src/main/java/org/apache/knox/gateway/services/security/token/impl/JWTProviderMessages.java
@@ -29,7 +29,7 @@ import com.nimbusds.jose.JOSEException;
 /**
  *
  */
-@Messages(logger="org.apache.hadoop.gateway")
+@Messages(logger="org.apache.knox.gateway")
 public interface JWTProviderMessages {
 
   @Message( level = MessageLevel.DEBUG, text = "Rendering JWT Token for the wire: {0}" )

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-spi/src/main/resources/org/apache/knox/gateway/topology/topology_binding-json.xml
----------------------------------------------------------------------
diff --git a/gateway-spi/src/main/resources/org/apache/knox/gateway/topology/topology_binding-json.xml b/gateway-spi/src/main/resources/org/apache/knox/gateway/topology/topology_binding-json.xml
index 7fb301b..f237f6e 100644
--- a/gateway-spi/src/main/resources/org/apache/knox/gateway/topology/topology_binding-json.xml
+++ b/gateway-spi/src/main/resources/org/apache/knox/gateway/topology/topology_binding-json.xml
@@ -18,7 +18,7 @@ or more contributor license agreements.  See the NOTICE file
 -->
 <xml-bindings
     xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
-    package-name="org.apache.hadoop.gateway.topology" 
+    package-name="org.apache.knox.gateway.topology"
     xml-mapping-metadata-complete="true">
     <xml-schema
         element-form-default="QUALIFIED"/>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-spi/src/main/resources/org/apache/knox/gateway/topology/topology_binding-xml.xml
----------------------------------------------------------------------
diff --git a/gateway-spi/src/main/resources/org/apache/knox/gateway/topology/topology_binding-xml.xml b/gateway-spi/src/main/resources/org/apache/knox/gateway/topology/topology_binding-xml.xml
index 50d8d58..9e9c26f 100644
--- a/gateway-spi/src/main/resources/org/apache/knox/gateway/topology/topology_binding-xml.xml
+++ b/gateway-spi/src/main/resources/org/apache/knox/gateway/topology/topology_binding-xml.xml
@@ -18,7 +18,7 @@ or more contributor license agreements.  See the NOTICE file
 -->
 <xml-bindings
     xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
-    package-name="org.apache.hadoop.gateway.topology" 
+    package-name="org.apache.knox.gateway.topology"
     xml-mapping-metadata-complete="true">
     <xml-schema
         element-form-default="QUALIFIED"/>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-test-release/webhdfs-kerb-test/src/test/java/org/apache/knox/gateway/SecureClusterTest.java
----------------------------------------------------------------------
diff --git a/gateway-test-release/webhdfs-kerb-test/src/test/java/org/apache/knox/gateway/SecureClusterTest.java b/gateway-test-release/webhdfs-kerb-test/src/test/java/org/apache/knox/gateway/SecureClusterTest.java
index 1c5963f..dca2a19 100644
--- a/gateway-test-release/webhdfs-kerb-test/src/test/java/org/apache/knox/gateway/SecureClusterTest.java
+++ b/gateway-test-release/webhdfs-kerb-test/src/test/java/org/apache/knox/gateway/SecureClusterTest.java
@@ -294,7 +294,7 @@ public class SecureClusterTest {
         .addTag("enabled").addText("true")
         .addTag( "param" )
         .addTag("name").addText("main.ldapRealm")
-        .addTag("value").addText("KnoxLdapRealm").gotoParent()
+        .addTag("value").addText("org.apache.knox.gateway.shirorealm.KnoxLdapRealm").gotoParent()
         .addTag( "param" )
         .addTag("name").addText("main.ldapRealm.userDnTemplate")
         .addTag( "value" ).addText("uid={0},ou=people,dc=hadoop,dc=apache,dc=org").gotoParent()

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-test-release/webhdfs-test/src/test/java/org/apache/knox/gateway/ShellTest.java
----------------------------------------------------------------------
diff --git a/gateway-test-release/webhdfs-test/src/test/java/org/apache/knox/gateway/ShellTest.java b/gateway-test-release/webhdfs-test/src/test/java/org/apache/knox/gateway/ShellTest.java
index 05fb2a0..455af41 100644
--- a/gateway-test-release/webhdfs-test/src/test/java/org/apache/knox/gateway/ShellTest.java
+++ b/gateway-test-release/webhdfs-test/src/test/java/org/apache/knox/gateway/ShellTest.java
@@ -153,7 +153,7 @@ public class ShellTest {
         .addTag("enabled").addText("true")
         .addTag( "param" )
         .addTag("name").addText("main.ldapRealm")
-        .addTag("value").addText("KnoxLdapRealm").gotoParent()
+        .addTag("value").addText("org.apache.knox.gateway.shirorealm.KnoxLdapRealm").gotoParent()
         .addTag( "param" )
         .addTag("name").addText("main.ldapRealm.userDnTemplate")
         .addTag( "value" ).addText("uid={0},ou=people,dc=hadoop,dc=apache,dc=org").gotoParent()

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-test/src/test/java/org/apache/knox/gateway/GatewayBasicFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/knox/gateway/GatewayBasicFuncTest.java b/gateway-test/src/test/java/org/apache/knox/gateway/GatewayBasicFuncTest.java
index 0d2e99c..8ec17d6 100644
--- a/gateway-test/src/test/java/org/apache/knox/gateway/GatewayBasicFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/knox/gateway/GatewayBasicFuncTest.java
@@ -201,7 +201,7 @@ public class GatewayBasicFuncTest {
               .addTag("enabled").addText("true")
               .addTag( "param" )
                 .addTag("name").addText("main.ldapRealm")
-                .addTag("value").addText("KnoxLdapRealm").gotoParent()
+                .addTag("value").addText("org.apache.knox.gateway.shirorealm.KnoxLdapRealm").gotoParent()
               .addTag( "param" )
                 .addTag( "name" ).addText( "main.ldapRealm.userDnTemplate" )
                 .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" ).gotoParent()
@@ -871,27 +871,27 @@ public class GatewayBasicFuncTest {
     deleteFile( user, pass, root, "true", HttpStatus.SC_OK );
 
     /* Put the mapreduce code into HDFS. (hadoop-examples.jar)
-    curl -X PUT --data-binary @hadoop-examples.jar 'http://192.168.1.163:8888/org.apache.org.apache.hadoop.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/hadoop-examples.jar?user.name=hdfs&op=CREATE'
+    curl -X PUT --data-binary @hadoop-examples.jar 'http://192.168.1.163:8888/org.apache.org.apache.knox.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/hadoop-examples.jar?user.name=hdfs&op=CREATE'
      */
     createFile( user, pass, null, root+"/hadoop-examples.jar", "777", "application/octet-stream", findHadoopExamplesJar(), 307, 201, 200 );
 
     /* Put the data file into HDFS (changes.txt)
-    curl -X PUT --data-binary @changes.txt 'http://192.168.1.163:8888/org.apache.org.apache.hadoop.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/input/changes.txt?user.name=hdfs&op=CREATE'
+    curl -X PUT --data-binary @changes.txt 'http://192.168.1.163:8888/org.apache.org.apache.knox.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/input/changes.txt?user.name=hdfs&op=CREATE'
      */
     createFile( user, pass, null, root+"/input/changes.txt", "777", "text/plain", "changes.txt", 307, 201, 200 );
 
     /* Create the output directory
-    curl -X PUT 'http://192.168.1.163:8888/org.apache.org.apache.hadoop.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/output?op=MKDIRS&user.name=hdfs'
+    curl -X PUT 'http://192.168.1.163:8888/org.apache.org.apache.knox.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/output?op=MKDIRS&user.name=hdfs'
     */
     createDir( user, pass, null, root+"/output", "777", 200, 200 );
 
     /* Submit the job
-    curl -d user.name=hdfs -d jar=wordcount/hadoop-examples.jar -d class=org.apache.WordCount -d arg=wordcount/input -d arg=wordcount/output 'http://localhost:8888/org.apache.org.apache.hadoop.gateway/cluster/templeton/v1/mapreduce/jar'
+    curl -d user.name=hdfs -d jar=wordcount/hadoop-examples.jar -d class=org.apache.org.apache.hadoop.examples.WordCount -d arg=wordcount/input -d arg=wordcount/output 'http://localhost:8888/org.apache.org.apache.knox.gateway/cluster/templeton/v1/mapreduce/jar'
     {"id":"job_201210301335_0059"}
     */
     String job = submitJava(
         user, pass,
-        root+"/hadoop-examples.jar", "org.apache.WordCount",
+        root+"/hadoop-examples.jar", "org.apache.org.apache.hadoop.examples.WordCount",
         root+"/input", root+"/output",
         200 );
 
@@ -902,7 +902,7 @@ public class GatewayBasicFuncTest {
 
     // Can't really check for the output here because the job won't be done.
     /* Retrieve results
-    curl 'http://192.168.1.163:8888/org.apache.org.apache.hadoop.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/input?op=LISTSTATUS'
+    curl 'http://192.168.1.163:8888/org.apache.org.apache.knox.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/input?op=LISTSTATUS'
     */
 
     if( CLEANUP_TEST ) {
@@ -985,12 +985,12 @@ public class GatewayBasicFuncTest {
     createFile( user, pass, group, root+"/workflow.xml", "666", "application/octet-stream", "oozie-workflow.xml", 307, 201, 200 );
 
     /* Put the mapreduce code into HDFS. (hadoop-examples.jar)
-    curl -X PUT --data-binary @hadoop-examples.jar 'http://192.168.1.163:8888/org.apache.org.apache.hadoop.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/hadoop-examples.jar?user.name=hdfs&op=CREATE'
+    curl -X PUT --data-binary @hadoop-examples.jar 'http://192.168.1.163:8888/org.apache.org.apache.knox.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/hadoop-examples.jar?user.name=hdfs&op=CREATE'
      */
     createFile( user, pass, group, root+"/lib/hadoop-examples.jar", "777", "application/octet-stream", findHadoopExamplesJar(), 307, 201, 200 );
 
     /* Put the data file into HDFS (changes.txt)
-    curl -X PUT --data-binary @changes.txt 'http://192.168.1.163:8888/org.apache.org.apache.hadoop.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/input/changes.txt?user.name=hdfs&op=CREATE'
+    curl -X PUT --data-binary @changes.txt 'http://192.168.1.163:8888/org.apache.org.apache.knox.gateway/cluster/webhdfs/v1/user/hdfs/wordcount/input/changes.txt?user.name=hdfs&op=CREATE'
      */
     createFile( user, pass, group, root+"/input/changes.txt", "666", "text/plain", "changes.txt", 307, 201, 200 );
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-test/src/test/java/org/apache/knox/gateway/GatewayHealthFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/knox/gateway/GatewayHealthFuncTest.java b/gateway-test/src/test/java/org/apache/knox/gateway/GatewayHealthFuncTest.java
index 5a18be4..dfd7ab3 100644
--- a/gateway-test/src/test/java/org/apache/knox/gateway/GatewayHealthFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/knox/gateway/GatewayHealthFuncTest.java
@@ -146,7 +146,7 @@ public class GatewayHealthFuncTest {
         .addTag("enabled").addText("true")
         .addTag("param")
         .addTag("name").addText("main.ldapRealm")
-        .addTag("value").addText("KnoxLdapRealm").gotoParent()
+        .addTag("value").addText("org.apache.knox.gateway.shirorealm.KnoxLdapRealm").gotoParent()
         .addTag("param")
         .addTag("name").addText("main.ldapRealm.userDnTemplate")
         .addTag("value").addText("uid={0},ou=people,dc=hadoop,dc=apache,dc=org").gotoParent()

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-test/src/test/java/org/apache/knox/gateway/GatewayPortMappingDisableFeatureTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/knox/gateway/GatewayPortMappingDisableFeatureTest.java b/gateway-test/src/test/java/org/apache/knox/gateway/GatewayPortMappingDisableFeatureTest.java
index 1017188..65d00a2 100644
--- a/gateway-test/src/test/java/org/apache/knox/gateway/GatewayPortMappingDisableFeatureTest.java
+++ b/gateway-test/src/test/java/org/apache/knox/gateway/GatewayPortMappingDisableFeatureTest.java
@@ -192,7 +192,7 @@ public class GatewayPortMappingDisableFeatureTest {
         .addTag("enabled").addText("true")
         .addTag("param")
         .addTag("name").addText("main.ldapRealm")
-        .addTag("value").addText("KnoxLdapRealm").gotoParent()
+        .addTag("value").addText("org.apache.knox.gateway.shirorealm.KnoxLdapRealm").gotoParent()
         .addTag("param")
         .addTag("name").addText("main.ldapRealm.userDnTemplate")
         .addTag("value").addText("uid={0},ou=people,dc=hadoop,dc=apache,dc=org").gotoParent()

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-test/src/test/java/org/apache/knox/gateway/GatewayPortMappingFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/knox/gateway/GatewayPortMappingFuncTest.java b/gateway-test/src/test/java/org/apache/knox/gateway/GatewayPortMappingFuncTest.java
index 53896b3..78ff451 100644
--- a/gateway-test/src/test/java/org/apache/knox/gateway/GatewayPortMappingFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/knox/gateway/GatewayPortMappingFuncTest.java
@@ -216,7 +216,7 @@ public class GatewayPortMappingFuncTest {
         .addTag("enabled").addText("true")
         .addTag("param")
         .addTag("name").addText("main.ldapRealm")
-        .addTag("value").addText("KnoxLdapRealm").gotoParent()
+        .addTag("value").addText("org.apache.knox.gateway.shirorealm.KnoxLdapRealm").gotoParent()
         .addTag("param")
         .addTag("name").addText("main.ldapRealm.userDnTemplate")
         .addTag("value").addText("uid={0},ou=people,dc=hadoop,dc=apache,dc=org").gotoParent()

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-test/src/test/java/org/apache/knox/gateway/TestJerseyServiceDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/knox/gateway/TestJerseyServiceDeploymentContributor.java b/gateway-test/src/test/java/org/apache/knox/gateway/TestJerseyServiceDeploymentContributor.java
index 3d284f6..6823d2e 100644
--- a/gateway-test/src/test/java/org/apache/knox/gateway/TestJerseyServiceDeploymentContributor.java
+++ b/gateway-test/src/test/java/org/apache/knox/gateway/TestJerseyServiceDeploymentContributor.java
@@ -24,7 +24,7 @@ public class TestJerseyServiceDeploymentContributor extends
 
   @Override
   protected String[] getPackages() {
-    return new String[]{ "org.apache.hadoop.gateway" };
+    return new String[]{ "org.apache.knox.gateway" };
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-test/src/test/java/org/apache/knox/gateway/WebHdfsHaFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/knox/gateway/WebHdfsHaFuncTest.java b/gateway-test/src/test/java/org/apache/knox/gateway/WebHdfsHaFuncTest.java
index b894b00..a76dbe6 100644
--- a/gateway-test/src/test/java/org/apache/knox/gateway/WebHdfsHaFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/knox/gateway/WebHdfsHaFuncTest.java
@@ -112,7 +112,7 @@ public class WebHdfsHaFuncTest {
             .addTag("enabled").addText("true")
             .addTag("param")
             .addTag("name").addText("main.ldapRealm")
-            .addTag("value").addText("KnoxLdapRealm").gotoParent()
+            .addTag("value").addText("org.apache.knox.gateway.shirorealm.KnoxLdapRealm").gotoParent()
             .addTag("param")
             .addTag("name").addText("main.ldapRealm.userDnTemplate")
             .addTag("value").addText("uid={0},ou=people,dc=hadoop,dc=apache,dc=org").gotoParent()


[22/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonUrlRewriteStreamFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonUrlRewriteStreamFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonUrlRewriteStreamFilter.java
new file mode 100644
index 0000000..bebc616
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonUrlRewriteStreamFilter.java
@@ -0,0 +1,59 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.json;
+
+import org.apache.commons.io.input.ReaderInputStream;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStreamFilter;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+public class JsonUrlRewriteStreamFilter implements UrlRewriteStreamFilter {
+
+  private static String[] TYPES = new String[]{ "application/json", "text/json", "*/json" };
+  private static String[] NAMES = new String[]{ null };
+
+  @Override
+  public String[] getTypes() {
+    return TYPES;
+  }
+
+  @Override
+  public String[] getNames() {
+    return NAMES;
+  }
+
+  @Override
+  public InputStream filter(
+      InputStream stream,
+      String encoding,
+      UrlRewriter rewriter,
+      Resolver resolver,
+      UrlRewriter.Direction direction,
+      UrlRewriteFilterContentDescriptor config )
+          throws IOException {
+    return new ReaderInputStream(
+        new JsonUrlRewriteFilterReader(
+            new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/noop/NoOpUrlRewriteStreamFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/noop/NoOpUrlRewriteStreamFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/noop/NoOpUrlRewriteStreamFilter.java
new file mode 100644
index 0000000..3db2bbd
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/noop/NoOpUrlRewriteStreamFilter.java
@@ -0,0 +1,55 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.noop;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStreamFilter;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+public class NoOpUrlRewriteStreamFilter implements UrlRewriteStreamFilter {
+
+  private static String[] TYPES = new String[]{ null };
+  private static String[] NAMES = new String[]{ null };
+
+  @Override
+  public String[] getTypes() {
+    return TYPES;
+  }
+
+  @Override
+  public String[] getNames() {
+    return NAMES;
+  }
+
+  @Override
+  public InputStream filter(
+      InputStream stream,
+      String encoding,
+      UrlRewriter rewriter,
+      Resolver resolver,
+      UrlRewriter.Direction direction,
+      UrlRewriteFilterContentDescriptor config )
+          throws IOException {
+    return stream;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReader.java
new file mode 100644
index 0000000..b5c2593
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReader.java
@@ -0,0 +1,643 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.xml;
+
+import org.apache.commons.lang3.StringEscapeUtils;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterBufferDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterDetectDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterGroupDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterScopeDescriptor;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteResources;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.i18n.resources.ResourcesFactory;
+import org.apache.knox.gateway.util.XmlUtils;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.Text;
+
+import javax.xml.namespace.QName;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLEventReader;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.events.Attribute;
+import javax.xml.stream.events.Characters;
+import javax.xml.stream.events.Comment;
+import javax.xml.stream.events.EndElement;
+import javax.xml.stream.events.Namespace;
+import javax.xml.stream.events.StartDocument;
+import javax.xml.stream.events.StartElement;
+import javax.xml.stream.events.XMLEvent;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpression;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.util.Iterator;
+import java.util.Stack;
+import java.util.regex.Pattern;
+
+public abstract class XmlFilterReader extends Reader {
+
+  private static final UrlRewriteResources RES = ResourcesFactory.get( UrlRewriteResources.class );
+
+  private static final String DEFAULT_XML_VERSION = "1.0";
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+  private static final UrlRewriteFilterPathDescriptor.Compiler<XPathExpression> XPATH_COMPILER = new XmlPathCompiler();
+  private static final UrlRewriteFilterPathDescriptor.Compiler<Pattern> REGEX_COMPILER = new RegexCompiler();
+
+  private Reader reader;
+  private UrlRewriteFilterContentDescriptor config;
+  private int offset;
+  private StringWriter writer;
+  private StringBuffer buffer;
+  private XMLInputFactory factory;
+  private XMLEventReader parser;
+  private Document document;
+  private Stack<Level> stack;
+  private boolean isEmptyElement;
+
+  protected XmlFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException, XMLStreamException {
+    this.reader = reader;
+    this.config = config;
+    writer = new StringWriter();
+    buffer = writer.getBuffer();
+    offset = 0;
+    document = null;
+    stack = new Stack<Level>();
+    isEmptyElement = false;
+    factory = XMLInputFactory.newFactory();
+    //KNOX-620 factory.setProperty( XMLConstants.ACCESS_EXTERNAL_DTD, "false" );
+    //KNOX-620 factory.setProperty( XMLConstants.ACCESS_EXTERNAL_SCHEMA, "false" );
+    factory.setProperty( "javax.xml.stream.isReplacingEntityReferences", Boolean.FALSE );
+    factory.setProperty("http://java.sun.com/xml/stream/"
+                + "properties/report-cdata-event", Boolean.TRUE);
+    parser = factory.createXMLEventReader( reader );
+  }
+
+  protected abstract String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName );
+
+  protected abstract String filterText( QName elementName, String text, String ruleName );
+
+  @Override
+  public int read( char[] destBuffer, int destOffset, int destCount ) throws IOException {
+    int count = 0;
+    int available = buffer.length() - offset;
+
+    if( available == 0 ) {
+      if( parser.hasNext() ) {
+        try {
+          XMLEvent event = parser.nextEvent();
+          processEvent( event );
+        } catch( IOException e ) {
+          throw e;
+        } catch( RuntimeException e ) {
+          throw e;
+        } catch ( Exception e ) {
+          throw new RuntimeException( e );
+        }
+        available = buffer.length() - offset;
+      } else {
+        count = -1;
+      }
+    }
+
+    if( available > 0 ) {
+      count = Math.min( destCount, available );
+      buffer.getChars( offset, offset + count, destBuffer, destOffset );
+      offset += count;
+      if( offset == buffer.length() ) {
+        offset = 0;
+        buffer.setLength( 0 );
+      }
+    }
+    return count;
+  }
+
+  private void processEvent( XMLEvent event ) throws ParserConfigurationException, XPathExpressionException, IOException, XMLStreamException {
+    int type = event.getEventType();
+    switch( type ) {
+      case XMLEvent.START_DOCUMENT:
+        processStartDocument( (StartDocument)event );
+        break;
+      case XMLEvent.END_DOCUMENT:
+        processEndDocument();
+        break;
+      case XMLEvent.START_ELEMENT:
+        if( parser.peek().getEventType() == XMLEvent.END_ELEMENT )
+          isEmptyElement = true;
+        processStartElement( event.asStartElement());
+        break;
+      case XMLEvent.END_ELEMENT:
+        processEndElement( event.asEndElement() );
+        isEmptyElement = false;
+        break;
+      case XMLEvent.CHARACTERS:
+      case XMLEvent.CDATA:
+      case XMLEvent.SPACE:
+        processCharacters( event.asCharacters() );
+        break;
+      case XMLEvent.COMMENT:
+        processComment( (Comment)event );
+        break;
+      case XMLEvent.DTD:
+      case XMLEvent.NAMESPACE:
+      case XMLEvent.ATTRIBUTE:
+      case XMLEvent.ENTITY_REFERENCE:
+      case XMLEvent.ENTITY_DECLARATION:
+      case XMLEvent.NOTATION_DECLARATION:
+      case XMLEvent.PROCESSING_INSTRUCTION:
+      default:
+        // Fail if we run into any of these for now.
+        throw new IllegalStateException( Integer.toString( type ) );
+    }
+  }
+
+  private void processStartDocument( StartDocument event ) throws ParserConfigurationException {
+    //System.out.println( "SD=" + event );
+    String s;
+
+    document = XmlUtils.createDocument( false );
+    pushLevel( null, event, document, document, config );
+
+    writer.write( "<?xml" );
+
+    s = event.getVersion();
+    if( s == null ) {
+      s = DEFAULT_XML_VERSION;
+    }
+    writer.write( " version=\"");
+    writer.write( s );
+    writer.write( "\"" );
+
+    s = event.getCharacterEncodingScheme();
+    if( s != null ) {
+      writer.write( " encoding=\"");
+      writer.write( s );
+      writer.write( "\"" );
+    }
+
+    writer.write( " standalone=\"");
+    writer.write( event.isStandalone() ? "yes" : "no" );
+    writer.write( "\"" );
+
+    writer.write( "?>" );
+  }
+
+  private void processEndDocument() {
+    stack.clear();
+    document = null;
+  }
+
+  private void processStartElement( StartElement event ) throws XPathExpressionException {
+    //System.out.println( "SE=" + event );
+
+    // Create a new "empty" element and add it to the document.
+    Element element = bufferElement( event );
+    Level parent = stack.peek();
+    parent.node.appendChild( element );
+
+    // If already buffering just continue to do so.
+    // Note: Don't currently support nested buffer or scope descriptors.
+    if( currentlyBuffering() ) {
+      pushLevel( parent, event, element, parent.scopeNode, parent.scopeConfig );
+      bufferAttributes( event, element );
+    // Else not currently buffering
+    } else {
+      // See if there is a matching path descriptor in the current scope.
+      UrlRewriteFilterPathDescriptor descriptor = pickFirstMatchingPath( parent );
+      if( descriptor != null ) {
+        // If this is a buffer descriptor then switch to buffering and buffer the attributes.
+        if( descriptor instanceof UrlRewriteFilterBufferDescriptor ) {
+          pushLevel( parent, event, element, element, (UrlRewriteFilterBufferDescriptor)descriptor );
+          bufferAttributes( event, element );
+        // Otherwise if this is a scope descriptor then change the scope and stream the attributes.
+        } else if( descriptor instanceof UrlRewriteFilterScopeDescriptor ) {
+          pushLevel( parent, event, element, element, (UrlRewriteFilterScopeDescriptor)descriptor );
+          streamElement( event, element );
+        // Else found an unexpected matching path.
+        } else {
+          // This is likely because there is an <apply> targeted at the text of an element.
+          // That "convenience" config will be taken care of in the streamElement() processing.
+          pushLevel( parent, event, element, parent.scopeNode, parent.scopeConfig );
+          streamElement( event, element );
+        }
+      // If there is no matching path descriptor then continue streaming.
+      } else {
+        pushLevel( parent, event, element, parent.scopeNode, parent.scopeConfig );
+        streamElement( event, element );
+      }
+    }
+  }
+
+  private void processEndElement( EndElement event ) throws XPathExpressionException, IOException {
+    //System.out.println( "EE=" + event );
+    boolean buffering = currentlyBuffering();
+    Level child = stack.pop();
+    if( buffering ) {
+      if( child.node == child.scopeNode ) {
+        processBufferedElement( child );
+      }
+    } else {
+      if( ! isEmptyElement ) {
+        QName n = event.getName();
+        writer.write( "</" );
+        String p = n.getPrefix();
+        if( p != null && !p.isEmpty() ) {
+          writer.write( p );
+          writer.write( ":" );
+        }
+        writer.write( n.getLocalPart() );
+        writer.write( ">" );
+      }
+      child.node.getParentNode().removeChild( child.node );
+    }
+  }
+
+  private Element bufferElement( StartElement event ) {
+    QName qname = event.getName();
+    String prefix = qname.getPrefix();
+    String uri = qname.getNamespaceURI();
+    Element element;
+    if( uri == null || uri.isEmpty() ) {
+      element = document.createElement( qname.getLocalPart() );
+    } else {
+      element = document.createElementNS( qname.getNamespaceURI(), qname.getLocalPart() );
+      if( prefix != null && !prefix.isEmpty() ) {
+        element.setPrefix( prefix );
+      }
+    }
+    // Always need to buffer the namespaces regardless of what else happens so that XPath will work on attributes
+    // namespace qualified attributes.
+    bufferNamespaces( event, element );
+    return element;
+  }
+
+  private void bufferNamespaces( StartElement event, Element element ) {
+    Iterator namespaces = event.getNamespaces();
+    while( namespaces.hasNext() ) {
+      Namespace namespace = (Namespace)namespaces.next();
+      if( namespace.isDefaultNamespaceDeclaration() ) {
+        element.setAttribute( "xmlns", namespace.getNamespaceURI() );
+      } else {
+        element.setAttribute( "xmlns:" + namespace.getPrefix(), namespace.getNamespaceURI() );
+      }
+    }
+  }
+
+  private void streamElement( StartElement event, Element element ) throws XPathExpressionException {
+    writer.write( "<" );
+    QName qname = event.getName();
+    String prefix = event.getName().getPrefix();
+    if( prefix != null && !prefix.isEmpty() ) {
+      writer.write( prefix );
+      writer.write( ":" );
+    }
+    writer.write( qname.getLocalPart() );
+    streamNamespaces( event );
+    streamAttributes( event, element );
+    if( isEmptyElement ) {
+      writer.write("/>");
+    } else {
+      writer.write(">");
+    }
+  }
+
+  private void processBufferedElement( Level level, UrlRewriteFilterGroupDescriptor config ) throws XPathExpressionException {
+    for( UrlRewriteFilterPathDescriptor selector : config.getSelectors() ) {
+      if( selector instanceof UrlRewriteFilterApplyDescriptor ) {
+        XPathExpression path = (XPathExpression)selector.compiledPath( XPATH_COMPILER );
+        Object node = path.evaluate( level.scopeNode, XPathConstants.NODE );
+        if( node != null ) {
+          UrlRewriteFilterApplyDescriptor apply = (UrlRewriteFilterApplyDescriptor)selector;
+          if( node instanceof Element ) {
+            Element element = (Element)node;
+            String value = element.getTextContent();
+            value = filterText( extractQName( element ), value, apply.rule() );
+            element.setTextContent( value );
+          } else if( node instanceof Text ) {
+            Text text = (Text)node;
+            String value = text.getWholeText();
+            value = filterText( extractQName( text.getParentNode() ), value, apply.rule() );
+            text.replaceWholeText( value );
+          } else if( node instanceof Attr ) {
+            Attr attr = (Attr)node;
+            String value = attr.getValue();
+            value = filterAttribute( extractQName( attr.getOwnerElement() ), extractQName( attr ), value, apply.rule() );
+            attr.setValue( value );
+          } else {
+            throw new IllegalArgumentException( RES.unexpectedSelectedNodeType( node ) );
+          }
+        }
+      } else if( selector instanceof UrlRewriteFilterDetectDescriptor) {
+        XPathExpression path = (XPathExpression)selector.compiledPath( XPATH_COMPILER );
+        Object node = path.evaluate( level.scopeNode, XPathConstants.NODE );
+        if( node != null ) {
+          UrlRewriteFilterDetectDescriptor detect = (UrlRewriteFilterDetectDescriptor)selector;
+          String value = null;
+          if( node instanceof Element ) {
+            Element element = (Element)node;
+            value = element.getTextContent();
+          } else if( node instanceof Text ) {
+            Text text = (Text)node;
+            value = text.getWholeText();
+          } else if( node instanceof Attr ) {
+            Attr attr = (Attr)node;
+            value = attr.getValue();
+          } else {
+            throw new IllegalArgumentException( RES.unexpectedSelectedNodeType( node ) );
+          }
+          if( detect.compiledValue( REGEX_COMPILER ).matcher( value ).matches() ) {
+            processBufferedElement( level, detect );
+          }
+        }
+      } else {
+        throw new IllegalArgumentException( RES.unexpectedRewritePathSelector( selector ) );
+      }
+    }
+  }
+
+  private void processBufferedElement( Level level ) throws XPathExpressionException, IOException {
+    processBufferedElement( level, level.scopeConfig );
+    writeBufferedElement( level.node, writer );
+  }
+
+  private QName extractQName( Node node ) {
+    QName qname;
+    String localName = node.getLocalName();
+    if( localName == null ) {
+      qname = new QName( node.getNodeName() );
+    } else {
+      if ( node.getPrefix() == null ) { 
+        qname = new QName( node.getNamespaceURI(), localName );
+      } else {
+        qname = new QName( node.getNamespaceURI(), localName, node.getPrefix() );
+      }
+      
+    }
+    return qname;
+  }
+
+  private void bufferAttributes( StartElement event, Element element ) {
+    Iterator attributes = event.getAttributes();
+    while( attributes.hasNext() ) {
+      Attribute attribute = (Attribute)attributes.next();
+      bufferAttribute( element, attribute );
+    }
+  }
+
+  private Attr bufferAttribute( Element element, Attribute attribute ) {
+    QName name = attribute.getName();
+    String prefix = name.getPrefix();
+    String uri = name.getNamespaceURI();
+    Attr node;
+    if( uri == null || uri.isEmpty() ) {
+      node = document.createAttribute( name.getLocalPart() );
+      element.setAttributeNode( node );
+    } else {
+      node = document.createAttributeNS( uri, name.getLocalPart() );
+      if( prefix != null && !prefix.isEmpty() ) {
+        node.setPrefix( prefix );
+      }
+      element.setAttributeNodeNS( node );
+    }
+    node.setTextContent( attribute.getValue() );
+    return node;
+  }
+
+  private void streamNamespaces( StartElement event ) {
+    Iterator i = event.getNamespaces();
+    while( i.hasNext() ) {
+      Namespace ns = (Namespace)i.next();
+      writer.write( " xmlns" );
+      if( !ns.isDefaultNamespaceDeclaration() ) {
+        writer.write( ":" );
+        writer.write( ns.getPrefix() );
+      }
+      writer.write( "=\"" );
+      writer.write( ns.getNamespaceURI() );
+      writer.write( "\"" );
+    }
+  }
+
+  private void streamAttributes( StartElement event, Element element ) throws XPathExpressionException {
+    Iterator i = event.getAttributes();
+    while( i.hasNext() ) {
+      Attribute attribute = (Attribute)i.next();
+      streamAttribute( element, attribute );
+    }
+  }
+
+  private void streamAttribute( Element element, Attribute attribute ) throws XPathExpressionException {
+    Attr node;
+    QName name = attribute.getName();
+    String prefix = name.getPrefix();
+    String uri = name.getNamespaceURI();
+    if( uri == null || uri.isEmpty() ) {
+      node = document.createAttribute( name.getLocalPart() );
+      element.setAttributeNode( node );
+    } else {
+      node = document.createAttributeNS( uri, name.getLocalPart() );
+      if( prefix != null && !prefix.isEmpty() ) {
+        node.setPrefix( prefix );
+      }
+      element.setAttributeNodeNS( node );
+    }
+
+    String value = attribute.getValue();
+    Level level = stack.peek();
+    if( ( level.scopeConfig ) == null || ( level.scopeConfig.getSelectors().isEmpty() ) ) {
+      value = filterAttribute( null, attribute.getName(), value, null );
+      node.setValue( value );
+    } else {
+      UrlRewriteFilterPathDescriptor path = pickFirstMatchingPath( level );
+      if( path instanceof UrlRewriteFilterApplyDescriptor ) {
+        String rule = ((UrlRewriteFilterApplyDescriptor)path).rule();
+        value = filterAttribute( null, attribute.getName(), value, rule );
+        node.setValue( value );
+      }
+    }
+
+    //dump( document );
+
+    if( prefix == null || prefix.isEmpty() ) {
+      writer.write( " " );
+      writer.write( name.getLocalPart() );
+    } else {
+      writer.write( " " );
+      writer.write( prefix );
+      writer.write( ":" );
+      writer.write( name.getLocalPart() );
+    }
+    writer.write( "=\"" );
+    writer.write( value );
+    writer.write( "\"" );
+    element.removeAttributeNode( node );
+  }
+
+  private void processCharacters( Characters event ) throws XPathExpressionException {
+    //System.out.println( "T[" + event.isCData() + "," + event.isWhiteSpace() + "," + event.isIgnorableWhiteSpace() + "]=" + event );
+    Level level = stack.peek();
+    Node node = stack.peek().node;
+    if( event.isCData() ) {
+      node.appendChild( document.createCDATASection( event.getData() ) );
+    } else {
+      node.appendChild( document.createTextNode( event.getData() ) );
+    }
+    if( !currentlyBuffering() ) {
+      String value = event.getData();
+      if( !event.isWhiteSpace() ) {
+        if( level.scopeConfig == null || level.scopeConfig.getSelectors().isEmpty() ) {
+          value = filterText( extractQName( node ), value, null );
+        } else {
+          UrlRewriteFilterPathDescriptor path = pickFirstMatchingPath( level );
+          if( path instanceof UrlRewriteFilterApplyDescriptor ) {
+            String rule = ((UrlRewriteFilterApplyDescriptor)path).rule();
+            value = filterText( extractQName( node ), value, rule );
+          }
+        }
+      }
+      if( event.isCData() ) {
+        writer.write( "<![CDATA[" );
+        writer.write( value );
+        writer.write( "]]>" );
+      } else {
+        writer.write( StringEscapeUtils.escapeXml( value ) );
+      }  
+    }
+  }
+
+  private void processComment( Comment event ) {
+    //System.out.println( "C=" + event );
+    if( currentlyBuffering() ) {
+      stack.peek().node.appendChild( document.createComment( event.getText() ) );
+    } else {
+      writer.write( "<!--" );
+      writer.write( event.getText() );
+      writer.write( "-->" );
+    }
+  }
+
+  @Override
+  public void close() throws IOException {
+    try {
+      parser.close();
+    } catch( XMLStreamException e ) {
+      throw new IOException( e );
+    }
+    reader.close();
+    writer.close();
+    stack.clear();
+  }
+
+  protected UrlRewriteFilterPathDescriptor pickFirstMatchingPath( Level level ) {
+    UrlRewriteFilterPathDescriptor match = null;
+    if( level.scopeConfig != null ) {
+      for( UrlRewriteFilterPathDescriptor selector : level.scopeConfig.getSelectors() ) {
+        try {
+          XPathExpression path = (XPathExpression)selector.compiledPath( XPATH_COMPILER );
+          Object node = path.evaluate( level.scopeNode, XPathConstants.NODE );
+          if( node != null ) {
+            match = selector;
+            break;
+          }
+        } catch( XPathExpressionException e ) {
+          throw new IllegalArgumentException( selector.path(), e );
+        }
+      }
+    }
+    return match;
+  }
+
+  private boolean currentlyBuffering() {
+    return stack.peek().buffered;
+  }
+
+  private Level pushLevel( Level parent, XMLEvent event, Node node, Node scopeNode, UrlRewriteFilterGroupDescriptor scopeConfig ) {
+    Level level = new Level( parent, event, node, scopeNode, scopeConfig );
+    stack.push( level );
+    return level;
+  }
+
+  private static class Level {
+//    private Level parent;
+//    private XMLEvent event;
+    private Node node;
+    private UrlRewriteFilterGroupDescriptor scopeConfig;
+    private Node scopeNode;
+    private boolean buffered;
+
+    private Level( Level parent, XMLEvent event, Node node, Node scopeNode, UrlRewriteFilterGroupDescriptor scopeConfig ) {
+//      this.parent = parent;
+//      this.event = event;
+      this.node = node;
+      this.scopeConfig = scopeConfig;
+      this.scopeNode = scopeNode;
+      this.buffered = ( ( parent != null ) && parent.buffered ) ||
+                      ( ( scopeConfig != null ) && ( scopeConfig instanceof UrlRewriteFilterBufferDescriptor ) );
+    }
+  }
+
+  private static class XmlPathCompiler implements UrlRewriteFilterPathDescriptor.Compiler<XPathExpression> {
+    private static XPath XPATH = XPathFactory.newInstance().newXPath();
+    @Override
+    public XPathExpression compile( String expression, XPathExpression compiled ) {
+      try {
+        return XPATH.compile( expression );
+      } catch( XPathExpressionException e ) {
+        throw new IllegalArgumentException( e );
+      }
+    }
+  }
+
+  private static class RegexCompiler implements UrlRewriteFilterPathDescriptor.Compiler<Pattern> {
+    @Override
+    public Pattern compile( String expression, Pattern compiled ) {
+      if( compiled != null ) {
+        return compiled;
+      } else {
+        return Pattern.compile( expression );
+      }
+    }
+  }
+
+  private static final void writeBufferedElement( Node node, Writer writer ) throws IOException {
+    try {
+      Transformer t = XmlUtils.getTransformer( false, false, 0, true );
+      t.transform( new DOMSource( node ), new StreamResult( writer ) );
+    } catch( TransformerException e ) {
+      throw new IOException( e );
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlRewriteRulesDigester.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlRewriteRulesDigester.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlRewriteRulesDigester.java
new file mode 100644
index 0000000..2c5b3c6
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlRewriteRulesDigester.java
@@ -0,0 +1,239 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.xml;
+
+import org.apache.commons.digester3.Digester;
+import org.apache.commons.digester3.Rule;
+import org.apache.commons.digester3.SetPropertiesRule;
+import org.apache.commons.digester3.binder.AbstractRulesModule;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterGroupDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFlowDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptorFactory;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptorFactory;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptorFactory;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteFilterApplyDescriptorImpl;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteFilterBufferDescriptorImpl;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteFilterDetectDescriptorImpl;
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteFilterScopeDescriptorImpl;
+import org.xml.sax.Attributes;
+
+public class XmlRewriteRulesDigester extends AbstractRulesModule implements XmlRewriteRulesTags {
+
+  @Override
+  protected void configure() {
+    forPattern( ROOT ).addRule( new RulesFactory() );
+    forPattern( ROOT ).addRule( new SetPropertiesRule() );
+
+    for( String name : UrlRewriteFunctionDescriptorFactory.getNames() ) {
+      forPattern( ROOT + "/" + FUNCTIONS + "/" + name ).addRule( new FunctionFactory() );
+      forPattern( ROOT + "/" + FUNCTIONS + "/" + name ).addRule( new SetPropertiesRule() );
+    }
+
+    forPattern( ROOT + "/" + RULE ).addRule( new RuleFactory() );
+    forPattern( ROOT + "/" + RULE ).addRule( new SetPropertiesRule() );
+    for( String type : UrlRewriteStepDescriptorFactory.getTypes() ) {
+      forPattern( "*/" + type ).addRule( new StepFactory() );
+      forPattern( "*/" + type ).addRule( new SetPropertiesRule() );
+    }
+
+    forPattern( ROOT + "/" + FILTER ).addRule( new FilterFactory() );
+    forPattern( ROOT + "/" + FILTER ).addRule( new SetPropertiesRule() );
+    forPattern( ROOT + "/" + FILTER + "/" + CONTENT ).addRule( new FilterContentFactory() );
+    forPattern( ROOT + "/" + FILTER + "/" + CONTENT ).addRule( new SetPropertiesRule() );
+
+    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/*/" + APPLY ).addRule( new FilterApplyFactory() );
+    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/*/" + APPLY ).addRule( new SetPropertiesRule() );
+
+    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/" + SCOPE ).addRule( new FilterScopeFactory() );
+    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/" + SCOPE ).addRule( new SetPropertiesRule() );
+
+    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/" + BUFFER ).addRule( new FilterBufferFactory() );
+    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/" + BUFFER ).addRule( new SetPropertiesRule() );
+
+    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/" + BUFFER + "/" + DETECT ).addRule( new FilterDetectFactory() );
+    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/" + BUFFER + "/" + DETECT ).addRule( new SetPropertiesRule() );
+
+//    forPattern( "*/" + MATCH ).addRule( new MatchFactory() );
+//    forPattern( "*/" + MATCH ).addRule( new SetPropertiesRule() );
+//    forPattern( "*/" + CHECK ).addRule( new CheckFactory() );
+//    forPattern( "*/" + CHECK ).addRule( new SetPropertiesRule() );
+//    forPattern( "*/" + CONTROL ).addRule( new ControlFactory() );
+//    forPattern( "*/" + CONTROL ).addRule( new SetPropertiesRule() );
+//    forPattern( "*/" + ACTION ).addRule( new ActionFactory() );
+//    forPattern( "*/" + ACTION ).addRule( new SetPropertiesRule() );
+  }
+
+  private static class RulesFactory extends FactoryRule {
+    @Override
+    public Object create( String namespace, String name, Attributes attributes ) {
+      return UrlRewriteRulesDescriptorFactory.create();
+    }
+  }
+
+  private static class RuleFactory extends Rule {
+    @Override
+    public void begin( String namespace, String name, Attributes attributes ) throws Exception {
+      Digester digester = getDigester();
+      UrlRewriteRulesDescriptor rules = digester.peek();
+      UrlRewriteRuleDescriptor rule = rules.newRule();
+      getDigester().push( rule );
+    }
+
+    @Override
+    public void end( String namespace, String name ) throws Exception {
+      Digester digester = getDigester();
+      UrlRewriteRuleDescriptor rule = digester.pop();
+      UrlRewriteRulesDescriptor rules = digester.peek();
+      rules.addRule( rule );
+    }
+  }
+
+  private static class StepFactory extends FactoryRule {
+    @Override
+    public Object create( String namespace, String name, Attributes attributes ) {
+      UrlRewriteFlowDescriptor flow = getDigester().peek();
+      return flow.addStep( name );
+    }
+  }
+
+  private static class FunctionFactory extends FactoryRule {
+    @Override
+    public Object create( String namespace, String name, Attributes attributes ) {
+      UrlRewriteRulesDescriptor rules = getDigester().peek();
+      return rules.addFunction( name );
+    }
+  }
+
+  private static class FilterFactory extends FactoryRule {
+    @Override
+    public Object create( String namespace, String name, Attributes attributes ) {
+      UrlRewriteRulesDescriptor parent = getDigester().peek();
+      return parent.addFilter( attributes.getValue( "name" ) );
+    }
+  }
+
+  private static class FilterContentFactory extends FactoryRule {
+    @Override
+    public Object create( String namespace, String name, Attributes attributes ) {
+      UrlRewriteFilterDescriptor parent = getDigester().peek();
+      UrlRewriteFilterContentDescriptor descriptor = parent.addContent( attributes.getValue( "type" ) );
+      if (attributes.getValue( "asType" ) != null) {
+        descriptor = descriptor.asType(attributes.getValue( "asType" ));
+      }
+      return descriptor;
+    }
+  }
+
+  private static class FilterApplyFactory extends FactoryRule {
+    @Override
+    public Object create( String namespace, String name, Attributes attributes ) {
+      UrlRewriteFilterGroupDescriptor parent = getDigester().peek();
+      UrlRewriteFilterPathDescriptor child = new UrlRewriteFilterApplyDescriptorImpl();
+      child.path( attributes.getValue( "path" ) );
+      parent.addSelector( child );
+      return child;
+    }
+  }
+
+  private static class FilterScopeFactory extends FactoryRule {
+    @Override
+    public Object create( String namespace, String name, Attributes attributes ) {
+      UrlRewriteFilterGroupDescriptor parent = getDigester().peek();
+      UrlRewriteFilterPathDescriptor child = new UrlRewriteFilterScopeDescriptorImpl();
+      child.path( attributes.getValue( "path" ) );
+      parent.addSelector( child );
+      return child;
+    }
+  }
+
+  private static class FilterBufferFactory extends FactoryRule {
+    @Override
+    public Object create( String namespace, String name, Attributes attributes ) {
+      UrlRewriteFilterGroupDescriptor parent = getDigester().peek();
+      UrlRewriteFilterPathDescriptor child = new UrlRewriteFilterBufferDescriptorImpl();
+      child.path( attributes.getValue( "path" ) );
+      parent.addSelector( child );
+      return child;
+    }
+  }
+
+  private static class FilterDetectFactory extends FactoryRule {
+    @Override
+    public Object create( String namespace, String name, Attributes attributes ) {
+      UrlRewriteFilterGroupDescriptor parent = getDigester().peek();
+      UrlRewriteFilterPathDescriptor child = new UrlRewriteFilterDetectDescriptorImpl();
+      child.path( attributes.getValue( "path" ) );
+      parent.addSelector( child );
+      return child;
+    }
+  }
+
+//  private static class MatchFactory extends FactoryRule {
+//    @Override
+//    public Object create( String namespace, String name, Attributes attributes ) {
+//      UrlRewriteRuleDescriptor rule = getDigester().peek();
+//      return rule.addMatch();
+//    }
+//  }
+//
+//  private static class CheckFactory extends FactoryRule {
+//    @Override
+//    public Object create( String namespace, String name, Attributes attributes ) {
+//      UrlRewriteRuleDescriptor rule = getDigester().peek();
+//      return rule.addCheck();
+//    }
+//  }
+//
+//  private static class ActionFactory extends FactoryRule {
+//    @Override
+//    public Object create( String namespace, String name, Attributes attributes ) {
+//      UrlRewriteRuleDescriptor rule = getDigester().peek();
+//      return rule.addAction();
+//    }
+//  }
+//
+//  private static class ControlFactory extends FactoryRule {
+//    @Override
+//    public Object create( String namespace, String name, Attributes attributes ) {
+//      UrlRewriteRuleDescriptor rule = getDigester().peek();
+//      return rule.addControl();
+//    }
+//  }
+
+  private static abstract class FactoryRule extends Rule {
+
+    protected abstract Object create( String namespace, String name, Attributes attributes );
+
+    @Override
+    public void begin( String namespace, String name, Attributes attributes ) throws Exception {
+      getDigester().push( create( namespace, name, attributes ) );
+    }
+
+    @Override
+    public void end( String namespace, String name ) throws Exception {
+      getDigester().pop();
+    }
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlRewriteRulesTags.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlRewriteRulesTags.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlRewriteRulesTags.java
new file mode 100644
index 0000000..872521a
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlRewriteRulesTags.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.knox.gateway.filter.rewrite.impl.xml;
+
+/**
+ * <rules>
+ *   <filter name="">
+ *     <content type="json"> == <scope path="$"/>
+ *       <apply/>
+ *       <select>
+ *         <choice>
+ *           <apply/>
+ *         </choice>
+ *       </select>
+ *     </content>
+ *   </filter>
+ * </rules>
+ */
+public interface XmlRewriteRulesTags {
+
+  static final String ROOT = "rules";
+
+  static final String FUNCTIONS = "functions";
+
+  static final String RULE = "rule";
+
+//  static final String MATCH = "match";
+//  static final String CHECK = "check";
+//  static final String CONTROL = "control";
+//  static final String ACTION = "action";
+
+  static final String FILTER = "filter";
+  static final String CONTENT = "content";
+  static final String SCOPE = "scope";
+  static final String BUFFER = "buffer";
+  static final String DETECT = "detect";
+  static final String APPLY = "apply";
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteFilterReader.java
new file mode 100644
index 0000000..68d13db
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteFilterReader.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.knox.gateway.filter.rewrite.impl.xml;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import javax.xml.namespace.QName;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLStreamException;
+import java.io.IOException;
+import java.io.Reader;
+import java.net.URISyntaxException;
+
+public class XmlUrlRewriteFilterReader extends XmlFilterReader {
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+
+  private Resolver resolver;
+  private UrlRewriter rewriter;
+  private UrlRewriter.Direction direction;
+
+  public XmlUrlRewriteFilterReader( Reader reader, UrlRewriter rewriter, Resolver resolver, UrlRewriter.Direction direction, UrlRewriteFilterContentDescriptor config )
+      throws IOException, ParserConfigurationException, XMLStreamException {
+    super( reader, config );
+    this.resolver = resolver;
+    this.rewriter = rewriter;
+    this.direction = direction;
+  }
+
+  //TODO: Need to limit which values are attempted to be filtered by the name.
+  private String filterValueString( String name, String value, String rule ) {
+    try {
+      Template input = Parser.parseLiteral( value );
+      if( input != null ) {
+        Template output = rewriter.rewrite( resolver, input, direction, rule );
+        if( output != null ) {
+          value = output.getPattern();
+        } else {
+          LOG.failedToFilterValue( value, rule );
+        }
+      } else {
+        LOG.failedToParseValueForUrlRewrite( value );
+      }
+    } catch( URISyntaxException e ) {
+      LOG.failedToParseValueForUrlRewrite( value );
+    }
+    return value;
+  }
+
+  @Override
+  protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
+    return filterValueString( attributeName.getLocalPart(), attributeValue, ruleName );
+  }
+
+  @Override
+  protected String filterText( QName elementName, String text, String ruleName ) {
+    return filterValueString( elementName.getLocalPart(), text, ruleName );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporter.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporter.java
new file mode 100644
index 0000000..00927b6
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporter.java
@@ -0,0 +1,200 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.xml;
+
+import org.apache.commons.beanutils.BeanUtils;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterBufferDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterGroupDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterScopeDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFlowDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteRulesExporter;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterDetectDescriptor;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.util.XmlUtils;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.TransformerException;
+import java.beans.BeanInfo;
+import java.beans.IntrospectionException;
+import java.beans.Introspector;
+import java.beans.PropertyDescriptor;
+import java.io.IOException;
+import java.io.Writer;
+import java.lang.reflect.InvocationTargetException;
+
+public class XmlUrlRewriteRulesExporter implements UrlRewriteRulesExporter, XmlRewriteRulesTags {
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+  
+  @Override
+  public String getFormat() {
+    return "xml";
+  }
+
+  @Override
+  public void store( UrlRewriteRulesDescriptor descriptor, Writer writer ) throws IOException {
+    try {
+      Document document = XmlUtils.createDocument();
+
+      Element root = document.createElement( ROOT );
+      document.appendChild( root );
+
+      if( !descriptor.getFunctions().isEmpty() ) {
+        Element functionsElement = document.createElement( FUNCTIONS );
+        root.appendChild( functionsElement );
+        for( UrlRewriteFunctionDescriptor function : descriptor.getFunctions() ) {
+          Element functionElement = createElement( document, function.name(), function );
+          functionsElement.appendChild( functionElement );
+        }
+      }
+
+      if( !descriptor.getRules().isEmpty() ) {
+        for( UrlRewriteRuleDescriptor rule : descriptor.getRules() ) {
+          Element ruleElement = createRule( document, rule );
+          root.appendChild( ruleElement );
+        }
+      }
+
+      if( !descriptor.getFilters().isEmpty() ) {
+        for( UrlRewriteFilterDescriptor filter : descriptor.getFilters() ) {
+          Element filterElement = createFilter( document, filter );
+          root.appendChild( filterElement );
+        }
+      }
+
+      XmlUtils.writeXml( document, writer );
+
+    } catch( ParserConfigurationException e ) {
+      throw new IOException( e );
+    } catch( TransformerException e ) {
+      throw new IOException( e );
+    } catch( InvocationTargetException e ) {
+      LOG.failedToWriteRulesDescriptor( e );
+    } catch( NoSuchMethodException e ) {
+      LOG.failedToWriteRulesDescriptor( e );
+    } catch( IntrospectionException e ) {
+      LOG.failedToWriteRulesDescriptor( e );
+    } catch( IllegalAccessException e ) {
+      LOG.failedToWriteRulesDescriptor( e );
+    }
+  }
+
+  private Element createFilter( Document document, UrlRewriteFilterDescriptor parent )
+      throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
+    Element parentElement = createElement( document, FILTER, parent );
+    for( UrlRewriteFilterContentDescriptor child: parent.getContents() ) {
+      Element childElement = createFilterContent( document, child );
+      parentElement.appendChild( childElement );
+    }
+    return parentElement;
+  }
+
+  private Element createFilterContent( Document document, UrlRewriteFilterContentDescriptor parent )
+      throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
+    Element parentElement = createElement( document, CONTENT, parent );
+    for( UrlRewriteFilterPathDescriptor child: parent.getSelectors() ) {
+      Element childElement = createFilterSelector( document, child );
+      parentElement.appendChild( childElement );
+    }
+    return parentElement;
+  }
+
+  private Element createFilterSelector( Document document, UrlRewriteFilterPathDescriptor parent )
+      throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
+    Element parentElement = createElement( document, toTagName( parent ), parent );
+    if( parent instanceof UrlRewriteFilterGroupDescriptor) {
+      for( UrlRewriteFilterPathDescriptor child: ((UrlRewriteFilterGroupDescriptor)parent).getSelectors() ) {
+        Element childElement = createFilterSelector( document, child );
+        parentElement.appendChild( childElement );
+      }
+    }
+    return parentElement;
+  }
+
+  private Element createRule( Document document, UrlRewriteRuleDescriptor rule )
+      throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
+    Element ruleElement = createElement( document, RULE, rule );
+    for( UrlRewriteStepDescriptor step: rule.steps() ) {
+      Element childElement = createStep( document, step );
+      ruleElement.appendChild( childElement );
+    }
+    return ruleElement;
+  }
+
+  private Element createStep( Document document, UrlRewriteStepDescriptor step )
+      throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
+    Element parentElement = createElement( document, step.type(), step );
+    if( step instanceof UrlRewriteFlowDescriptor) {
+      UrlRewriteFlowDescriptor flow = (UrlRewriteFlowDescriptor)step;
+      for( Object child: flow.steps() ) {
+        UrlRewriteStepDescriptor childStep = (UrlRewriteStepDescriptor)child;
+        Element childElement = createStep( document, childStep );
+        parentElement.appendChild( childElement );
+      }
+
+    }
+    return parentElement;
+  }
+
+  private Element createElement( Document document, String name, Object bean )
+      throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
+    Element element = document.createElement( name );
+    BeanInfo beanInfo = Introspector.getBeanInfo( bean.getClass(), Object.class );
+    for( PropertyDescriptor propInfo: beanInfo.getPropertyDescriptors() ) {
+      String propName = propInfo.getName();
+      if( propInfo.getReadMethod() != null && String.class.isAssignableFrom( propInfo.getPropertyType() ) ) {
+        String propValue = BeanUtils.getProperty( bean, propName );
+        if( propValue != null && !propValue.isEmpty() ) {
+          // Doing it the hard way to avoid having the &'s in the query string escaped at &amp;
+          Attr attr = document.createAttribute( propName );
+          attr.setValue( propValue );
+          element.setAttributeNode( attr );
+          //element.setAttribute( propName, propValue );
+        }
+      }
+    }
+    return element;
+  }
+
+  private static String toTagName( final UrlRewriteFilterPathDescriptor descriptor ) {
+    if( descriptor instanceof UrlRewriteFilterApplyDescriptor) {
+      return APPLY;
+    } else if( descriptor instanceof UrlRewriteFilterDetectDescriptor) {
+      return DETECT;
+    } else if( descriptor instanceof UrlRewriteFilterBufferDescriptor) {
+      return BUFFER;
+    } else if( descriptor instanceof UrlRewriteFilterScopeDescriptor) {
+      return SCOPE;
+    } else {
+      throw new IllegalArgumentException();
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesImporter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesImporter.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesImporter.java
new file mode 100644
index 0000000..ec60826
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesImporter.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.knox.gateway.filter.rewrite.impl.xml;
+
+import org.apache.commons.digester3.Digester;
+import org.apache.commons.digester3.ExtendedBaseRules;
+import org.apache.commons.digester3.binder.DigesterLoader;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteRulesImporter;
+import org.xml.sax.SAXException;
+
+import java.io.IOException;
+import java.io.Reader;
+
+import static org.apache.commons.digester3.binder.DigesterLoader.newLoader;
+
+public class XmlUrlRewriteRulesImporter implements UrlRewriteRulesImporter {
+
+  private static DigesterLoader loader = newLoader( new XmlRewriteRulesDigester() );
+
+  @Override
+  public String getFormat() {
+    return "xml";
+  }
+
+  @Override
+  public UrlRewriteRulesDescriptor load( Reader reader ) throws IOException {
+    Digester digester = loader.newDigester( new ExtendedBaseRules() );
+    digester.setValidating( false );
+    try {
+      UrlRewriteRulesDescriptor rules = digester.parse( reader );
+      return rules;
+    } catch( SAXException e ) {
+      throw new IOException( e );
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteStreamFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteStreamFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteStreamFilter.java
new file mode 100644
index 0000000..d2aa47f
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteStreamFilter.java
@@ -0,0 +1,67 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.xml;
+
+import org.apache.commons.io.input.ReaderInputStream;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStreamFilter;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLStreamException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+public class XmlUrlRewriteStreamFilter implements UrlRewriteStreamFilter {
+
+  private static String[] TYPES = new String[]{ "application/xml", "text/xml", "*/xml" };
+  private static String[] NAMES = new String[]{ null };
+
+  @Override
+  public String[] getTypes() {
+    return TYPES;
+  }
+
+  @Override
+  public String[] getNames() {
+    return NAMES;
+  }
+
+  @Override
+  public InputStream filter(
+      InputStream stream,
+      String encoding,
+      UrlRewriter rewriter,
+      Resolver resolver,
+      UrlRewriter.Direction direction,
+      UrlRewriteFilterContentDescriptor config )
+          throws IOException {
+    try {
+      return new ReaderInputStream(
+          new XmlUrlRewriteFilterReader(
+              new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
+    } catch( ParserConfigurationException e ) {
+      throw new IOException( e );
+    } catch( XMLStreamException e ) {
+      throw new IOException( e );
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteActionDescriptorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteActionDescriptorBase.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteActionDescriptorBase.java
new file mode 100644
index 0000000..7451415
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteActionDescriptorBase.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.knox.gateway.filter.rewrite.spi;
+
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
+
+public abstract class UrlRewriteActionDescriptorBase
+    extends UrlRewriteStepDescriptorBase<UrlRewriteActionDescriptor>
+    implements UrlRewriteActionDescriptor {
+
+  private String operation;
+  private String parameter;
+
+  protected UrlRewriteActionDescriptorBase( String type ) {
+    super( type );
+  }
+
+  @Override
+  public String operation() {
+    return operation;
+  }
+
+  @Override
+  public UrlRewriteActionDescriptor operation( String operation ) {
+    this.operation = operation;
+    return this;
+  }
+
+  public void setOperation( String operation ) {
+    operation( operation );
+  }
+
+  public void setOper( String operation ) {
+    operation( operation );
+  }
+
+  public void setOp( String operation ) {
+    operation( operation );
+  }
+
+  public String getOper() {
+    return operation();
+  }
+
+  @Override
+  public String parameter() {
+    return parameter;
+  }
+
+  @Override
+  public UrlRewriteActionDescriptor parameter( String parameter ) {
+    this.parameter = parameter;
+    return this;
+  }
+
+  public void setParameter( String parameter ) {
+    parameter( parameter );
+  }
+
+  public void setParam( String parameter ) {
+    parameter( parameter );
+  }
+
+  public String getParam() {
+    return parameter();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteContext.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteContext.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteContext.java
new file mode 100644
index 0000000..5aa82c1
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteContext.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.knox.gateway.filter.rewrite.spi;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.util.urltemplate.Evaluator;
+import org.apache.knox.gateway.util.urltemplate.Params;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+public interface UrlRewriteContext {
+
+  UrlRewriter.Direction getDirection();
+
+  Template getOriginalUrl();
+
+  Template getCurrentUrl();
+
+  void setCurrentUrl( Template url );
+
+  /**
+   * Adds parameters to the rewrite context and replaces some of them if they already exist
+   * @param parameters the parameters to be added or replaced
+   */
+  void addParameters( Params parameters );
+
+  Params getParameters();
+
+  Evaluator getEvaluator();
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteFlowDescriptorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteFlowDescriptorBase.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteFlowDescriptorBase.java
new file mode 100644
index 0000000..fcfee24
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteFlowDescriptorBase.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.knox.gateway.filter.rewrite.spi;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFlowDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptorFactory;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepFlow;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public abstract class UrlRewriteFlowDescriptorBase<T> extends UrlRewriteStepDescriptorBase<T> implements
+    UrlRewriteFlowDescriptor<T> {
+
+  private UrlRewriteStepFlow flow;
+  private List<UrlRewriteStepDescriptor> steps = new ArrayList<UrlRewriteStepDescriptor>();
+
+  public UrlRewriteFlowDescriptorBase( String type ) {
+    super( type );
+  }
+
+  @Override
+  public UrlRewriteStepFlow flow() {
+    return flow;
+  }
+
+  @SuppressWarnings( "unchecked" )
+  @Override
+  public <F extends UrlRewriteFlowDescriptor<?>> F flow( String flow ) {
+    setFlow( flow );
+    return (F)this;
+  }
+
+  @SuppressWarnings( "unchecked" )
+  @Override
+  public <F extends UrlRewriteFlowDescriptor<?>> F flow( UrlRewriteStepFlow flow ) {
+    setFlow( flow );
+    return (F)this;
+  }
+
+  public void setFlow( UrlRewriteStepFlow flow ) {
+    this.flow = flow;
+  }
+
+  public void setFlow( String flow ) {
+    flow = flow.trim().toUpperCase();
+    this.flow = Enum.valueOf( UrlRewriteStepFlow.class, flow );
+  }
+
+  public String getFlow() {
+    String str = null;
+    if( flow != null ) {
+      str = flow.toString();
+    }
+    return str;
+  }
+
+  @Override
+  public List<UrlRewriteStepDescriptor> steps() {
+    return steps;
+  }
+
+//  @Override
+//  public UrlRewriteMatchDescriptor addMatch() {
+//    UrlRewriteMatchDescriptor step = new UrlRewriteMatchDescriptorExt();
+//    steps.add( step );
+//    return step;
+//  }
+//
+//  @Override
+//  public UrlRewriteCheckDescriptor addCheck() {
+//    UrlRewriteCheckDescriptor step = new UrlRewriteCheckDescriptorExt();
+//    steps.add( step );
+//    return step;
+//  }
+//
+//  @Override
+//  public UrlRewriteControlDescriptor addControl() {
+//    UrlRewriteControlDescriptor step = new UrlRewriteControlDescriptorExt();
+//    steps.add( step );
+//    return step;
+//  }
+//
+//  @Override
+//  public UrlRewriteActionDescriptor addAction() {
+//    UrlRewriteActionDescriptor step = new UrlRewriteActionDescriptorBase();
+//    steps.add( step );
+//    return step;
+//  }
+
+  @SuppressWarnings( "unchecked" )
+  @Override
+  public <T extends UrlRewriteStepDescriptor<?>> T addStep( String type ) {
+    T step = (T)UrlRewriteStepDescriptorFactory.create( type );
+    steps.add( step );
+    return (T)step;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessor.java
new file mode 100644
index 0000000..8028145
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessor.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.spi;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+public interface UrlRewriteFunctionProcessor<T extends UrlRewriteFunctionDescriptor> extends UrlRewriteResolver {
+
+  String name();
+
+  void initialize( UrlRewriteEnvironment environment, T descriptor ) throws Exception;
+
+  void destroy() throws Exception;
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessorBase.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessorBase.java
new file mode 100644
index 0000000..7638f37
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteFunctionProcessorBase.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.spi;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
+
+public abstract class UrlRewriteFunctionProcessorBase<T extends UrlRewriteFunctionDescriptor> implements UrlRewriteFunctionProcessor<T> {
+
+  public void initialize( UrlRewriteEnvironment environment, T descriptor ) throws Exception {
+  }
+
+  public void destroy() throws Exception {
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteResolver.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteResolver.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteResolver.java
new file mode 100644
index 0000000..c190f55
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteResolver.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.knox.gateway.filter.rewrite.spi;
+
+import java.util.List;
+
+public interface UrlRewriteResolver {
+
+  List<String> resolve( UrlRewriteContext context, List<String> parameter ) throws Exception;
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteRulesExporter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteRulesExporter.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteRulesExporter.java
new file mode 100644
index 0000000..d2dd56e
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteRulesExporter.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.spi;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+
+import java.io.IOException;
+import java.io.Writer;
+
+public interface UrlRewriteRulesExporter {
+
+  String getFormat();
+
+  void store( UrlRewriteRulesDescriptor rules, Writer writer ) throws IOException;
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteRulesImporter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteRulesImporter.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteRulesImporter.java
new file mode 100644
index 0000000..ae963bb
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteRulesImporter.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.spi;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+
+import java.io.IOException;
+import java.io.Reader;
+
+public interface UrlRewriteRulesImporter {
+
+  String getFormat();
+
+  UrlRewriteRulesDescriptor load( Reader reader ) throws IOException;
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStepDescriptorBase.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStepDescriptorBase.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStepDescriptorBase.java
new file mode 100644
index 0000000..b51d036
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStepDescriptorBase.java
@@ -0,0 +1,46 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.spi;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
+
+public abstract class UrlRewriteStepDescriptorBase<T> implements UrlRewriteStepDescriptor<T> {
+
+  private String type;
+
+  public UrlRewriteStepDescriptorBase( String type ) {
+    this.type = type;
+  }
+
+  @Override
+  public String type() {
+    return type;
+  }
+
+  @Override
+  @SuppressWarnings( "unchecked" )
+  public T type( String type ) {
+    this.type = type;
+    return (T)this;
+  }
+
+  public void setType( String type ) {
+    this.type = type;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStepProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStepProcessor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStepProcessor.java
new file mode 100644
index 0000000..bc44db2
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStepProcessor.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.knox.gateway.filter.rewrite.spi;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
+
+public interface UrlRewriteStepProcessor<T extends UrlRewriteStepDescriptor> {
+
+  String getType();
+
+  void initialize( UrlRewriteEnvironment environment, T descriptor ) throws Exception;
+
+  UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception;
+
+  void destroy() throws Exception;
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStepStatus.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStepStatus.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStepStatus.java
new file mode 100644
index 0000000..67e8a36
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/spi/UrlRewriteStepStatus.java
@@ -0,0 +1,20 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.spi;
+
+public enum UrlRewriteStepStatus { SUCCESS, FAILURE, FINISHED }


[50/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-applications/src/main/resources/applications/knoxauth/app/redirecting.jsp
----------------------------------------------------------------------
diff --git a/gateway-applications/src/main/resources/applications/knoxauth/app/redirecting.jsp b/gateway-applications/src/main/resources/applications/knoxauth/app/redirecting.jsp
index 7af5fdc..e3a0673 100644
--- a/gateway-applications/src/main/resources/applications/knoxauth/app/redirecting.jsp
+++ b/gateway-applications/src/main/resources/applications/knoxauth/app/redirecting.jsp
@@ -14,9 +14,9 @@
 -->
 <%@ page import="java.util.Collection" %>
 <%@ page import="java.util.Map" %>
-<%@ page import="org.apache.hadoop.gateway.topology.Topology" %>
-<%@ page import="org.apache.hadoop.gateway.topology.Service" %>
-<%@ page import="org.apache.hadoop.gateway.util.RegExUtils" %>
+<%@ page import="org.apache.knox.gateway.topology.Topology" %>
+<%@ page import="org.apache.knox.gateway.topology.Service" %>
+<%@ page import="org.apache.knox.gateway.util.RegExUtils" %>
 
 <!DOCTYPE html>
 <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7"><![endif]-->

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-demo-ldap-launcher/pom.xml
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap-launcher/pom.xml b/gateway-demo-ldap-launcher/pom.xml
index b5723d3..54aa2b2 100644
--- a/gateway-demo-ldap-launcher/pom.xml
+++ b/gateway-demo-ldap-launcher/pom.xml
@@ -59,7 +59,7 @@
                             </descriptorRefs>
                             <archive>
                                 <manifest>
-                                    <mainClass>org.apache.hadoop.gateway.launcher.Launcher</mainClass>
+                                    <mainClass>org.apache.knox.gateway.launcher.Launcher</mainClass>
                                 </manifest>
                             </archive>
                         </configuration>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/BaseDirectoryService.java
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/BaseDirectoryService.java b/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/BaseDirectoryService.java
deleted file mode 100644
index b519f4b..0000000
--- a/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/BaseDirectoryService.java
+++ /dev/null
@@ -1,2323 +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.hadoop.gateway.security.ldap;
-
-
-import org.apache.directory.api.ldap.codec.api.LdapApiService;
-import org.apache.directory.api.ldap.codec.api.LdapApiServiceFactory;
-import org.apache.directory.api.ldap.model.constants.AuthenticationLevel;
-import org.apache.directory.api.ldap.model.constants.SchemaConstants;
-import org.apache.directory.api.ldap.model.csn.Csn;
-import org.apache.directory.api.ldap.model.csn.CsnFactory;
-import org.apache.directory.api.ldap.model.cursor.Cursor;
-import org.apache.directory.api.ldap.model.entry.Attribute;
-import org.apache.directory.api.ldap.model.entry.DefaultEntry;
-import org.apache.directory.api.ldap.model.entry.Entry;
-import org.apache.directory.api.ldap.model.entry.Modification;
-import org.apache.directory.api.ldap.model.entry.Value;
-import org.apache.directory.api.ldap.model.exception.LdapException;
-import org.apache.directory.api.ldap.model.exception.LdapNoPermissionException;
-import org.apache.directory.api.ldap.model.exception.LdapOperationException;
-import org.apache.directory.api.ldap.model.ldif.ChangeType;
-import org.apache.directory.api.ldap.model.ldif.LdifEntry;
-import org.apache.directory.api.ldap.model.ldif.LdifReader;
-import org.apache.directory.api.ldap.model.name.Dn;
-import org.apache.directory.api.ldap.model.name.DnUtils;
-import org.apache.directory.api.ldap.model.name.Rdn;
-import org.apache.directory.api.ldap.model.schema.SchemaManager;
-import org.apache.directory.api.ldap.util.tree.DnNode;
-import org.apache.directory.api.util.DateUtils;
-import org.apache.directory.api.util.Strings;
-import org.apache.directory.api.util.exception.NotImplementedException;
-import org.apache.directory.server.constants.ServerDNConstants;
-import org.apache.directory.server.core.DefaultOperationManager;
-import org.apache.directory.server.core.admin.AdministrativePointInterceptor;
-import org.apache.directory.server.core.api.*;
-import org.apache.directory.server.core.api.administrative.AccessControlAdministrativePoint;
-import org.apache.directory.server.core.api.administrative.CollectiveAttributeAdministrativePoint;
-import org.apache.directory.server.core.api.administrative.SubschemaAdministrativePoint;
-import org.apache.directory.server.core.api.administrative.TriggerExecutionAdministrativePoint;
-import org.apache.directory.server.core.api.changelog.ChangeLog;
-import org.apache.directory.server.core.api.changelog.ChangeLogEvent;
-import org.apache.directory.server.core.api.changelog.Tag;
-import org.apache.directory.server.core.api.changelog.TaggableSearchableChangeLogStore;
-import org.apache.directory.server.core.api.event.EventService;
-import org.apache.directory.server.core.api.interceptor.BaseInterceptor;
-import org.apache.directory.server.core.api.interceptor.Interceptor;
-import org.apache.directory.server.core.api.interceptor.context.AddOperationContext;
-import org.apache.directory.server.core.api.interceptor.context.BindOperationContext;
-import org.apache.directory.server.core.api.interceptor.context.HasEntryOperationContext;
-import org.apache.directory.server.core.api.interceptor.context.LookupOperationContext;
-import org.apache.directory.server.core.api.interceptor.context.OperationContext;
-import org.apache.directory.server.core.api.journal.Journal;
-import org.apache.directory.server.core.api.partition.Partition;
-import org.apache.directory.server.core.api.partition.PartitionNexus;
-import org.apache.directory.server.core.api.schema.SchemaPartition;
-import org.apache.directory.server.core.api.subtree.SubentryCache;
-import org.apache.directory.server.core.api.subtree.SubtreeEvaluator;
-import org.apache.directory.server.core.authn.AuthenticationInterceptor;
-import org.apache.directory.server.core.authn.ppolicy.PpolicyConfigContainer;
-import org.apache.directory.server.core.authz.AciAuthorizationInterceptor;
-import org.apache.directory.server.core.authz.DefaultAuthorizationInterceptor;
-import org.apache.directory.server.core.changelog.ChangeLogInterceptor;
-import org.apache.directory.server.core.changelog.DefaultChangeLog;
-import org.apache.directory.server.core.collective.CollectiveAttributeInterceptor;
-import org.apache.directory.server.core.event.EventInterceptor;
-import org.apache.directory.server.core.exception.ExceptionInterceptor;
-import org.apache.directory.server.core.journal.DefaultJournal;
-import org.apache.directory.server.core.journal.JournalInterceptor;
-import org.apache.directory.server.core.normalization.NormalizationInterceptor;
-import org.apache.directory.server.core.operational.OperationalAttributeInterceptor;
-import org.apache.directory.server.core.referral.ReferralInterceptor;
-import org.apache.directory.server.core.schema.SchemaInterceptor;
-import org.apache.directory.server.core.security.TlsKeyGenerator;
-import org.apache.directory.server.core.shared.DefaultCoreSession;
-import org.apache.directory.server.core.shared.DefaultDnFactory;
-import org.apache.directory.server.core.shared.partition.DefaultPartitionNexus;
-import org.apache.directory.server.core.subtree.SubentryInterceptor;
-import org.apache.directory.server.core.trigger.TriggerInterceptor;
-import org.apache.directory.server.i18n.I18n;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-import java.io.StringReader;
-import java.lang.reflect.Method;
-import java.nio.channels.FileLock;
-import java.nio.channels.OverlappingFileLockException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-
-/**
- * Base implementation of {@link DirectoryService}.
- * This is a copy of org.apache.directory.server.core.DefaultDirectoryService
- * created to make showSecurityWarnings protected.  This can be removed
- * when http://svn.apache.org/r1546144 in ApacheDS 2.0.0-M16 is available.
- *
- * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
- */
-public class BaseDirectoryService implements DirectoryService
-{
-  /** The logger */
-  private static final Logger LOG = LoggerFactory.getLogger( BaseDirectoryService.class );
-
-  private SchemaPartition schemaPartition;
-
-  /** A reference on the SchemaManager */
-  private SchemaManager schemaManager;
-
-  /** The LDAP Codec Service */
-  private LdapApiService ldapCodecService = LdapApiServiceFactory.getSingleton();
-
-  /** the root nexus */
-  private DefaultPartitionNexus partitionNexus;
-
-  /** whether or not server is started for the first time */
-  private boolean firstStart;
-
-  /** whether or not this instance has been shutdown */
-  private boolean started;
-
-  /** the change log service */
-  private ChangeLog changeLog;
-
-  /** the journal service */
-  private Journal journal;
-
-  /**
-   * the interface used to perform various operations on this
-   * DirectoryService
-   */
-  private OperationManager operationManager = new DefaultOperationManager( this );
-
-  /** the distinguished name of the administrative user */
-  private Dn adminDn;
-
-  /** session used as admin for internal operations */
-  private CoreSession adminSession;
-
-  /** The referral manager */
-  private ReferralManager referralManager;
-
-  /** A flag to tell if the userPassword attribute's value must be hidden */
-  private boolean passwordHidden = false;
-
-  /** The service's CSN factory */
-  private CsnFactory csnFactory;
-
-  /** The directory instance replication ID */
-  private int replicaId;
-
-  /** remove me after implementation is completed */
-  private static final String PARTIAL_IMPL_WARNING =
-      "WARNING: the changelog is only partially operational and will revert\n" +
-          "state without consideration of who made the original change.  All reverting " +
-          "changes are made by the admin user.\n Furthermore the used controls are not at " +
-          "all taken into account";
-
-  /** The delay to wait between each sync on disk */
-  private long syncPeriodMillis;
-
-  /** The default delay to wait between sync on disk : 15 seconds */
-  private static final long DEFAULT_SYNC_PERIOD = 15000;
-
-  /** */
-  private Thread workerThread;
-
-  /** The default timeLimit : 100 entries */
-  public static final int MAX_SIZE_LIMIT_DEFAULT = 100;
-
-  /** The default timeLimit : 10 seconds */
-  public static final int MAX_TIME_LIMIT_DEFAULT = 10000;
-
-  /** The instance Id */
-  private String instanceId;
-
-  /** The server directory layout*/
-  private InstanceLayout instanceLayout;
-
-  /**
-   * A flag used to shutdown the VM when stopping the server. Useful
-   * when the server is standalone. If the server is embedded, we don't
-   * want to shutdown the VM
-   */
-  private boolean exitVmOnShutdown = true; // allow by default
-
-  /** A flag used to indicate that a shutdown hook has been installed */
-  private boolean shutdownHookEnabled = true; // allow by default
-
-  /** Manage anonymous access to entries other than the RootDSE */
-  private boolean allowAnonymousAccess = false; // forbid by default
-
-  /** Manage the basic access control checks */
-  private boolean accessControlEnabled; // off by default
-
-  /** Manage the operational attributes denormalization */
-  private boolean denormalizeOpAttrsEnabled; // off by default
-
-  /** The list of declared interceptors */
-  private List<Interceptor> interceptors;
-  private Map<String, Interceptor> interceptorNames;
-
-  /** A lock to protect the interceptors List */
-  private ReadWriteLock interceptorsLock = new ReentrantReadWriteLock();
-
-  /** The read and write locks */
-  private Lock readLock = interceptorsLock.readLock();
-  private Lock writeLock = interceptorsLock.writeLock();
-
-  /** A map associating a list of interceptor to each operation */
-  private Map<OperationEnum, List<String>> operationInterceptors;
-
-  /** The System partition */
-  private Partition systemPartition;
-
-  /** The set of all declared partitions */
-  private Set<Partition> partitions = new HashSet<>();
-
-  /** A list of LDIF entries to inject at startup */
-  private List<? extends LdifEntry> testEntries = new ArrayList<LdifEntry>(); // List<Attributes>
-
-  /** The event service */
-  private EventService eventService;
-
-  /** The maximum size for an incoming PDU */
-  private int maxPDUSize = Integer.MAX_VALUE;
-
-  /** the value of last successful add/update operation's CSN */
-  private String contextCsn;
-
-  /** lock file for directory service's working directory */
-  private RandomAccessFile lockFile = null;
-
-  private static final String LOCK_FILE_NAME = ".dirservice.lock";
-
-  /** the ehcache based cache service */
-  private CacheService cacheService;
-
-  /** The AccessControl AdministrativePoint cache */
-  private DnNode<AccessControlAdministrativePoint> accessControlAPCache;
-
-  /** The CollectiveAttribute AdministrativePoint cache */
-  private DnNode<CollectiveAttributeAdministrativePoint> collectiveAttributeAPCache;
-
-  /** The Subschema AdministrativePoint cache */
-  private DnNode<SubschemaAdministrativePoint> subschemaAPCache;
-
-  /** The TriggerExecution AdministrativePoint cache */
-  private DnNode<TriggerExecutionAdministrativePoint> triggerExecutionAPCache;
-
-  /** The Dn factory */
-  private DnFactory dnFactory;
-
-  /** The Subentry cache */
-  SubentryCache subentryCache = new SubentryCache();
-
-  /** The Subtree evaluator instance */
-  private SubtreeEvaluator evaluator;
-
-
-  // ------------------------------------------------------------------------
-  // Constructor
-  // ------------------------------------------------------------------------
-
-  /**
-   * Creates a new instance of the directory service.
-   */
-  public BaseDirectoryService() throws Exception
-  {
-    changeLog = new DefaultChangeLog();
-    journal = new DefaultJournal();
-    syncPeriodMillis = DEFAULT_SYNC_PERIOD;
-    csnFactory = new CsnFactory( replicaId );
-    evaluator = new SubtreeEvaluator( schemaManager );
-    setDefaultInterceptorConfigurations();
-  }
-
-
-  // ------------------------------------------------------------------------
-  // C O N F I G U R A T I O N   M E T H O D S
-  // ------------------------------------------------------------------------
-
-  public void setInstanceId( String instanceId )
-  {
-    this.instanceId = instanceId;
-  }
-
-
-  public String getInstanceId()
-  {
-    return instanceId;
-  }
-
-
-  /**
-   * Gets the {@link Partition}s used by this DirectoryService.
-   *
-   * @return the set of partitions used
-   */
-  public Set<? extends Partition> getPartitions()
-  {
-    Set<Partition> cloned = new HashSet<>();
-    cloned.addAll( partitions );
-    return cloned;
-  }
-
-
-  /**
-   * Sets {@link Partition}s used by this DirectoryService.
-   *
-   * @param partitions the partitions to used
-   */
-  public void setPartitions( Set<? extends Partition> partitions )
-  {
-    Set<Partition> cloned = new HashSet<>();
-    cloned.addAll( partitions );
-    Set<String> names = new HashSet<>();
-
-    for ( Partition partition : cloned )
-    {
-      String id = partition.getId();
-
-      if ( names.contains( id ) )
-      {
-        LOG.warn( "Encountered duplicate partition {} identifier.", id );
-      }
-
-      names.add( id );
-    }
-
-    this.partitions = cloned;
-  }
-
-
-  /**
-   * Returns <tt>true</tt> if access control checks are enabled.
-   *
-   * @return true if access control checks are enabled, false otherwise
-   */
-  public boolean isAccessControlEnabled()
-  {
-    return accessControlEnabled;
-  }
-
-
-  /**
-   * Sets whether to enable basic access control checks or not.
-   *
-   * @param accessControlEnabled true to enable access control checks, false otherwise
-   */
-  public void setAccessControlEnabled( boolean accessControlEnabled )
-  {
-    this.accessControlEnabled = accessControlEnabled;
-  }
-
-
-  /**
-   * Returns <tt>true</tt> if anonymous access is allowed on entries besides the RootDSE.
-   * If the access control subsystem is enabled then access to some entries may not be
-   * allowed even when full anonymous access is enabled.
-   *
-   * @return true if anonymous access is allowed on entries besides the RootDSE, false
-   * if anonymous access is allowed to all entries.
-   */
-  public boolean isAllowAnonymousAccess()
-  {
-    return allowAnonymousAccess;
-  }
-
-
-  /**
-   * Sets whether to allow anonymous access to entries other than the RootDSE.  If the
-   * access control subsystem is enabled then access to some entries may not be allowed
-   * even when full anonymous access is enabled.
-   *
-   * @param enableAnonymousAccess true to enable anonymous access, false to disable it
-   */
-  public void setAllowAnonymousAccess( boolean enableAnonymousAccess )
-  {
-    this.allowAnonymousAccess = enableAnonymousAccess;
-  }
-
-
-  /**
-   * Returns interceptors in the server.
-   *
-   * @return the interceptors in the server.
-   */
-  public List<Interceptor> getInterceptors()
-  {
-    List<Interceptor> cloned = new ArrayList<Interceptor>();
-
-    readLock.lock();
-
-    try
-    {
-      cloned.addAll( interceptors );
-
-      return cloned;
-    }
-    finally
-    {
-      readLock.unlock();
-    }
-  }
-
-
-  /**
-   * Returns interceptors in the server for a given operation.
-   *
-   * @return the interceptors in the server for the given operation.
-   */
-  public List<String> getInterceptors( OperationEnum operation )
-  {
-    List<String> cloned = new ArrayList<String>();
-
-    readLock.lock();
-
-    try
-    {
-      cloned.addAll( operationInterceptors.get( operation ) );
-
-      return cloned;
-    }
-    finally
-    {
-      readLock.unlock();
-    }
-
-  }
-
-
-  /**
-   * Compute the list of  to call for each operation
-   */
-  private void initOperationsList()
-  {
-    writeLock.lock();
-
-    try
-    {
-      operationInterceptors = new ConcurrentHashMap<OperationEnum, List<String>>();
-
-      for ( OperationEnum operation : OperationEnum.getOperations() )
-      {
-        List<String> operationList = new ArrayList<String>();
-
-        for ( Interceptor interceptor : interceptors )
-        {
-          gatherInterceptors( interceptor, interceptor.getClass(), operation, operationList );
-        }
-
-        operationInterceptors.put( operation, operationList );
-      }
-    }
-    finally
-    {
-      writeLock.unlock();
-    }
-  }
-
-
-  /**
-   * Recursively checks if the given interceptor can be added to the list of interceptors for a given
-   * operation and adds to the list of interceptors if it implements the respective operation
-   *
-   * @param interceptor the instance of the interceptor
-   * @param interceptorClz the class of the interceptor
-   * @param operation type of operation
-   * @param selectedInterceptorList the list of selected interceptors
-   */
-  private void gatherInterceptors( Interceptor interceptor, Class<?> interceptorClz, OperationEnum operation,
-                                   List<String> selectedInterceptorList )
-  {
-    // We stop recursing when we reach the Base class
-    if ( ( interceptorClz == null ) || ( interceptorClz == BaseInterceptor.class ) )
-    {
-      return;
-    }
-
-    // We don't call getMethods() because it would get back the default methods
-    // from the BaseInterceptor, something we don't want.
-    Method[] methods = interceptorClz.getDeclaredMethods();
-
-    for ( Method method : methods )
-    {
-      Class<?>[] param = method.getParameterTypes();
-      boolean hasCorrestSig = false;
-
-      // check for the correct signature
-      if ( ( param == null ) || ( param.length > 1 ) || ( param.length == 0 ) )
-      {
-        continue;
-      }
-
-      if ( OperationContext.class.isAssignableFrom( param[0] ) )
-      {
-        hasCorrestSig = true;
-      }
-      else
-      {
-        continue;
-      }
-
-      if ( hasCorrestSig && method.getName().equals( operation.getMethodName() ) )
-      {
-        if ( !selectedInterceptorList.contains( interceptor.getName() ) )
-        {
-          selectedInterceptorList.add( interceptor.getName() );
-        }
-
-        break;
-      }
-    }
-
-    // Recurse on extended classes, as we have used getDeclaredMethods() instead of getmethods()
-    gatherInterceptors( interceptor, interceptorClz.getSuperclass(), operation, selectedInterceptorList );
-  }
-
-
-  /**
-   * Add an interceptor to the list of interceptors to call for each operation
-   * @throws LdapException
-   */
-  private void addInterceptor( Interceptor interceptor, int position ) throws LdapException
-  {
-    // First, init the interceptor
-    interceptor.init( this );
-
-    writeLock.lock();
-
-    try
-    {
-      for ( OperationEnum operation : OperationEnum.getOperations() )
-      {
-        List<String> operationList = operationInterceptors.get( operation );
-
-        Method[] methods = interceptor.getClass().getDeclaredMethods();
-
-        for ( Method method : methods )
-        {
-          if ( method.getName().equals( operation.getMethodName() ) )
-          {
-            if ( position == -1 )
-            {
-              operationList.add( interceptor.getName() );
-            }
-            else
-            {
-              operationList.add( position, interceptor.getName() );
-            }
-
-            break;
-          }
-        }
-      }
-
-      interceptorNames.put( interceptor.getName(), interceptor );
-
-      if ( position == -1 )
-      {
-        interceptors.add( interceptor );
-      }
-      else
-      {
-        interceptors.add( position, interceptor );
-      }
-    }
-    finally
-    {
-      writeLock.unlock();
-    }
-  }
-
-
-  /**
-   * Remove an interceptor to the list of interceptors to call for each operation
-   */
-  private void removeOperationsList( String interceptorName )
-  {
-    Interceptor interceptor = interceptorNames.get( interceptorName );
-
-    writeLock.lock();
-
-    try
-    {
-      for ( OperationEnum operation : OperationEnum.getOperations() )
-      {
-        List<String> operationList = operationInterceptors.get( operation );
-
-        Method[] methods = interceptor.getClass().getDeclaredMethods();
-
-        for ( Method method : methods )
-        {
-          if ( method.getName().equals( operation.getMethodName() ) )
-          {
-            operationList.remove( interceptor.getName() );
-
-            break;
-          }
-        }
-      }
-
-      interceptorNames.remove( interceptorName );
-      interceptors.remove( interceptor );
-    }
-    finally
-    {
-      writeLock.unlock();
-    }
-  }
-
-
-  /**
-   * Sets the interceptors in the server.
-   *
-   * @param interceptors the interceptors to be used in the server.
-   */
-  public void setInterceptors( List<Interceptor> interceptors )
-  {
-    Map<String, Interceptor> interceptorNames = new HashMap<>();
-
-    // Check if we don't have duplicate names in the interceptors list
-    for ( Interceptor interceptor : interceptors )
-    {
-      if ( interceptorNames.containsKey( interceptor.getName() ) )
-      {
-        LOG.warn( "Encountered duplicate definitions for {} interceptor", interceptor.getName() );
-        continue;
-      }
-
-      interceptorNames.put( interceptor.getName(), interceptor );
-    }
-
-    this.interceptors = interceptors;
-    this.interceptorNames = interceptorNames;
-
-    // Now update the Map that connect each operation with the list of interceptors.
-    initOperationsList();
-  }
-
-
-  /**
-   * Initialize the interceptors
-   */
-  private void initInterceptors() throws LdapException
-  {
-    for ( Interceptor interceptor : interceptors )
-    {
-      interceptor.init( this );
-    }
-  }
-
-
-  /**
-   * Returns test directory entries({@link LdifEntry}) to be loaded while
-   * bootstrapping.
-   *
-   * @return test entries to load during bootstrapping
-   */
-  public List<LdifEntry> getTestEntries()
-  {
-    List<LdifEntry> cloned = new ArrayList<LdifEntry>();
-    cloned.addAll( testEntries );
-
-    return cloned;
-  }
-
-
-  /**
-   * Sets test directory entries({@link javax.naming.directory.Attributes}) to be loaded while
-   * bootstrapping.
-   *
-   * @param testEntries the test entries to load while bootstrapping
-   */
-  public void setTestEntries( List<? extends LdifEntry> testEntries )
-  {
-    //noinspection MismatchedQueryAndUpdateOfCollection
-    List<LdifEntry> cloned = new ArrayList<LdifEntry>();
-    cloned.addAll( testEntries );
-    this.testEntries = cloned;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public InstanceLayout getInstanceLayout()
-  {
-    return instanceLayout;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public void setInstanceLayout( InstanceLayout instanceLayout ) throws IOException
-  {
-    this.instanceLayout = instanceLayout;
-
-    // Create the directories if they are missing
-    if ( !instanceLayout.getInstanceDirectory().exists() )
-    {
-      if ( !instanceLayout.getInstanceDirectory().mkdirs() )
-      {
-        throw new IOException( I18n.err( I18n.ERR_112_COULD_NOT_CREATE_DIRECORY,
-            instanceLayout.getInstanceDirectory() ) );
-      }
-    }
-
-    if ( !instanceLayout.getLogDirectory().exists() )
-    {
-      if ( !instanceLayout.getLogDirectory().mkdirs() )
-      {
-        throw new IOException( I18n.err( I18n.ERR_112_COULD_NOT_CREATE_DIRECORY,
-            instanceLayout.getLogDirectory() ) );
-      }
-    }
-
-    if ( !instanceLayout.getRunDirectory().exists() )
-    {
-      if ( !instanceLayout.getRunDirectory().mkdirs() )
-      {
-        throw new IOException( I18n.err( I18n.ERR_112_COULD_NOT_CREATE_DIRECORY,
-            instanceLayout.getRunDirectory() ) );
-      }
-    }
-
-    if ( !instanceLayout.getPartitionsDirectory().exists() )
-    {
-      if ( !instanceLayout.getPartitionsDirectory().mkdirs() )
-      {
-        throw new IOException( I18n.err( I18n.ERR_112_COULD_NOT_CREATE_DIRECORY,
-            instanceLayout.getPartitionsDirectory() ) );
-      }
-    }
-
-    if ( !instanceLayout.getConfDirectory().exists() )
-    {
-      if ( !instanceLayout.getConfDirectory().mkdirs() )
-      {
-        throw new IOException( I18n.err( I18n.ERR_112_COULD_NOT_CREATE_DIRECORY,
-            instanceLayout.getConfDirectory() ) );
-      }
-    }
-  }
-
-
-  public void setShutdownHookEnabled( boolean shutdownHookEnabled )
-  {
-    this.shutdownHookEnabled = shutdownHookEnabled;
-  }
-
-
-  public boolean isShutdownHookEnabled()
-  {
-    return shutdownHookEnabled;
-  }
-
-
-  public void setExitVmOnShutdown( boolean exitVmOnShutdown )
-  {
-    this.exitVmOnShutdown = exitVmOnShutdown;
-  }
-
-
-  public boolean isExitVmOnShutdown()
-  {
-    return exitVmOnShutdown;
-  }
-
-
-  public void setSystemPartition( Partition systemPartition )
-  {
-    this.systemPartition = systemPartition;
-  }
-
-
-  public Partition getSystemPartition()
-  {
-    return systemPartition;
-  }
-
-
-  /**
-   * return true if the operational attributes must be normalized when returned
-   */
-  public boolean isDenormalizeOpAttrsEnabled()
-  {
-    return denormalizeOpAttrsEnabled;
-  }
-
-
-  /**
-   * Sets whether the operational attributes are denormalized when returned
-   * @param denormalizeOpAttrsEnabled The flag value
-   */
-  public void setDenormalizeOpAttrsEnabled( boolean denormalizeOpAttrsEnabled )
-  {
-    this.denormalizeOpAttrsEnabled = denormalizeOpAttrsEnabled;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public ChangeLog getChangeLog()
-  {
-    return changeLog;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public Journal getJournal()
-  {
-    return journal;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public void setChangeLog( ChangeLog changeLog )
-  {
-    this.changeLog = changeLog;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public void setJournal( Journal journal )
-  {
-    this.journal = journal;
-  }
-
-
-  public void addPartition( Partition partition ) throws Exception
-  {
-    partition.setSchemaManager( schemaManager );
-
-    try
-    {
-      // can be null when called before starting up
-      if ( partitionNexus != null )
-      {
-        partitionNexus.addContextPartition( partition );
-      }
-    }
-    catch ( LdapException le )
-    {
-      // We've got an exception, we cannot add the partition to the partitions
-      throw le;
-    }
-
-    // Now, add the partition to the set of managed partitions
-    partitions.add( partition );
-  }
-
-
-  public void removePartition( Partition partition ) throws Exception
-  {
-    // Do the backend cleanup first
-    try
-    {
-      // can be null when called before starting up
-      if ( partitionNexus != null )
-      {
-        partitionNexus.removeContextPartition( partition.getSuffixDn() );
-      }
-    }
-    catch ( LdapException le )
-    {
-      // Bad ! We can't go any further
-      throw le;
-    }
-
-    // And update the set of managed partitions
-    partitions.remove( partition );
-  }
-
-
-  // ------------------------------------------------------------------------
-  // BackendSubsystem Interface Method Implementations
-  // ------------------------------------------------------------------------
-  /**
-   * Define a default list of interceptors that has to be used if no other
-   * configuration is defined.
-   */
-  private void setDefaultInterceptorConfigurations()
-  {
-    // Set default interceptor chains
-    List<Interceptor> list = new ArrayList<Interceptor>();
-
-    list.add( new NormalizationInterceptor() );
-    list.add( new AuthenticationInterceptor() );
-    list.add( new ReferralInterceptor() );
-    list.add( new AciAuthorizationInterceptor() );
-    list.add( new DefaultAuthorizationInterceptor() );
-    list.add( new AdministrativePointInterceptor() );
-    list.add( new ExceptionInterceptor() );
-    list.add( new SchemaInterceptor() );
-    list.add( new OperationalAttributeInterceptor() );
-    list.add( new CollectiveAttributeInterceptor() );
-    list.add( new SubentryInterceptor() );
-    list.add( new EventInterceptor() );
-    list.add( new TriggerInterceptor() );
-    list.add( new ChangeLogInterceptor() );
-    list.add( new JournalInterceptor() );
-
-    setInterceptors( list );
-  }
-
-
-  public CoreSession getAdminSession()
-  {
-    return adminSession;
-  }
-
-
-  /**
-   * Get back an anonymous session
-   */
-  public CoreSession getSession()
-  {
-    return new DefaultCoreSession( new LdapPrincipal( schemaManager ), this );
-  }
-
-
-  /**
-   * Get back a session for a given principal
-   */
-  public CoreSession getSession( LdapPrincipal principal )
-  {
-    return new DefaultCoreSession( principal, this );
-  }
-
-
-  /**
-   * Get back a session for the give user and credentials bound with Simple Bind
-   */
-  public CoreSession getSession( Dn principalDn, byte[] credentials ) throws LdapException
-  {
-    synchronized ( this )
-    {
-      if ( !started )
-      {
-        throw new IllegalStateException( "Service has not started." );
-      }
-    }
-
-    BindOperationContext bindContext = new BindOperationContext( null );
-    bindContext.setCredentials( credentials );
-    bindContext.setDn( principalDn.apply( schemaManager ) );
-    bindContext.setInterceptors( getInterceptors( OperationEnum.BIND ) );
-
-    operationManager.bind( bindContext );
-
-    return bindContext.getSession();
-  }
-
-
-  /**
-   * Get back a session for a given user bound with SASL Bind
-   */
-  public CoreSession getSession( Dn principalDn, byte[] credentials, String saslMechanism, String saslAuthId )
-      throws Exception
-  {
-    synchronized ( this )
-    {
-      if ( !started )
-      {
-        throw new IllegalStateException( "Service has not started." );
-
-      }
-    }
-
-    BindOperationContext bindContext = new BindOperationContext( null );
-    bindContext.setCredentials( credentials );
-    bindContext.setDn( principalDn.apply( schemaManager ) );
-    bindContext.setSaslMechanism( saslMechanism );
-    bindContext.setInterceptors( getInterceptors( OperationEnum.BIND ) );
-
-    operationManager.bind( bindContext );
-
-    return bindContext.getSession();
-  }
-
-
-  public long revert() throws LdapException
-  {
-    if ( changeLog == null || !changeLog.isEnabled() )
-    {
-      throw new IllegalStateException( I18n.err( I18n.ERR_310 ) );
-    }
-
-    Tag latest = changeLog.getLatest();
-
-    if ( null != latest )
-    {
-      if ( latest.getRevision() < changeLog.getCurrentRevision() )
-      {
-        return revert( latest.getRevision() );
-      }
-      else
-      {
-        LOG.info( "Ignoring request to revert without changes since the latest tag." );
-        return changeLog.getCurrentRevision();
-      }
-    }
-
-    throw new IllegalStateException( I18n.err( I18n.ERR_311 ) );
-  }
-
-
-  /**
-   * We handle the ModDN/ModRDN operation for the revert here.
-   */
-  private void moddn( Dn oldDn, Dn newDn, boolean delOldRdn ) throws LdapException
-  {
-    if ( oldDn.size() == 0 )
-    {
-      throw new LdapNoPermissionException( I18n.err( I18n.ERR_312 ) );
-    }
-
-    // calculate parents
-    Dn oldBase = oldDn.getParent();
-    Dn newBase = newDn.getParent();
-
-    // Compute the Rdn for each of the Dn
-    Rdn newRdn = newDn.getRdn();
-    Rdn oldRdn = oldDn.getRdn();
-
-        /*
-         * We need to determine if this rename operation corresponds to a simple
-         * Rdn name change or a move operation.  If the two names are the same
-         * except for the Rdn then it is a simple modifyRdn operation.  If the
-         * names differ in size or have a different baseDN then the operation is
-         * a move operation.  Furthermore if the Rdn in the move operation
-         * changes it is both an Rdn change and a move operation.
-         */
-    if ( ( oldDn.size() == newDn.size() ) && oldBase.equals( newBase ) )
-    {
-      adminSession.rename( oldDn, newRdn, delOldRdn );
-    }
-    else
-    {
-      Dn target = newDn.getParent();
-
-      if ( newRdn.equals( oldRdn ) )
-      {
-        adminSession.move( oldDn, target );
-      }
-      else
-      {
-        adminSession.moveAndRename( oldDn, target, new Rdn( newRdn ), delOldRdn );
-      }
-    }
-  }
-
-
-  public long revert( long revision ) throws LdapException
-  {
-    if ( changeLog == null || !changeLog.isEnabled() )
-    {
-      throw new IllegalStateException( I18n.err( I18n.ERR_310 ) );
-    }
-
-    if ( revision < 0 )
-    {
-      throw new IllegalArgumentException( I18n.err( I18n.ERR_239 ) );
-    }
-
-    if ( revision >= changeLog.getChangeLogStore().getCurrentRevision() )
-    {
-      throw new IllegalArgumentException( I18n.err( I18n.ERR_314 ) );
-    }
-
-    Cursor<ChangeLogEvent> cursor = changeLog.getChangeLogStore().findAfter( revision );
-
-        /*
-         * BAD, BAD, BAD!!!
-         *
-         * No synchronization no nothing.  Just getting this to work for now
-         * so we can revert tests.  Any production grade use of this feature
-         * needs to synchronize on all changes while the revert is in progress.
-         *
-         * How about making this operation transactional?
-         *
-         * First of all just stop using JNDI and construct the operations to
-         * feed into the interceptor pipeline.
-         *
-         * TODO review this code.
-         */
-
-    try
-    {
-      LOG.warn( PARTIAL_IMPL_WARNING );
-      cursor.afterLast();
-
-      while ( cursor.previous() ) // apply ldifs in reverse order
-      {
-        ChangeLogEvent event = cursor.get();
-        List<LdifEntry> reverses = event.getReverseLdifs();
-
-        for ( LdifEntry reverse : reverses )
-        {
-          switch ( reverse.getChangeType().getChangeType() )
-          {
-            case ChangeType.ADD_ORDINAL:
-              adminSession.add(
-                  new DefaultEntry( schemaManager, reverse.getEntry() ), true );
-              break;
-
-            case ChangeType.DELETE_ORDINAL:
-              adminSession.delete( reverse.getDn(), true );
-              break;
-
-            case ChangeType.MODIFY_ORDINAL:
-              List<Modification> mods = reverse.getModifications();
-
-              adminSession.modify( reverse.getDn(), mods, true );
-              break;
-
-            case ChangeType.MODDN_ORDINAL:
-              // NO BREAK - both ModDN and ModRDN handling is the same
-
-            case ChangeType.MODRDN_ORDINAL:
-              Dn forwardDn = event.getForwardLdif().getDn();
-              Dn reverseDn = reverse.getDn();
-
-              moddn( reverseDn, forwardDn, reverse.isDeleteOldRdn() );
-
-              break;
-
-            default:
-              LOG.error( I18n.err( I18n.ERR_75 ) );
-              throw new NotImplementedException( I18n.err( I18n.ERR_76, reverse.getChangeType() ) );
-          }
-        }
-      }
-    }
-    catch ( Exception e )
-    {
-      throw new LdapOperationException( e.getMessage(), e );
-    }
-    finally
-    {
-      try
-      {
-        cursor.close();
-      }
-      catch ( Exception e )
-      {
-        throw new LdapOperationException( e.getMessage(), e );
-      }
-    }
-
-    return changeLog.getCurrentRevision();
-  }
-
-
-  public OperationManager getOperationManager()
-  {
-    return operationManager;
-  }
-
-
-  /**
-   * @throws Exception if the LDAP server cannot be started
-   */
-  public synchronized void startup() throws Exception
-  {
-    if ( started )
-    {
-      return;
-    }
-
-    lockWorkDir();
-
-    if ( shutdownHookEnabled )
-    {
-      Runtime.getRuntime().addShutdownHook( new Thread( new Runnable()
-      {
-        public void run()
-        {
-          try
-          {
-            shutdown();
-          }
-          catch ( Exception e )
-          {
-            LOG.warn( "Failed to shut down the directory service: "
-                + BaseDirectoryService.this.instanceId, e );
-          }
-        }
-      }, "ApacheDS Shutdown Hook (" + instanceId + ')' ) );
-
-      LOG.info( "ApacheDS shutdown hook has been registered with the runtime." );
-    }
-    else if ( LOG.isWarnEnabled() )
-    {
-      LOG.warn( "ApacheDS shutdown hook has NOT been registered with the runtime."
-          + "  This default setting for standalone operation has been overriden." );
-    }
-
-    initialize();
-    showSecurityWarnings();
-
-    // load the last stored valid CSN value
-    LookupOperationContext loc = new LookupOperationContext( getAdminSession(), systemPartition.getSuffixDn(),
-        SchemaConstants.ALL_ATTRIBUTES_ARRAY );
-
-    Entry entry = systemPartition.lookup( loc );
-
-    Attribute cntextCsnAt = entry.get( SchemaConstants.CONTEXT_CSN_AT );
-
-    if ( cntextCsnAt != null )
-    {
-      // this is a multivalued attribute but current syncrepl provider implementation stores only ONE value at ou=system
-      contextCsn = cntextCsnAt.getString();
-    }
-
-    started = true;
-
-    if ( !testEntries.isEmpty() )
-    {
-      createTestEntries();
-    }
-  }
-
-
-  public synchronized void sync() throws Exception
-  {
-    if ( !started )
-    {
-      return;
-    }
-
-    this.changeLog.sync();
-    this.partitionNexus.sync();
-  }
-
-
-  public synchronized void shutdown() throws Exception
-  {
-    LOG.debug( "+++ DirectoryService Shutdown required" );
-
-    if ( !started )
-    {
-      return;
-    }
-
-    // --------------------------------------------------------------------
-    // Shutdown the sync thread
-    // --------------------------------------------------------------------
-    LOG.debug( "--- Syncing the nexus " );
-    partitionNexus.sync();
-
-    // --------------------------------------------------------------------
-    // Shutdown the changelog
-    // --------------------------------------------------------------------
-    LOG.debug( "--- Syncing the changeLog " );
-    changeLog.sync();
-    changeLog.destroy();
-
-    // --------------------------------------------------------------------
-    // Shutdown the journal if enabled
-    // --------------------------------------------------------------------
-    if ( journal.isEnabled() )
-    {
-      LOG.debug( "--- Destroying the journal " );
-      journal.destroy();
-    }
-
-    // --------------------------------------------------------------------
-    // Shutdown the partition
-    // --------------------------------------------------------------------
-
-    LOG.debug( "--- Destroying the nexus" );
-    partitionNexus.destroy();
-
-    // Last flush...
-    LOG.debug( "--- Flushing everything before quitting" );
-    getOperationManager().lockWrite();
-    partitionNexus.sync();
-    getOperationManager().unlockWrite();
-
-    // --------------------------------------------------------------------
-    // And shutdown the server
-    // --------------------------------------------------------------------
-    LOG.debug( "--- Deleting the cache service" );
-    cacheService.destroy();
-
-    LOG.debug( "---Deleting the DnCache" );
-    dnFactory = null;
-
-    if ( lockFile != null )
-    {
-      try
-      {
-        lockFile.close();
-        // no need to delete the lock file
-      }
-      catch ( IOException e )
-      {
-        LOG.warn( "couldn't delete the lock file {}", LOCK_FILE_NAME );
-      }
-    }
-
-    LOG.debug( "+++ DirectoryService stopped" );
-    started = false;
-  }
-
-
-  /**
-   * @return The referral manager
-   */
-  public ReferralManager getReferralManager()
-  {
-    return referralManager;
-  }
-
-
-  /**
-   * Set the referralManager
-   * @param referralManager The initialized referralManager
-   */
-  public void setReferralManager( ReferralManager referralManager )
-  {
-    this.referralManager = referralManager;
-  }
-
-
-  /**
-   * @return the SchemaManager
-   */
-  public SchemaManager getSchemaManager()
-  {
-    return schemaManager;
-  }
-
-
-  /**
-   * Set the SchemaManager instance.
-   *
-   * @param schemaManager The server schemaManager
-   */
-  public void setSchemaManager( SchemaManager schemaManager )
-  {
-    this.schemaManager = schemaManager;
-  }
-
-
-  public LdapApiService getLdapCodecService()
-  {
-    return ldapCodecService;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public SchemaPartition getSchemaPartition()
-  {
-    return schemaPartition;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public void setSchemaPartition( SchemaPartition schemaPartition )
-  {
-    this.schemaPartition = schemaPartition;
-  }
-
-
-  public DefaultPartitionNexus getPartitionNexus()
-  {
-    return partitionNexus;
-  }
-
-
-  public boolean isFirstStart()
-  {
-    return firstStart;
-  }
-
-
-  public synchronized boolean isStarted()
-  {
-    return started;
-  }
-
-
-  public Entry newEntry( Dn dn )
-  {
-    return new DefaultEntry( schemaManager, dn );
-  }
-
-
-  /**
-   * Returns true if we had to create the bootstrap entries on the first
-   * start of the server.  Otherwise if all entries exist, meaning none
-   * had to be created, then we are not starting for the first time.
-   *
-   * @return true if the bootstrap entries had to be created, false otherwise
-   * @throws Exception if entries cannot be created
-   */
-  private boolean createBootstrapEntries() throws Exception
-  {
-    boolean firstStart = false;
-
-    // -------------------------------------------------------------------
-    // create admin entry
-    // -------------------------------------------------------------------
-
-        /*
-         * If the admin entry is there, then the database was already created
-         */
-    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, adminDn ) ) )
-    {
-      firstStart = true;
-
-      Entry serverEntry = new DefaultEntry( schemaManager, adminDn );
-
-      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT,
-          SchemaConstants.TOP_OC,
-          SchemaConstants.PERSON_OC,
-          SchemaConstants.ORGANIZATIONAL_PERSON_OC,
-          SchemaConstants.INET_ORG_PERSON_OC );
-
-      serverEntry.put( SchemaConstants.UID_AT, PartitionNexus.ADMIN_UID );
-      serverEntry.put( SchemaConstants.USER_PASSWORD_AT, PartitionNexus.ADMIN_PASSWORD_BYTES );
-      serverEntry.put( SchemaConstants.DISPLAY_NAME_AT, "Directory Superuser" );
-      serverEntry.put( SchemaConstants.CN_AT, "system administrator" );
-      serverEntry.put( SchemaConstants.SN_AT, "administrator" );
-      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
-      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
-      serverEntry.put( SchemaConstants.DISPLAY_NAME_AT, "Directory Superuser" );
-      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
-      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
-
-      TlsKeyGenerator.addKeyPair( serverEntry );
-      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
-    }
-
-    // -------------------------------------------------------------------
-    // create system users area
-    // -------------------------------------------------------------------
-
-    Dn userDn = getDnFactory().create( ServerDNConstants.USERS_SYSTEM_DN );
-
-    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, userDn ) ) )
-    {
-      firstStart = true;
-
-      Entry serverEntry = new DefaultEntry( schemaManager, userDn );
-
-      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT,
-          SchemaConstants.TOP_OC,
-          SchemaConstants.ORGANIZATIONAL_UNIT_OC );
-
-      serverEntry.put( SchemaConstants.OU_AT, "users" );
-      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
-      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
-      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
-      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
-
-      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
-    }
-
-    // -------------------------------------------------------------------
-    // create system groups area
-    // -------------------------------------------------------------------
-
-    Dn groupDn = getDnFactory().create( ServerDNConstants.GROUPS_SYSTEM_DN );
-
-    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, groupDn ) ) )
-    {
-      firstStart = true;
-
-      Entry serverEntry = new DefaultEntry( schemaManager, groupDn );
-
-      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT,
-          SchemaConstants.TOP_OC,
-          SchemaConstants.ORGANIZATIONAL_UNIT_OC );
-
-      serverEntry.put( SchemaConstants.OU_AT, "groups" );
-      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
-      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
-      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
-      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
-
-      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
-    }
-
-    // -------------------------------------------------------------------
-    // create administrator group
-    // -------------------------------------------------------------------
-
-    Dn name = getDnFactory().create( ServerDNConstants.ADMINISTRATORS_GROUP_DN );
-
-    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, name ) ) )
-    {
-      firstStart = true;
-
-      Entry serverEntry = new DefaultEntry( schemaManager, name );
-
-      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT,
-          SchemaConstants.TOP_OC,
-          SchemaConstants.GROUP_OF_UNIQUE_NAMES_OC );
-
-      serverEntry.put( SchemaConstants.CN_AT, "Administrators" );
-      serverEntry.put( SchemaConstants.UNIQUE_MEMBER_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
-      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
-      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
-      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
-      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
-
-      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
-    }
-
-    // -------------------------------------------------------------------
-    // create system configuration area
-    // -------------------------------------------------------------------
-
-    Dn configurationDn = getDnFactory().create( "ou=configuration,ou=system" );
-
-    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, configurationDn ) ) )
-    {
-      firstStart = true;
-
-      Entry serverEntry = new DefaultEntry( schemaManager, configurationDn );
-      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT, SchemaConstants.TOP_OC,
-          SchemaConstants.ORGANIZATIONAL_UNIT_OC );
-
-      serverEntry.put( SchemaConstants.OU_AT, "configuration" );
-      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
-      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
-      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
-      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
-
-      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
-    }
-
-    // -------------------------------------------------------------------
-    // create system configuration area for partition information
-    // -------------------------------------------------------------------
-
-    Dn partitionsDn = getDnFactory().create( "ou=partitions,ou=configuration,ou=system" );
-
-    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, partitionsDn ) ) )
-    {
-      firstStart = true;
-
-      Entry serverEntry = new DefaultEntry( schemaManager, partitionsDn );
-      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT, SchemaConstants.TOP_OC,
-          SchemaConstants.ORGANIZATIONAL_UNIT_OC );
-      serverEntry.put( SchemaConstants.OU_AT, "partitions" );
-      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
-      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
-      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
-      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
-
-      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
-    }
-
-    // -------------------------------------------------------------------
-    // create system configuration area for services
-    // -------------------------------------------------------------------
-
-    Dn servicesDn = getDnFactory().create( "ou=services,ou=configuration,ou=system" );
-
-    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, servicesDn ) ) )
-    {
-      firstStart = true;
-
-      Entry serverEntry = new DefaultEntry( schemaManager, servicesDn );
-      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT, SchemaConstants.TOP_OC,
-          SchemaConstants.ORGANIZATIONAL_UNIT_OC );
-
-      serverEntry.put( SchemaConstants.OU_AT, "services" );
-      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
-      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
-      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
-      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
-
-      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
-    }
-
-    // -------------------------------------------------------------------
-    // create system configuration area for interceptors
-    // -------------------------------------------------------------------
-
-    Dn interceptorsDn = getDnFactory().create( "ou=interceptors,ou=configuration,ou=system" );
-
-    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, interceptorsDn ) ) )
-    {
-      firstStart = true;
-
-      Entry serverEntry = new DefaultEntry( schemaManager, interceptorsDn );
-      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT, SchemaConstants.TOP_OC,
-          SchemaConstants.ORGANIZATIONAL_UNIT_OC );
-
-      serverEntry.put( SchemaConstants.OU_AT, "interceptors" );
-      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
-      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
-      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
-      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
-
-      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
-    }
-
-    // -------------------------------------------------------------------
-    // create system preferences area
-    // -------------------------------------------------------------------
-
-    Dn sysPrefRootDn = getDnFactory().create( ServerDNConstants.SYSPREFROOT_SYSTEM_DN );
-
-    if ( !partitionNexus.hasEntry( new HasEntryOperationContext( adminSession, sysPrefRootDn ) ) )
-    {
-      firstStart = true;
-
-      Entry serverEntry = new DefaultEntry( schemaManager, sysPrefRootDn );
-      serverEntry.put( SchemaConstants.OBJECT_CLASS_AT,
-          SchemaConstants.TOP_OC,
-          SchemaConstants.ORGANIZATIONAL_UNIT_OC,
-          SchemaConstants.EXTENSIBLE_OBJECT_OC );
-
-      serverEntry.put( "prefNodeName", "sysPrefRoot" );
-      serverEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN_NORMALIZED );
-      serverEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
-      serverEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
-      serverEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
-
-      partitionNexus.add( new AddOperationContext( adminSession, serverEntry ) );
-    }
-
-    return firstStart;
-  }
-
-
-  /**
-   * Displays security warning messages if any possible secutiry issue is found.
-   * @throws Exception if there are failures parsing and accessing internal structures
-   */
-  protected void showSecurityWarnings() throws Exception
-  {
-    // Warn if the default password is not changed.
-    boolean needToChangeAdminPassword = false;
-
-    Dn adminDn = getDnFactory().create( ServerDNConstants.ADMIN_SYSTEM_DN );
-
-    Entry adminEntry = partitionNexus.lookup( new LookupOperationContext( adminSession, adminDn ) );
-    Value<?> userPassword = adminEntry.get( SchemaConstants.USER_PASSWORD_AT ).get();
-    needToChangeAdminPassword = Arrays.equals( PartitionNexus.ADMIN_PASSWORD_BYTES, userPassword.getBytes() );
-
-    if ( needToChangeAdminPassword )
-    {
-      LOG.warn( "You didn't change the admin password of directory service " + "instance '" + instanceId + "'.  "
-          + "Please update the admin password as soon as possible " + "to prevent a possible security breach." );
-    }
-  }
-
-
-  /**
-   * Adds test entries into the core.
-   *
-   * @todo this may no longer be needed when JNDI is not used for bootstrapping
-   *
-   * @throws Exception if the creation of test entries fails.
-   */
-  private void createTestEntries() throws Exception
-  {
-    for ( LdifEntry testEntry : testEntries )
-    {
-      try
-      {
-        LdifEntry ldifEntry = testEntry.clone();
-        Entry entry = ldifEntry.getEntry();
-        String dn = ldifEntry.getDn().getName();
-
-        try
-        {
-          getAdminSession().add( new DefaultEntry( schemaManager, entry ) );
-        }
-        catch ( Exception e )
-        {
-          LOG.warn( dn + " test entry already exists.", e );
-        }
-      }
-      catch ( CloneNotSupportedException cnse )
-      {
-        LOG.warn( "Cannot clone the entry ", cnse );
-      }
-    }
-  }
-
-
-  private void initializeSystemPartition() throws Exception
-  {
-    Partition system = getSystemPartition();
-
-    // Add root context entry for system partition
-    Dn systemSuffixDn = getDnFactory().create( ServerDNConstants.SYSTEM_DN );
-    CoreSession adminSession = getAdminSession();
-
-    if ( !system.hasEntry( new HasEntryOperationContext( adminSession, systemSuffixDn ) ) )
-    {
-      Entry systemEntry = new DefaultEntry( schemaManager, systemSuffixDn );
-
-      // Add the ObjectClasses
-      systemEntry.put( SchemaConstants.OBJECT_CLASS_AT, SchemaConstants.TOP_OC,
-          SchemaConstants.ORGANIZATIONAL_UNIT_OC, SchemaConstants.EXTENSIBLE_OBJECT_OC );
-
-      // Add some operational attributes
-      systemEntry.put( SchemaConstants.CREATORS_NAME_AT, ServerDNConstants.ADMIN_SYSTEM_DN );
-      systemEntry.put( SchemaConstants.CREATE_TIMESTAMP_AT, DateUtils.getGeneralizedTime() );
-      systemEntry.add( SchemaConstants.ENTRY_CSN_AT, getCSN().toString() );
-      systemEntry.add( SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString() );
-      systemEntry.put( DnUtils.getRdnAttributeType( ServerDNConstants.SYSTEM_DN ), DnUtils
-          .getRdnValue( ServerDNConstants.SYSTEM_DN ) );
-
-      AddOperationContext addOperationContext = new AddOperationContext( adminSession, systemEntry );
-      system.add( addOperationContext );
-    }
-  }
-
-
-  /**
-   * Kicks off the initialization of the entire system.
-   *
-   * @throws Exception if there are problems along the way
-   */
-  private void initialize() throws Exception
-  {
-    if ( LOG.isDebugEnabled() )
-    {
-      LOG.debug( "---> Initializing the DefaultDirectoryService " );
-    }
-
-    csnFactory.setReplicaId( replicaId );
-
-    // If no interceptor list is defined, setup a default list
-    if ( interceptors == null )
-    {
-      setDefaultInterceptorConfigurations();
-    }
-
-    if ( cacheService == null )
-    {
-      // Initialize a default cache service
-      cacheService = new CacheService();
-    }
-
-    cacheService.initialize( instanceLayout );
-
-    // Initialize the AP caches
-    accessControlAPCache = new DnNode<AccessControlAdministrativePoint>();
-    collectiveAttributeAPCache = new DnNode<CollectiveAttributeAdministrativePoint>();
-    subschemaAPCache = new DnNode<SubschemaAdministrativePoint>();
-    triggerExecutionAPCache = new DnNode<TriggerExecutionAdministrativePoint>();
-
-    if ( dnFactory == null )
-    {
-      dnFactory = new DefaultDnFactory( schemaManager, cacheService.getCache( "dnCache" ) );
-    }
-
-    // triggers partition to load schema fully from schema partition
-    schemaPartition.setCacheService( cacheService );
-    schemaPartition.initialize();
-    partitions.add( schemaPartition );
-    systemPartition.setCacheService( cacheService );
-    systemPartition.getSuffixDn().apply( schemaManager );
-
-    adminDn = getDnFactory().create( ServerDNConstants.ADMIN_SYSTEM_DN );
-    adminSession = new DefaultCoreSession( new LdapPrincipal( schemaManager, adminDn, AuthenticationLevel.STRONG ),
-        this );
-
-    // @TODO - NOTE: Need to find a way to instantiate without dependency on DPN
-    partitionNexus = new DefaultPartitionNexus( new DefaultEntry( schemaManager, Dn.ROOT_DSE ) );
-    partitionNexus.setDirectoryService( this );
-    partitionNexus.initialize();
-
-    initializeSystemPartition();
-
-    // --------------------------------------------------------------------
-    // Create all the bootstrap entries before initializing chain
-    // --------------------------------------------------------------------
-
-    firstStart = createBootstrapEntries();
-
-    // Initialize the interceptors
-    initInterceptors();
-
-    // --------------------------------------------------------------------
-    // Initialize the changeLog if it's enabled
-    // --------------------------------------------------------------------
-
-    if ( changeLog.isEnabled() )
-    {
-      changeLog.init( this );
-
-      if ( changeLog.isExposed() && changeLog.isTagSearchSupported() )
-      {
-        String clSuffix = ( ( TaggableSearchableChangeLogStore ) changeLog.getChangeLogStore() ).getPartition()
-            .getSuffixDn().getName();
-        partitionNexus.getRootDse( null ).add( SchemaConstants.CHANGELOG_CONTEXT_AT, clSuffix );
-      }
-    }
-
-    // --------------------------------------------------------------------
-    // Initialize the journal if it's enabled
-    // --------------------------------------------------------------------
-    if ( journal.isEnabled() )
-    {
-      journal.init( this );
-    }
-
-    if ( LOG.isDebugEnabled() )
-    {
-      LOG.debug( "<--- DefaultDirectoryService initialized" );
-    }
-  }
-
-
-  /**
-   * Read an entry (without Dn)
-   *
-   * @param text The ldif format file
-   * @return An entry.
-   */
-  // This will suppress PMD.EmptyCatchBlock warnings in this method
-  @SuppressWarnings("PMD.EmptyCatchBlock")
-  private Entry readEntry( String text )
-  {
-    StringReader strIn = new StringReader( text );
-    BufferedReader in = new BufferedReader( strIn );
-
-    String line = null;
-    Entry entry = new DefaultEntry();
-
-    try
-    {
-      while ( ( line = in.readLine() ) != null )
-      {
-        if ( line.length() == 0 )
-        {
-          continue;
-        }
-
-        String addedLine = line.trim();
-
-        if ( Strings.isEmpty( addedLine ) )
-        {
-          continue;
-        }
-
-        Attribute attribute = LdifReader.parseAttributeValue( addedLine );
-        Attribute oldAttribute = entry.get( attribute.getId() );
-
-        if ( oldAttribute != null )
-        {
-          try
-          {
-            oldAttribute.add( attribute.get() );
-            entry.put( oldAttribute );
-          }
-          catch ( LdapException ne )
-          {
-            // Do nothing
-          }
-        }
-        else
-        {
-          try
-          {
-            entry.put( attribute );
-          }
-          catch ( LdapException ne )
-          {
-            // TODO do nothing ...
-          }
-        }
-      }
-    }
-    catch ( IOException ioe )
-    {
-      // Do nothing : we can't reach this point !
-    }
-
-    return entry;
-  }
-
-
-  /**
-   * Create a new Entry
-   *
-   * @param ldif The String representing the attributes, as a LDIF file
-   * @param dn The Dn for this new entry
-   */
-  public Entry newEntry( String ldif, String dn )
-  {
-    try
-    {
-      Entry entry = readEntry( ldif );
-      Dn newDn = getDnFactory().create( dn );
-
-      entry.setDn( newDn );
-
-      // TODO Let's get rid of this Attributes crap
-      Entry serverEntry = new DefaultEntry( schemaManager, entry );
-      return serverEntry;
-    }
-    catch ( Exception e )
-    {
-      LOG.error( I18n.err( I18n.ERR_78, ldif, dn ) );
-      // do nothing
-      return null;
-    }
-  }
-
-
-  public EventService getEventService()
-  {
-    return eventService;
-  }
-
-
-  public void setEventService( EventService eventService )
-  {
-    this.eventService = eventService;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public boolean isPasswordHidden()
-  {
-    return passwordHidden;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public void setPasswordHidden( boolean passwordHidden )
-  {
-    this.passwordHidden = passwordHidden;
-  }
-
-
-  /**
-   * @return The maximum allowed size for an incoming PDU
-   */
-  public int getMaxPDUSize()
-  {
-    return maxPDUSize;
-  }
-
-
-  /**
-   * Set the maximum allowed size for an incoming PDU
-   * @param maxPDUSize A positive number of bytes for the PDU. A negative or
-   * null value will be transformed to {@link Integer#MAX_VALUE}
-   */
-  public void setMaxPDUSize( int maxPDUSize )
-  {
-    if ( maxPDUSize <= 0 )
-    {
-      maxPDUSize = Integer.MAX_VALUE;
-    }
-
-    this.maxPDUSize = maxPDUSize;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public Interceptor getInterceptor( String interceptorName )
-  {
-    readLock.lock();
-
-    try
-    {
-      return interceptorNames.get( interceptorName );
-    }
-    finally
-    {
-      readLock.unlock();
-    }
-  }
-
-
-  /**
-   * {@inheritDoc}
-   * @throws LdapException
-   */
-  public void addFirst( Interceptor interceptor ) throws LdapException
-  {
-    addInterceptor( interceptor, 0 );
-  }
-
-
-  /**
-   * {@inheritDoc}
-   * @throws LdapException
-   */
-  public void addLast( Interceptor interceptor ) throws LdapException
-  {
-    addInterceptor( interceptor, -1 );
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public void addAfter( String interceptorName, Interceptor interceptor )
-  {
-    writeLock.lock();
-
-    try
-    {
-      int position = 0;
-
-      // Find the position
-      for ( Interceptor inter : interceptors )
-      {
-        if ( interceptorName.equals( inter.getName() ) )
-        {
-          break;
-        }
-
-        position++;
-      }
-
-      if ( position == interceptors.size() )
-      {
-        interceptors.add( interceptor );
-      }
-      else
-      {
-        interceptors.add( position, interceptor );
-      }
-    }
-    finally
-    {
-      writeLock.unlock();
-    }
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public void remove( String interceptorName )
-  {
-    removeOperationsList( interceptorName );
-  }
-
-
-  /**
-   * Get a new CSN
-   * @return The CSN generated for this directory service
-   */
-  public Csn getCSN()
-  {
-    return csnFactory.newInstance();
-  }
-
-
-  /**
-   * @return the replicaId
-   */
-  public int getReplicaId()
-  {
-    return replicaId;
-  }
-
-
-  /**
-   * @param replicaId the replicaId to set
-   */
-  public void setReplicaId( int replicaId )
-  {
-    if ( ( replicaId < 0 ) || ( replicaId > 999 ) )
-    {
-      LOG.error( I18n.err( I18n.ERR_79 ) );
-      this.replicaId = 0;
-    }
-    else
-    {
-      this.replicaId = replicaId;
-    }
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public long getSyncPeriodMillis()
-  {
-    return syncPeriodMillis;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public void setSyncPeriodMillis( long syncPeriodMillis )
-  {
-    this.syncPeriodMillis = syncPeriodMillis;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public String getContextCsn()
-  {
-    return contextCsn;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public void setContextCsn( String lastKnownCsn )
-  {
-    this.contextCsn = lastKnownCsn;
-  }
-
-
-  /**
-   * checks if the working directory is already in use by some other directory service, if yes
-   * then throws a runtime exception else will obtain the lock on the working directory
-   */
-  private void lockWorkDir()
-  {
-    FileLock fileLock = null;
-
-    try
-    {
-      lockFile = new RandomAccessFile( new File( instanceLayout.getInstanceDirectory(), LOCK_FILE_NAME ), "rw" );
-      try
-      {
-        fileLock = lockFile.getChannel().tryLock( 0, 1, false );
-      }
-      catch ( IOException e )
-      {
-        // shoudn't happen, but log
-        LOG.error( "failed to lock the work directory", e );
-      }
-      catch ( OverlappingFileLockException e ) // thrown if we can't get a lock
-      {
-        fileLock = null;
-      }
-    }
-    catch ( FileNotFoundException e )
-    {
-      // shouldn't happen, but log anyway
-      LOG.error( "failed to lock the work directory", e );
-    }
-
-    if ( ( fileLock == null ) || ( !fileLock.isValid() ) )
-    {
-      String message = "the working directory " + instanceLayout.getRunDirectory()
-          + " has been locked by another directory service.";
-      LOG.error( message );
-      throw new RuntimeException( message );
-    }
-
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public CacheService getCacheService()
-  {
-    return cacheService;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public DnNode<AccessControlAdministrativePoint> getAccessControlAPCache()
-  {
-    return accessControlAPCache;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public DnNode<CollectiveAttributeAdministrativePoint> getCollectiveAttributeAPCache()
-  {
-    return collectiveAttributeAPCache;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public DnNode<SubschemaAdministrativePoint> getSubschemaAPCache()
-  {
-    return subschemaAPCache;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public DnNode<TriggerExecutionAdministrativePoint> getTriggerExecutionAPCache()
-  {
-    return triggerExecutionAPCache;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public boolean isPwdPolicyEnabled()
-  {
-    AuthenticationInterceptor authenticationInterceptor = (AuthenticationInterceptor) getInterceptor( InterceptorEnum.AUTHENTICATION_INTERCEPTOR
-        .getName() );
-
-    if ( authenticationInterceptor == null )
-    {
-      return false;
-    }
-
-    PpolicyConfigContainer pwdPolicyContainer = authenticationInterceptor.getPwdPolicyContainer();
-
-    return ( ( pwdPolicyContainer != null )
-        && ( ( pwdPolicyContainer.getDefaultPolicy() != null )
-        || ( pwdPolicyContainer.hasCustomConfigs() ) ) );
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public DnFactory getDnFactory()
-  {
-    return dnFactory;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public void setDnFactory( DnFactory dnFactory )
-  {
-    this.dnFactory = dnFactory;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public SubentryCache getSubentryCache()
-  {
-    return subentryCache;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public SubtreeEvaluator getEvaluator()
-  {
-    return evaluator;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public void setCacheService( CacheService cacheService )
-  {
-    this.cacheService = cacheService;
-  }
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/BaseDirectoryServiceFactory.java
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/BaseDirectoryServiceFactory.java b/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/BaseDirectoryServiceFactory.java
deleted file mode 100644
index 2d2bc1f..0000000
--- a/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/BaseDirectoryServiceFactory.java
+++ /dev/null
@@ -1,290 +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.hadoop.gateway.security.ldap;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.directory.api.ldap.model.constants.SchemaConstants;
-import org.apache.directory.api.ldap.model.schema.LdapComparator;
-import org.apache.directory.api.ldap.model.schema.SchemaManager;
-import org.apache.directory.api.ldap.model.schema.comparators.NormalizingComparator;
-import org.apache.directory.api.ldap.model.schema.registries.ComparatorRegistry;
-import org.apache.directory.api.ldap.model.schema.registries.SchemaLoader;
-import org.apache.directory.api.ldap.schemaextractor.SchemaLdifExtractor;
-import org.apache.directory.api.ldap.schemaextractor.impl.DefaultSchemaLdifExtractor;
-import org.apache.directory.api.ldap.schemaloader.LdifSchemaLoader;
-import org.apache.directory.api.ldap.schemamanager.impl.DefaultSchemaManager;
-import org.apache.directory.api.util.exception.Exceptions;
-import org.apache.directory.server.constants.ServerDNConstants;
-import org.apache.directory.server.core.DefaultDirectoryService;
-import org.apache.directory.server.core.api.CacheService;
-import org.apache.directory.server.core.api.DirectoryService;
-import org.apache.directory.server.core.api.InstanceLayout;
-import org.apache.directory.server.core.api.partition.Partition;
-import org.apache.directory.server.core.api.schema.SchemaPartition;
-import org.apache.directory.server.core.factory.DefaultDirectoryServiceFactory;
-import org.apache.directory.server.core.factory.DirectoryServiceFactory;
-import org.apache.directory.server.core.factory.JdbmPartitionFactory;
-import org.apache.directory.server.core.factory.PartitionFactory;
-import org.apache.directory.server.core.partition.ldif.LdifPartition;
-import org.apache.directory.server.i18n.I18n;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-
-
-/**
- * A Default factory for DirectoryService.
- * This is a copy of org.apache.directory.server.core.factory.DefaultDirectoryServiceFactory
- * created to control how the DirectoryService is created.  This can be removed
- * when http://svn.apache.org/r1546144 in ApacheDS 2.0.0-M16 is available.
- *
- * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
- */
-public class BaseDirectoryServiceFactory implements DirectoryServiceFactory
-{
-  /** A logger for this class */
-  private static final Logger LOG = LoggerFactory.getLogger( DefaultDirectoryServiceFactory.class );
-
-  /** The directory service. */
-  private DirectoryService directoryService;
-
-  /** The partition factory. */
-  private PartitionFactory partitionFactory;
-
-
-  public BaseDirectoryServiceFactory()
-  {
-    directoryService = createDirectoryService();
-    partitionFactory = createPartitionFactory();
-  }
-
-  protected DirectoryService createDirectoryService() {
-    DirectoryService result;
-    try
-    {
-      // Creating the instance here so that
-      // we we can set some properties like accesscontrol, anon access
-      // before starting up the service
-      result = new DefaultDirectoryService();
-
-      // No need to register a shutdown hook during tests because this
-      // starts a lot of threads and slows down test execution
-      result.setShutdownHookEnabled( false );
-    }
-    catch ( Exception e )
-    {
-      throw new RuntimeException( e );
-    }
-    return result;
-  }
-
-  protected PartitionFactory createPartitionFactory() {
-    PartitionFactory result;
-    try
-    {
-      String typeName = System.getProperty( "apacheds.partition.factory" );
-      if ( typeName != null )
-      {
-        Class<? extends PartitionFactory> type = ( Class<? extends PartitionFactory> ) Class.forName( typeName );
-        result = type.newInstance();
-      }
-      else
-      {
-        result = new JdbmPartitionFactory();
-      }
-    }
-    catch ( Exception e )
-    {
-      LOG.error( "Error instantiating custom partition factory", e );
-      throw new RuntimeException( e );
-    }
-    return result;
-  }
-
-  /**
-   * {@inheritDoc}
-   */
-  public void init( String name ) throws Exception
-  {
-    if ( ( directoryService != null ) && directoryService.isStarted() )
-    {
-      return;
-    }
-
-    build( name );
-  }
-
-
-  /**
-   * Build the working directory
-   */
-  private void buildInstanceDirectory( String name ) throws IOException
-  {
-    String instanceDirectory = System.getProperty( "workingDirectory" );
-
-    if ( instanceDirectory == null )
-    {
-      instanceDirectory = System.getProperty( "java.io.tmpdir" ) + "/server-work-" + name;
-    }
-
-    InstanceLayout instanceLayout = new InstanceLayout( instanceDirectory );
-
-    if ( instanceLayout.getInstanceDirectory().exists() )
-    {
-      try
-      {
-        FileUtils.deleteDirectory( instanceLayout.getInstanceDirectory() );
-      }
-      catch ( IOException e )
-      {
-        LOG.warn( "couldn't delete the instance directory before initializing the DirectoryService", e );
-      }
-    }
-
-    directoryService.setInstanceLayout( instanceLayout );
-  }
-
-
-  /**
-   * Inits the schema and schema partition.
-   */
-  private void initSchema() throws Exception
-  {
-    File workingDirectory = directoryService.getInstanceLayout().getPartitionsDirectory();
-
-    // Extract the schema on disk (a brand new one) and load the registries
-    File schemaRepository = new File( workingDirectory, "schema" );
-    SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor( workingDirectory );
-
-    try
-    {
-      extractor.extractOrCopy();
-    }
-    catch ( IOException ioe )
-    {
-      // The schema has already been extracted, bypass
-    }
-
-    SchemaLoader loader = new LdifSchemaLoader( schemaRepository );
-    SchemaManager schemaManager = new DefaultSchemaManager( loader );
-
-    // We have to load the schema now, otherwise we won't be able
-    // to initialize the Partitions, as we won't be able to parse
-    // and normalize their suffix Dn
-    schemaManager.loadAllEnabled();
-
-    // Tell all the normalizer comparators that they should not normalize anything
-    ComparatorRegistry comparatorRegistry = schemaManager.getComparatorRegistry();
-
-    for ( LdapComparator<?> comparator : comparatorRegistry )
-    {
-      if ( comparator instanceof NormalizingComparator )
-      {
-        ( ( NormalizingComparator ) comparator ).setOnServer();
-      }
-    }
-
-    directoryService.setSchemaManager( schemaManager );
-
-    // Init the LdifPartition
-    LdifPartition ldifPartition = new LdifPartition( schemaManager, directoryService.getDnFactory() );
-    ldifPartition.setPartitionPath( new File( workingDirectory, "schema" ).toURI() );
-    SchemaPartition schemaPartition = new SchemaPartition( schemaManager );
-    schemaPartition.setWrappedPartition( ldifPartition );
-    directoryService.setSchemaPartition( schemaPartition );
-
-    List<Throwable> errors = schemaManager.getErrors();
-
-    if ( errors.size() != 0 )
-    {
-      throw new Exception( I18n.err( I18n.ERR_317, Exceptions.printErrors( errors ) ) );
-    }
-  }
-
-
-  /**
-   * Inits the system partition.
-   *
-   * @throws Exception the exception
-   */
-  private void initSystemPartition() throws Exception
-  {
-    // change the working directory to something that is unique
-    // on the system and somewhere either under target directory
-    // or somewhere in a temp area of the machine.
-
-    // Inject the System Partition
-    Partition systemPartition = partitionFactory.createPartition(
-        directoryService.getSchemaManager(),
-        directoryService.getDnFactory(),
-        "system",
-        ServerDNConstants.SYSTEM_DN,
-        500,
-        new File( directoryService.getInstanceLayout().getPartitionsDirectory(), "system" ) );
-    systemPartition.setSchemaManager( directoryService.getSchemaManager() );
-
-    partitionFactory.addIndex( systemPartition, SchemaConstants.OBJECT_CLASS_AT, 100 );
-
-    directoryService.setSystemPartition( systemPartition );
-  }
-
-
-  /**
-   * Builds the directory server instance.
-   *
-   * @param name the instance name
-   */
-  private void build( String name ) throws Exception
-  {
-    directoryService.setInstanceId( name );
-    buildInstanceDirectory( name );
-
-    CacheService cacheService = new CacheService();
-    cacheService.initialize( directoryService.getInstanceLayout() );
-
-    directoryService.setCacheService( cacheService );
-
-    // Init the service now
-    initSchema();
-    initSystemPartition();
-
-    directoryService.startup();
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public DirectoryService getDirectoryService() throws Exception
-  {
-    return directoryService;
-  }
-
-
-  /**
-   * {@inheritDoc}
-   */
-  public PartitionFactory getPartitionFactory() throws Exception
-  {
-    return partitionFactory;
-  }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/SimpleDirectoryService.java
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/SimpleDirectoryService.java b/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/SimpleDirectoryService.java
deleted file mode 100644
index 68fa1da..0000000
--- a/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/SimpleDirectoryService.java
+++ /dev/null
@@ -1,29 +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.hadoop.gateway.security.ldap;
-
-public class SimpleDirectoryService extends BaseDirectoryService {
-
-  public SimpleDirectoryService() throws Exception {
-  }
-
-  protected void showSecurityWarnings() throws Exception {
-    // NoOp - This prevents confusing warnings from being output.
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/SimpleDirectoryServiceFactory.java
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/SimpleDirectoryServiceFactory.java b/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/SimpleDirectoryServiceFactory.java
deleted file mode 100644
index 72a05ff..0000000
--- a/gateway-demo-ldap/src/main/java/org/apache/hadoop/gateway/security/ldap/SimpleDirectoryServiceFactory.java
+++ /dev/null
@@ -1,34 +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.hadoop.gateway.security.ldap;
-
-import org.apache.directory.server.core.api.DirectoryService;
-
-public class SimpleDirectoryServiceFactory extends BaseDirectoryServiceFactory {
-
-  protected DirectoryService createDirectoryService() {
-    DirectoryService result;
-    try {
-      result = new SimpleDirectoryService();
-    } catch( Exception e ) {
-      throw new RuntimeException( e );
-    }
-    return result;
-  }
-
-}


[25/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStepDescriptorFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStepDescriptorFactory.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStepDescriptorFactory.java
new file mode 100644
index 0000000..df05cf4
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStepDescriptorFactory.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.knox.gateway.filter.rewrite.api;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.ServiceLoader;
+import java.util.Set;
+
+public abstract class UrlRewriteStepDescriptorFactory {
+
+  private static Map<String,Class<? extends UrlRewriteStepDescriptor>> MAP = loadStepDescriptors();
+
+  private UrlRewriteStepDescriptorFactory() {
+  }
+
+  @SuppressWarnings("unchecked")
+  public static <T extends UrlRewriteStepDescriptor<?>> T create( String type ) {
+    try {
+      Class<? extends UrlRewriteStepDescriptor> descriptorClass = MAP.get( type );
+      return (T)descriptorClass.newInstance();
+    } catch( InstantiationException e ) {
+      throw new IllegalArgumentException( type );
+    } catch( IllegalAccessException e ) {
+      throw new IllegalArgumentException( type );
+    }
+  }
+
+  private static Map<String,Class<? extends UrlRewriteStepDescriptor>> loadStepDescriptors() {
+    Map<String,Class<? extends UrlRewriteStepDescriptor>> map
+        = new HashMap<>();
+    ServiceLoader<? extends UrlRewriteStepDescriptor> descriptors
+        = ServiceLoader.load( UrlRewriteStepDescriptor.class );
+    for( UrlRewriteStepDescriptor descriptor : descriptors ) {
+      String descriptorType = descriptor.type();
+      Class<? extends UrlRewriteStepDescriptor> descriptorClass = descriptor.getClass() ;
+      map.put( descriptorType, descriptorClass );
+    }
+    return map;
+  }
+
+  public static Set<String> getTypes() {
+    return MAP.keySet();
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStepFlow.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStepFlow.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStepFlow.java
new file mode 100644
index 0000000..ace4536
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStepFlow.java
@@ -0,0 +1,20 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+public enum UrlRewriteStepFlow { ALL, AND, OR }

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStreamFilterFactory.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStreamFilterFactory.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStreamFilterFactory.java
new file mode 100644
index 0000000..5a742b7
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStreamFilterFactory.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.knox.gateway.filter.rewrite.api;
+
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStreamFilter;
+import org.apache.knox.gateway.util.MimeTypes;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+
+import javax.activation.MimeType;
+import javax.activation.MimeTypeParseException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.ServiceLoader;
+
+public abstract class UrlRewriteStreamFilterFactory {
+
+  private static final String DEFAULT_CHARACTER_ENCODING = "ISO-8859-1";
+
+  private static final Map<String,Map<String,UrlRewriteStreamFilter>> MAP = loadFactories();
+
+  private UrlRewriteStreamFilterFactory() {
+  }
+
+  public static InputStream create(
+      MimeType type,
+      String name,
+      InputStream stream,
+      UrlRewriter rewriter,
+      Resolver resolver,
+      UrlRewriter.Direction direction,
+      UrlRewriteFilterContentDescriptor config )
+          throws IOException {
+    InputStream filteredStream = null;
+    Map<String,UrlRewriteStreamFilter> nameMap = getNameMap( type );
+    UrlRewriteStreamFilter filter = getFilter( nameMap, name );
+    String charset = MimeTypes.getCharset( type, DEFAULT_CHARACTER_ENCODING );
+    if( filter != null ) {
+      filteredStream = filter.filter( stream, charset, rewriter, resolver, direction, config );
+    }
+    return filteredStream;
+  }
+
+  private static Map<String,Map<String,UrlRewriteStreamFilter>> loadFactories() {
+    Map<String,Map<String,UrlRewriteStreamFilter>> typeMap = new HashMap<>();
+    ServiceLoader<UrlRewriteStreamFilter> filters = ServiceLoader.load( UrlRewriteStreamFilter.class );
+    for( UrlRewriteStreamFilter filter : filters ) {
+      String[] types = filter.getTypes();
+      for( String type: types ) {
+        Map<String,UrlRewriteStreamFilter> nameMap = typeMap.get( type );
+        if( nameMap == null ) {
+          nameMap = new LinkedHashMap<String,UrlRewriteStreamFilter>();
+          typeMap.put( type, nameMap );
+        }
+        for( String name: filter.getNames() ) {
+          nameMap.put( name, filter );
+        }
+      }
+    }
+    return typeMap;
+  }
+
+  private static Map<String,UrlRewriteStreamFilter> getNameMap( MimeType type ) {
+    if( type == null ) {
+      type = new MimeType();
+    }
+    Map<String,UrlRewriteStreamFilter> nameMap = MAP.get( type.getBaseType() );
+    try {
+      if( nameMap == null ) {
+        type.setPrimaryType( "*" );
+        nameMap = MAP.get( type.getBaseType() );
+        if( nameMap == null ) {
+          type.setSubType( "*" );
+          nameMap = MAP.get( type.getBaseType() );
+          if( nameMap == null ) {
+            nameMap = MAP.get( null );
+          }
+        }
+      }
+    } catch( MimeTypeParseException e ) {
+      throw new IllegalArgumentException( type.toString(), e );
+    }
+    return nameMap;
+  }
+
+  private static UrlRewriteStreamFilter getFilter( Map<String,UrlRewriteStreamFilter> map, String name ) {
+    UrlRewriteStreamFilter filter = null;
+    if( map != null ) {
+      if( name == null && !map.isEmpty() ) {
+        filter = map.values().iterator().next();
+      } else {
+        filter = map.get( name );
+      }
+    }
+    return filter;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriter.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriter.java
new file mode 100644
index 0000000..bfee565
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriter.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.api;
+
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+public interface UrlRewriter {
+
+  enum Direction { IN, OUT }
+
+  UrlRewriteRulesDescriptor getConfig();
+
+  Template rewrite( Resolver resolver, Template uri, Direction direction, String ruleName );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/ScopedMatcher.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/ScopedMatcher.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/ScopedMatcher.java
new file mode 100644
index 0000000..08efde4
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/ScopedMatcher.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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.ext;
+
+import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteRuleProcessorHolder;
+import org.apache.knox.gateway.util.urltemplate.Matcher;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A simple extension to the matcher that takes into account scopes for rules along with the templates themselves.
+ * This matcher maintains a list of matchers and delegates to an appropriate matcher based on scope information for the
+ * associated rules.
+ */
+public class ScopedMatcher extends Matcher<UrlRewriteRuleProcessorHolder> {
+
+  public static final String GLOBAL_SCOPE = "GLOBAL";
+
+  private List<Matcher<UrlRewriteRuleProcessorHolder>> matchers;
+
+  public ScopedMatcher() {
+    super();
+    matchers = new ArrayList<>();
+    matchers.add(new Matcher<UrlRewriteRuleProcessorHolder>());
+  }
+
+  @Override
+  public UrlRewriteRuleProcessorHolder get(Template template) {
+    return super.get(template);
+  }
+
+  @Override
+  public void add(Template template, UrlRewriteRuleProcessorHolder value) {
+    Matcher<UrlRewriteRuleProcessorHolder> matcher = getMatcher(template, value);
+    matcher.add( template, value );
+  }
+
+  @Override
+  public Match match(Template input) {
+    return match(input, null);
+  }
+
+  public Match match(Template input, String scope) {
+    List<Match> matches = new ArrayList<>();
+    for (Matcher<UrlRewriteRuleProcessorHolder> matcher : matchers) {
+      Match match = matcher.match(input);
+      if (match != null) {
+        matches.add(match);
+      }
+    }
+    if (matches.size() == 0) {
+      return null;
+    }
+    if (matches.size() == 1) {
+      return getMatch(matches, scope);
+    }
+    return findBestMatch(matches, scope);
+  }
+
+  private Match findBestMatch(List<Match> matches, String scope) {
+    if (scope != null) {
+      //when multiple matches are found, find the first one that matches in scope
+      for ( Match match : matches ) {
+        String matchedScope = match.getValue().getScope();
+        if ( matchedScope != null && matchedScope.equals(scope) ) {
+          return match;
+        }
+      }
+    }
+    //since no scope match was found return the first global scopeed match
+    for ( Match match : matches ) {
+      String matchedScope = match.getValue().getScope();
+      if ( matchedScope != null && matchedScope.equals(GLOBAL_SCOPE) ) {
+        return match;
+      }
+    }
+    //return the first match from the list
+    return getMatch(matches, scope);
+  }
+
+  private Match getMatch(List<Match> matches, String scope) {
+    Match match = matches.get(0);
+    String matchedScope = match.getValue().getScope();
+    if (matchedScope != null && scope != null && !matchedScope.equals(scope) && !matchedScope.equals(GLOBAL_SCOPE)) {
+      return null;
+    }
+    return match;
+  }
+
+  /**
+   * Returns a matcher for a given template and processor holder. This method takes into account different scopes in
+   * addition to template values. If a matcher exists for a template but the scope is different, a new matcher is
+   * created and returned.
+   * @param template the template for which a matcher is needed
+   * @param holder the rule holder that goes along with the template.
+   * @return a matcher
+   */
+  private Matcher<UrlRewriteRuleProcessorHolder> getMatcher(Template template, UrlRewriteRuleProcessorHolder holder) {
+    for (Matcher<UrlRewriteRuleProcessorHolder> matcher : matchers) {
+      UrlRewriteRuleProcessorHolder matchersHolder = matcher.get(template);
+      if (matchersHolder == null) {
+        return matcher;
+      } else if (holder.getScope() == null && matchersHolder.getScope() == null) {
+        return matcher;
+      }
+    }
+    Matcher<UrlRewriteRuleProcessorHolder> matcher = new Matcher<>();
+    matchers.add(matcher);
+    return matcher;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteActionDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteActionDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteActionDescriptor.java
new file mode 100644
index 0000000..6c4cf24
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteActionDescriptor.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.knox.gateway.filter.rewrite.ext;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
+
+public interface UrlRewriteActionDescriptor extends UrlRewriteStepDescriptor<UrlRewriteActionDescriptor> {
+
+  String operation();
+
+  UrlRewriteActionDescriptor operation( String operation );
+
+  String parameter();
+
+  UrlRewriteActionDescriptor parameter( String parameter );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteActionRewriteDescriptorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteActionRewriteDescriptorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteActionRewriteDescriptorExt.java
new file mode 100644
index 0000000..40edd14
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteActionRewriteDescriptorExt.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.knox.gateway.filter.rewrite.ext;
+
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
+
+public class UrlRewriteActionRewriteDescriptorExt
+    extends UrlRewriteActionDescriptorBase
+    implements UrlRewriteActionDescriptor {
+
+  public UrlRewriteActionRewriteDescriptorExt() {
+    super( "rewrite" );
+  }
+
+  public String template() {
+    return parameter();
+  }
+
+  public UrlRewriteActionRewriteDescriptorExt template( String template ) {
+    parameter( template );
+    return this;
+  }
+
+  public void setTemplate( String template ) {
+    parameter( template );
+  }
+
+  @Override
+  public String getParam() {
+    return null;
+  }
+
+  public String getTemplate() {
+    return parameter();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteActionRewriteProcessorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteActionRewriteProcessorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteActionRewriteProcessorExt.java
new file mode 100644
index 0000000..9b6eb89
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteActionRewriteProcessorExt.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.knox.gateway.filter.rewrite.ext;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+import org.apache.knox.gateway.util.urltemplate.Expander;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+public class UrlRewriteActionRewriteProcessorExt
+    implements UrlRewriteStepProcessor<UrlRewriteActionRewriteDescriptorExt> {
+
+  private Template template;
+  private Expander expander;
+
+  @Override
+  public String getType() {
+    return "rewrite";
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, UrlRewriteActionRewriteDescriptorExt descriptor ) throws Exception {
+    this.expander = new Expander();
+    if ( descriptor.parameter() != null ) {
+      this.template = Parser.parseTemplate( descriptor.parameter() );
+    } else {
+      this.template = Parser.parseTemplate( "" );
+    }
+  }
+
+  @Override
+  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
+    Template rewritten = expander.expandToTemplate( template, context.getParameters(), context.getEvaluator() );
+    context.setCurrentUrl( rewritten );
+    return UrlRewriteStepStatus.SUCCESS;
+  }
+
+  @Override
+  public void destroy() {
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptor.java
new file mode 100644
index 0000000..ec8696b
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptor.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.knox.gateway.filter.rewrite.ext;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFlowDescriptor;
+
+public interface UrlRewriteCheckDescriptor extends UrlRewriteFlowDescriptor<UrlRewriteCheckDescriptor> {
+
+  String operation();
+
+  UrlRewriteCheckDescriptor operation( String operation );
+
+  String input();
+
+  UrlRewriteCheckDescriptor input( String input );
+
+  String value();
+
+  UrlRewriteCheckDescriptor value( String value );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptorExt.java
new file mode 100644
index 0000000..e123929
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteCheckDescriptorExt.java
@@ -0,0 +1,99 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.ext;
+
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFlowDescriptorBase;
+
+public class UrlRewriteCheckDescriptorExt
+    extends UrlRewriteFlowDescriptorBase<UrlRewriteCheckDescriptor>
+    implements UrlRewriteCheckDescriptor {
+
+  private String operation;
+  private String input;
+  private String value;
+
+  public UrlRewriteCheckDescriptorExt() {
+    super( "check" );
+  }
+
+  @Override
+  public String operation() {
+    return operation;
+  }
+
+  @Override
+  public UrlRewriteCheckDescriptor operation( String operation ) {
+    this.operation = operation;
+    return this;
+  }
+
+  public void setOperation( String operation ) {
+    operation( operation );
+  }
+
+  public void setOper( String operation ) {
+    operation( operation );
+  }
+
+  public void setOp( String operation ) {
+    operation( operation );
+  }
+
+  public String getOper() {
+    return operation();
+  }
+
+  @Override
+  public String input() {
+    return input;
+  }
+
+  @Override
+  public UrlRewriteCheckDescriptor input( String input ) {
+    this.input = input;
+    return this;
+  }
+
+  public void setInput( String input ) {
+    input( input );
+  }
+
+  public String getInput() {
+    return input();
+  }
+
+  @Override
+  public String value() {
+    return value;
+  }
+
+  @Override
+  public UrlRewriteCheckDescriptor value( String value ) {
+    this.value = value;
+    return this;
+  }
+
+  public void setValue( String value ) {
+    value( value );
+  }
+
+  public String getValue() {
+    return value();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteCheckProcessorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteCheckProcessorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteCheckProcessorExt.java
new file mode 100644
index 0000000..f21aa2f
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteCheckProcessorExt.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.knox.gateway.filter.rewrite.ext;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+
+public class UrlRewriteCheckProcessorExt implements
+    UrlRewriteStepProcessor<UrlRewriteCheckDescriptor> {
+
+  @Override
+  public String getType() {
+    return "check";
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, UrlRewriteCheckDescriptor descriptor ) throws Exception {
+  }
+
+  @Override
+  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
+    return UrlRewriteStepStatus.FAILURE;
+  }
+
+  @Override
+  public void destroy() {
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteControlDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteControlDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteControlDescriptor.java
new file mode 100644
index 0000000..3146cff
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteControlDescriptor.java
@@ -0,0 +1,23 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.ext;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFlowDescriptor;
+
+public interface UrlRewriteControlDescriptor extends UrlRewriteFlowDescriptor<UrlRewriteControlDescriptor> {
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteControlDescriptorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteControlDescriptorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteControlDescriptorExt.java
new file mode 100644
index 0000000..39a77cf
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteControlDescriptorExt.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.knox.gateway.filter.rewrite.ext;
+
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFlowDescriptorBase;
+
+public class UrlRewriteControlDescriptorExt
+    extends UrlRewriteFlowDescriptorBase<UrlRewriteControlDescriptor>
+    implements UrlRewriteControlDescriptor {
+
+  public UrlRewriteControlDescriptorExt() {
+    super( "control" );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteControlProcessorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteControlProcessorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteControlProcessorExt.java
new file mode 100644
index 0000000..6e11082
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteControlProcessorExt.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.knox.gateway.filter.rewrite.ext;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+
+public class UrlRewriteControlProcessorExt implements
+    UrlRewriteStepProcessor<UrlRewriteControlDescriptor> {
+
+  @Override
+  public String getType() {
+    return "control";
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, UrlRewriteControlDescriptor descriptor ) throws Exception {
+  }
+
+  @Override
+  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
+    return UrlRewriteStepStatus.FAILURE;
+  }
+
+  @Override
+  public void destroy() {
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptor.java
new file mode 100644
index 0000000..6396516
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptor.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.knox.gateway.filter.rewrite.ext;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFlowDescriptor;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.net.URISyntaxException;
+
+public interface UrlRewriteMatchDescriptor extends
+    UrlRewriteFlowDescriptor<UrlRewriteMatchDescriptor> {
+
+  String operation();
+
+  UrlRewriteMatchDescriptor operation( String operation );
+
+  String pattern();
+
+  UrlRewriteMatchDescriptor pattern( String pattern ) throws URISyntaxException;
+
+  Template template();
+
+  UrlRewriteMatchDescriptor template( Template pattern );
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptorExt.java
new file mode 100644
index 0000000..51a08d5
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteMatchDescriptorExt.java
@@ -0,0 +1,110 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.ext;
+
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFlowDescriptorBase;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.net.URISyntaxException;
+
+public class UrlRewriteMatchDescriptorExt
+    extends UrlRewriteFlowDescriptorBase<UrlRewriteMatchDescriptor>
+    implements UrlRewriteMatchDescriptor {
+
+  private String operation;
+  private String pattern;
+  private Template template;
+
+  public UrlRewriteMatchDescriptorExt() {
+    super( "match" );
+  }
+
+  @Override
+  public String operation() {
+    return operation;
+  }
+
+  public String getOperation() {
+    return operation;
+  }
+
+  @Override
+  public UrlRewriteMatchDescriptor operation( String operation ) {
+    this.operation = operation;
+    return this;
+  }
+
+  public void setOperation( String operation ) {
+    operation( operation );
+  }
+
+  public void setOper( String operation ) {
+    operation( operation );
+  }
+
+  public void setOp( String operation ) {
+    operation( operation );
+  }
+
+  public String getOper() {
+    return operation();
+  }
+
+  @Override
+  public String pattern() {
+    return pattern;
+  }
+
+  @Override
+  public UrlRewriteMatchDescriptor pattern( String pattern ) throws URISyntaxException {
+    this.pattern = pattern;
+    this.template = Parser.parseTemplate( pattern );
+    return this;
+  }
+
+  public void setUrl( String pattern ) throws URISyntaxException {
+    pattern( pattern );
+  }
+
+  public void setPattern( String pattern ) throws URISyntaxException {
+    pattern( pattern );
+  }
+
+  public String getPattern() {
+    return pattern;
+  }
+
+  @Override
+  public Template template() {
+    return template;
+  }
+
+  @Override
+  public UrlRewriteMatchDescriptor template( Template template ) {
+    this.template = template;
+    // The template is now optional for rules.
+    if( template == null ) {
+      this.pattern = null;
+    } else {
+      this.pattern = template.toString();
+    }
+    return this;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteMatchProcessorExt.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteMatchProcessorExt.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteMatchProcessorExt.java
new file mode 100644
index 0000000..45c9155
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/UrlRewriteMatchProcessorExt.java
@@ -0,0 +1,67 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.ext;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+import org.apache.knox.gateway.util.urltemplate.Matcher;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+public class UrlRewriteMatchProcessorExt implements
+    UrlRewriteStepProcessor<UrlRewriteMatchDescriptor> {
+
+  //private UrlRewriteMatchDescriptor descriptor;
+  private Matcher<Void> matcher;
+
+  @Override
+  public String getType() {
+    return "match";
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, UrlRewriteMatchDescriptor descriptor ) throws Exception {
+    Template template = descriptor.template();
+    if( template == null ) {
+      this.matcher = null;
+    } else {
+      this.matcher = new Matcher<Void>( descriptor.template(), null );
+    }
+  }
+
+  @Override
+  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
+    UrlRewriteStepStatus status = UrlRewriteStepStatus.SUCCESS;
+    if( matcher != null ) {
+      status = UrlRewriteStepStatus.FAILURE;
+      Matcher.Match match = matcher.match( context.getCurrentUrl() );
+      if( match != null ) {
+        context.addParameters( match.getParams() );
+        status = UrlRewriteStepStatus.SUCCESS;
+      }
+    }
+    return status;
+  }
+
+  @Override
+  public void destroy() {
+    matcher = null;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/i18n/UrlRewriteMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/i18n/UrlRewriteMessages.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/i18n/UrlRewriteMessages.java
new file mode 100644
index 0000000..35247c9
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/i18n/UrlRewriteMessages.java
@@ -0,0 +1,87 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.i18n;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+import org.apache.knox.gateway.i18n.messages.Message;
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.Messages;
+import org.apache.knox.gateway.i18n.messages.StackTrace;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+@Messages(logger="org.apache.hadoop.gateway")
+public interface UrlRewriteMessages {
+
+  @Message( level = MessageLevel.DEBUG, text = "Failed to parse value as URL: {0}" )
+  void failedToParseValueForUrlRewrite( String value );
+
+  @Message( level = MessageLevel.ERROR, text = "Failed to write the rules descriptor: {0}" )
+  void failedToWriteRulesDescriptor( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
+
+  @Message( level = MessageLevel.DEBUG, text = "Failed to filter attribute {0}: {1}" )
+  void failedToFilterAttribute( String attributeName, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
+
+  @Message( level = MessageLevel.ERROR, text = "Failed to load rewrite rules descriptor: {0}" )
+  void failedToLoadRewriteRulesDescriptor( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
+
+  @Message( level = MessageLevel.ERROR, text = "Failed to initialize rewrite rules: {0}" )
+  void failedToInitializeRewriteRules( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
+
+  @Message( level = MessageLevel.ERROR, text = "Failed to initialize rewrite functions: {0}" )
+  void failedToInitializeRewriteFunctions( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
+
+  @Message( level = MessageLevel.ERROR, text = "Failed to destroy rewrite rule processor: {0}" )
+  void failedToDestroyRewriteStepProcessor( @StackTrace(level = MessageLevel.DEBUG) Exception e );
+
+  @Message( level = MessageLevel.ERROR, text = "Failed to destroy rewrite function processor: {0}" )
+  void failedToDestroyRewriteFunctionProcessor( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
+
+  @Message( level = MessageLevel.ERROR, text = "Failed to filter value {0}, rule {1}" )
+  void failedToFilterValue( String value, String rule );
+
+  @Message( level = MessageLevel.ERROR, text = "Failed to filter value {0}, rule {1}: {2}" )
+  void failedToFilterValue( String value, String rule, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
+
+  @Message( level = MessageLevel.ERROR, text = "Failed to filter field name {0}: {1}" )
+  void failedToFilterFieldName( String fieldName, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
+
+  @Message( level = MessageLevel.ERROR, text = "Rewrite function {0} failed: {1}" )
+  void failedToInvokeRewriteFunction( String functionName, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
+
+  @Message( level = MessageLevel.ERROR, text = "Failed to find values by parameter name {0}: {1}" )
+  void failedToFindValuesByParameter( String parameterName, @StackTrace( level = MessageLevel.DEBUG ) Exception e );
+
+  @Message( level = MessageLevel.DEBUG, text = "Rewrote URL: {0}, direction: {1} via implicit rule: {2} to URL: {3}" )
+  void rewroteUrlViaImplicitRule( Template inputUri, UrlRewriter.Direction direction, String ruleName, Template outputUri );
+
+  @Message( level = MessageLevel.DEBUG, text = "Rewrote URL: {0}, direction: {1} via explicit rule: {2} to URL: {3}" )
+  void rewroteUrlViaExplicitRule( Template inputUri, UrlRewriter.Direction direction, String ruleName, Template outputUri );
+
+  @Message( level = MessageLevel.ERROR, text = "Failed to rewrite URL: {0}, direction: {1} via rule: {2}, status: {3}" )
+  void failedToRewriteUrl( Template inputUri, UrlRewriter.Direction direction, String ruleName, UrlRewriteStepStatus stepStatus );
+
+  @Message( level = MessageLevel.ERROR, text = "Failed to rewrite URL: {0}, direction: {1}, rule: {2}" )
+  void failedToRewriteUrlDueToException( Template inputUri, UrlRewriter.Direction direction, String ruleName, @StackTrace(level = MessageLevel.DEBUG) Exception exception );
+
+  @Message( level = MessageLevel.TRACE, text = "No rule matching URL: {0}, direction: {1}" )
+  void noRuleMatchingUrl( Template inputUri, UrlRewriter.Direction direction );
+
+  @Message( level = MessageLevel.TRACE, text = "Failed to decode query string: {0}" )
+  void failedToDecodeQueryString( String queryString, @StackTrace(level = MessageLevel.TRACE) Exception exception );
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/i18n/UrlRewriteResources.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/i18n/UrlRewriteResources.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/i18n/UrlRewriteResources.java
new file mode 100644
index 0000000..8b4c7b5
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/i18n/UrlRewriteResources.java
@@ -0,0 +1,41 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.i18n;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
+import org.apache.knox.gateway.i18n.resources.Resource;
+import org.apache.knox.gateway.i18n.resources.Resources;
+
+@Resources
+public interface UrlRewriteResources {
+
+  @Resource( text="No importer for descriptor format {0}" )
+  String noImporterForFormat( String format );
+
+  @Resource( text="No exporter for descriptor format {0}" )
+  String noExporterForFormat( String format );
+
+  @Resource( text="Unexpected selector type {0}" )
+  String unexpectedRewritePathSelector( UrlRewriteFilterPathDescriptor selector );
+
+  @Resource( text="Unexpected selected node type {0}" )
+  String unexpectedSelectedNodeType( Object node );
+
+  @Resource( text="Invalid frontend rewrite function parameter {0}" )
+  String invalidFrontendFunctionParameter( String parameter );
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/CookieScopeResponseWrapper.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/CookieScopeResponseWrapper.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/CookieScopeResponseWrapper.java
new file mode 100644
index 0000000..8fbc3a7
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/CookieScopeResponseWrapper.java
@@ -0,0 +1,59 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.GatewayResponseWrapper;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.OutputStream;
+
+public class CookieScopeResponseWrapper extends GatewayResponseWrapper {
+
+    private static final String SET_COOKIE = "Set-Cookie";
+
+    private static final String COOKIE_PATH = "Path=/";
+
+    private final String scopePath;
+
+    public CookieScopeResponseWrapper(HttpServletResponse response, String gatewayPath) {
+        super(response);
+        this.scopePath = COOKIE_PATH + gatewayPath + "/";
+    }
+
+    @Override
+    public void addHeader(String name, String value) {
+        if (SET_COOKIE.equals(name)) {
+            String updatedCookie;
+            if (value.contains(COOKIE_PATH)) {
+                updatedCookie = value.replace(COOKIE_PATH, scopePath);
+            } else {
+                // append the scope path
+                updatedCookie = String.format("%s %s;", value, scopePath);
+            }
+            super.addHeader(name, updatedCookie);
+        } else {
+            super.addHeader(name, value);
+        }
+    }
+
+    @Override
+    public OutputStream getRawOutputStream() throws IOException {
+        return getResponse().getOutputStream();
+    }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessor.java
new file mode 100644
index 0000000..5964510
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessor.java
@@ -0,0 +1,125 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.FrontendFunctionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteResources;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteResolver;
+import org.apache.knox.gateway.i18n.resources.ResourcesFactory;
+import org.apache.knox.gateway.services.GatewayServices;
+
+import java.net.URI;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class FrontendFunctionProcessor implements UrlRewriteFunctionProcessor<FrontendFunctionDescriptor> {
+
+  private static UrlRewriteResources RES = ResourcesFactory.get( UrlRewriteResources.class );
+
+  private Map<String,UrlRewriteResolver> resolvers;
+
+  @Override
+  public String name() {
+    return FrontendFunctionDescriptor.FUNCTION_NAME;
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, FrontendFunctionDescriptor descriptor ) throws Exception {
+    if( environment == null ) {
+      throw new IllegalArgumentException( "environment==null" );
+    }
+    URI frontend = environment.getAttribute( FrontendFunctionDescriptor.FRONTEND_URI_ATTRIBUTE );
+    resolvers = new HashMap<>();
+    if( frontend == null ) {
+      resolvers.put( "url", new ParamResolver( "gateway.url" ) );
+      resolvers.put( "addr", new ParamResolver( "gateway.addr" ) );
+      resolvers.put( "scheme", new ParamResolver( "gateway.scheme" ) );
+      resolvers.put( "host", new ParamResolver( "gateway.host" ) );
+      resolvers.put( "port", new ParamResolver( "gateway.port" ) );
+      resolvers.put( "path", new ParamResolver( "gateway.path" ) );
+    } else {
+      resolvers.put( "url", new FixedResolver( frontend.toString() ) );
+      resolvers.put( "addr", new FixedResolver( frontend.getHost() + ":" + frontend.getPort() ) );
+      resolvers.put( "scheme", new FixedResolver( frontend.getScheme() ) );
+      resolvers.put( "host", new FixedResolver( frontend.getHost() ) );
+      resolvers.put( "port", new FixedResolver( Integer.toString( frontend.getPort() ) ) );
+      resolvers.put( "path", new FixedResolver( frontend.getPath() ) );
+    }
+    resolvers.put( "topology", new FixedResolver( (String)environment.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE) ) );
+    resolvers.put( "address", resolvers.get( "addr" ) );
+  }
+
+  @Override
+  public void destroy() throws Exception {
+    resolvers.clear();
+  }
+
+  @Override
+  public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
+    String parameter = "url";
+    if( parameters != null && parameters.size() > 0 ) {
+      String first = parameters.get( 0 );
+      if( first != null ) {
+        parameter = first;
+      }
+    }
+    parameter = parameter.trim().toLowerCase();
+    UrlRewriteResolver resolver = resolvers.get( parameter );
+    if( resolver == null ) {
+      throw new IllegalArgumentException( RES.invalidFrontendFunctionParameter( parameter ) );
+    }
+    List<String> results = resolver.resolve( context, parameters );
+    return results;
+  }
+
+  private static class ParamResolver implements UrlRewriteResolver {
+
+    private String paramName;
+
+    private ParamResolver( String paramName ) {
+      this.paramName = paramName;
+    }
+
+    @Override
+    public List<String> resolve( UrlRewriteContext context, List<String> parameter ) throws Exception {
+      return context.getParameters().resolve( paramName );
+    }
+
+  }
+
+  private static class FixedResolver implements UrlRewriteResolver {
+
+    private List<String> fixedValues;
+
+    private FixedResolver( String... fixedValues ) {
+      this.fixedValues = Arrays.asList( fixedValues );
+    }
+
+    @Override
+    public List<String> resolve( UrlRewriteContext context, List<String> parameter ) throws Exception {
+      return fixedValues;
+    }
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteContextImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteContextImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteContextImpl.java
new file mode 100644
index 0000000..8a7e2bc
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteContextImpl.java
@@ -0,0 +1,152 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.util.urltemplate.Evaluator;
+import org.apache.knox.gateway.util.urltemplate.Params;
+import org.apache.knox.gateway.util.urltemplate.Resolver;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class UrlRewriteContextImpl implements UrlRewriteContext {
+
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+
+  private UrlRewriteEnvironment environment;
+  private Resolver resolver;
+  private Evaluator evaluator;
+  private Map<String,UrlRewriteFunctionProcessor> functions;
+  private ContextParameters params;
+  private UrlRewriter.Direction direction;
+  private Template originalUrl;
+  private Template currentUrl;
+
+  public UrlRewriteContextImpl(
+      UrlRewriteEnvironment environment,
+      Resolver resolver,
+      Map<String,UrlRewriteFunctionProcessor> functions,
+      UrlRewriter.Direction direction,
+      Template url ) {
+    this.environment = environment;
+    this.resolver = resolver;
+    this.functions = functions;
+    this.params = new ContextParameters();
+    this.evaluator = new ContextEvaluator();
+    this.direction = direction;
+    this.originalUrl = url;
+    this.currentUrl = url;
+  }
+
+  @Override
+  public UrlRewriter.Direction getDirection() {
+    return direction;
+  }
+
+  @Override
+  public Template getOriginalUrl() {
+    return originalUrl;
+  }
+
+  @Override
+  public Template getCurrentUrl() {
+    return currentUrl;
+  }
+
+  @Override
+  public void setCurrentUrl( Template url ) {
+    currentUrl = url;
+  }
+
+  @Override
+  public void addParameters( Params parameters ) {
+    params.add( parameters );
+  }
+
+  @Override
+  public Params getParameters() {
+    return params;
+  }
+
+  @Override
+  public Evaluator getEvaluator() {
+    return evaluator;
+  }
+
+  private class ContextParameters implements Params {
+
+    Map<String,List<String>> map = new HashMap<>();
+
+    @Override
+    public Set<String> getNames() {
+      return map.keySet();
+    }
+
+    @Override
+    public List<String> resolve( String name ) {
+      List<String> values = map.get( name ); // Try to find the name in the context map.
+      if( values == null ) {
+        try {
+          values = resolver.resolve( name );
+          if( values == null ) {
+            values = environment.resolve( name ); // Try to find the name in the environment.
+          }
+        } catch( Exception e ) {
+          LOG.failedToFindValuesByParameter( name, e );
+          // Ignore it and return null.
+        }
+      }
+      return values;
+    }
+
+    public void add( Params params ) {
+      for( String name : params.getNames() ) {
+        map.put( name, params.resolve( name ) );
+      }
+    }
+
+  }
+
+  private class ContextEvaluator implements Evaluator {
+
+    @Override
+    public List<String> evaluate( String function, List<String> parameters ) {
+      List<String> results = null;
+      UrlRewriteFunctionProcessor processor = functions.get( function );
+      if( processor != null ) {
+        try {
+          results = processor.resolve( UrlRewriteContextImpl.this, parameters );
+        } catch( Exception e ) {
+          LOG.failedToInvokeRewriteFunction( function, e );
+          results = null;
+        }
+      }
+      return results;
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteDeploymentContributor.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteDeploymentContributor.java
new file mode 100644
index 0000000..e3213e8
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteDeploymentContributor.java
@@ -0,0 +1,101 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterDescriptor;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptorFactory;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletFilter;
+import org.apache.knox.gateway.filter.rewrite.i18n.UrlRewriteMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+import org.jboss.shrinkwrap.api.asset.StringAsset;
+
+import java.io.IOException;
+import java.io.StringWriter;
+import java.util.List;
+
+public class UrlRewriteDeploymentContributor extends
+    ProviderDeploymentContributorBase {
+
+  private static final String PROVIDER_ROLE_NAME = "rewrite";
+  private static final String PROVIDER_IMPL_NAME = "url-rewrite";
+  private static final String PARAM_SERVICE_ROLE = "service.role";
+  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
+
+  @Override
+  public String getRole() {
+    return PROVIDER_ROLE_NAME;
+  }
+
+  @Override
+  public String getName() {
+    return PROVIDER_IMPL_NAME;
+  }
+
+  public void initializeContribution( DeploymentContext context ) {
+    context.addDescriptor( getRole(), UrlRewriteRulesDescriptorFactory.create() );
+  }
+
+  public void contributeProvider( DeploymentContext context, Provider provider ) {
+  }
+
+  public void finalizeContribution( DeploymentContext context ) {
+    // Write the descriptor into the archive.
+    UrlRewriteRulesDescriptor descriptor = context.getDescriptor( getRole() );
+    StringWriter writer = new StringWriter();
+    try {
+      UrlRewriteRulesDescriptorFactory.store( descriptor, "xml", writer );
+    } catch( IOException e ) {
+      LOG.failedToWriteRulesDescriptor( e );
+    }
+    String asset = writer.toString();
+    context.getWebArchive().addAsWebInfResource(
+        new StringAsset( asset ),
+        UrlRewriteServletContextListener.DESCRIPTOR_DEFAULT_FILE_NAME );
+
+    // Tell the provider the location of the descriptor.
+    context.getWebAppDescriptor().createListener().listenerClass( UrlRewriteServletContextListener.class.getName() );
+    context.getWebAppDescriptor().createContextParam()
+        .paramName( UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME )
+        .paramValue( UrlRewriteServletContextListener.DESCRIPTOR_DEFAULT_LOCATION );
+//    ServletType<WebAppDescriptor> servlet = findServlet( context, context.getTopology().getName() );
+//    servlet.createInitParam()
+//        .paramName( UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME )
+//        .paramValue( DESCRIPTOR_FILE_NAME );
+  }
+
+  @Override
+  public void contributeFilter(
+      DeploymentContext context,
+      Provider provider,
+      Service service,
+      ResourceDescriptor resource,
+      List<FilterParamDescriptor> params ) {
+    FilterDescriptor filterDescriptor = resource.addFilter();
+    filterDescriptor.role( getRole() ).name( getName() ).impl( UrlRewriteServletFilter.class ).params( params );
+    filterDescriptor.param().name(PARAM_SERVICE_ROLE).value(service.getRole());
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterApplyDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterApplyDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterApplyDescriptorImpl.java
new file mode 100644
index 0000000..a11999d
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterApplyDescriptorImpl.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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
+
+public class UrlRewriteFilterApplyDescriptorImpl
+    extends UrlRewriteFilterSelectorDescriptorBase<UrlRewriteFilterApplyDescriptor>
+    implements UrlRewriteFilterApplyDescriptor {
+
+  private String rule;
+
+  @Override
+  public String rule() {
+    return rule;
+  }
+
+  @Override
+  public UrlRewriteFilterApplyDescriptor rule( String rule ) {
+    this.rule = rule;
+    return this;
+  }
+
+  public void setRule( String rule ) {
+    this.rule = rule;
+  }
+
+  public String getRule() {
+    return rule;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterBufferDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterBufferDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterBufferDescriptorImpl.java
new file mode 100644
index 0000000..3079f2d
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterBufferDescriptorImpl.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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterBufferDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterDetectDescriptor;
+
+public class UrlRewriteFilterBufferDescriptorImpl
+    extends UrlRewriteFilterGroupDescriptorBase
+    implements UrlRewriteFilterBufferDescriptor {
+
+  @Override
+  public UrlRewriteFilterDetectDescriptor addDetect( String path, String value ) {
+    UrlRewriteFilterDetectDescriptor detect = new UrlRewriteFilterDetectDescriptorImpl();
+    detect.path( path );
+    detect.value( value );
+    addSelector( detect );
+    return detect;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterContentDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterContentDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterContentDescriptorImpl.java
new file mode 100644
index 0000000..8176507
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterContentDescriptorImpl.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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterBufferDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+
+public class UrlRewriteFilterContentDescriptorImpl
+    extends UrlRewriteFilterGroupDescriptorBase
+    implements UrlRewriteFilterContentDescriptor {
+
+  private String type;
+
+  private String asType;
+
+  public UrlRewriteFilterContentDescriptorImpl() {
+  }
+
+  @Override
+  public String type() {
+    return this.type;
+  }
+
+  @Override
+  public String asType() {
+    return asType;
+  }
+
+  @Override
+  public UrlRewriteFilterContentDescriptor type( String type ) {
+    this.type = type;
+    return this;
+  }
+
+  @Override
+  public UrlRewriteFilterContentDescriptor asType( String type ) {
+    asType = type;
+    return this;
+  }
+
+  public void setType(String type ) {
+    type( type );
+  }
+
+  public String getType() {
+    return type;
+  }
+
+  public String getAsType() {
+    return asType;
+  }
+
+  public void setAsType(String asType) {
+    this.asType = asType;
+  }
+
+  @Override
+  public UrlRewriteFilterBufferDescriptor addBuffer( String path ) {
+    UrlRewriteFilterBufferDescriptor descriptor = new UrlRewriteFilterBufferDescriptorImpl();
+    descriptor.path( path );
+    addSelector( descriptor );
+    return descriptor;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterDescriptorImpl.java
new file mode 100644
index 0000000..70425ba
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterDescriptorImpl.java
@@ -0,0 +1,86 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterDescriptor;
+import org.apache.knox.gateway.util.MimeTypeMap;
+
+import javax.activation.MimeType;
+import javax.activation.MimeTypeParseException;
+import java.util.ArrayList;
+import java.util.List;
+
+public class UrlRewriteFilterDescriptorImpl implements
+    UrlRewriteFilterDescriptor {
+
+  private String name;
+  private List<UrlRewriteFilterContentDescriptor> contentList = new ArrayList<UrlRewriteFilterContentDescriptor>();
+  private MimeTypeMap<UrlRewriteFilterContentDescriptor> contentMap = new MimeTypeMap<UrlRewriteFilterContentDescriptor>();
+
+  public UrlRewriteFilterDescriptorImpl() {
+  }
+
+  @Override
+  public String name() {
+    return this.name;
+  }
+
+  public String getName() {
+    return name;
+  }
+
+  @Override
+  public UrlRewriteFilterDescriptor name( String name ) {
+    this.name = name;
+    return this;
+  }
+
+  public void setName( String name ) {
+    this.name = name;
+  }
+
+  @Override
+  public List<UrlRewriteFilterContentDescriptor> getContents() {
+    return contentList;
+  }
+
+  @Override
+  public UrlRewriteFilterContentDescriptor getContent( String type ) {
+    return contentMap.get( type );
+  }
+
+  @Override
+  public UrlRewriteFilterContentDescriptor getContent( MimeType type ) {
+    return contentMap.get( type );
+  }
+
+  @Override
+  public UrlRewriteFilterContentDescriptor addContent( String type ) {
+    UrlRewriteFilterContentDescriptorImpl impl = new UrlRewriteFilterContentDescriptorImpl();
+    impl.type( type );
+    contentList.add( impl );
+    try {
+      contentMap.put( new MimeType( type ), impl );
+    } catch( MimeTypeParseException e ) {
+      throw new IllegalArgumentException( type, e );
+    }
+    return impl;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterDetectDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterDetectDescriptorImpl.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterDetectDescriptorImpl.java
new file mode 100644
index 0000000..b78cef8
--- /dev/null
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteFilterDetectDescriptorImpl.java
@@ -0,0 +1,65 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterDetectDescriptor;
+
+public class UrlRewriteFilterDetectDescriptorImpl
+    extends UrlRewriteFilterGroupDescriptorBase
+    implements UrlRewriteFilterDetectDescriptor {
+
+  private String value;
+  private Object compiledValue;
+
+  @Override
+  public String value() {
+    return value;
+  }
+
+  @Override
+  public UrlRewriteFilterDetectDescriptor value( String value ) {
+    this.value = value;
+    return this;
+  }
+
+  public void setValue( String value ) {
+    this.value = value;
+  }
+
+  public String getValue() {
+    return value;
+  }
+
+  @Override
+  public <C> C compiledValue() {
+    return (C)compiledValue;
+  }
+
+  @Override
+  public UrlRewriteFilterDetectDescriptor compiledValue( String compiledValue ) {
+    this.compiledValue = compiledValue;
+    return this;
+  }
+
+  @Override
+  public <C> C compiledValue( Compiler<C> compiler ) {
+    compiledValue = compiler.compile( value, (C)compiledValue );
+    return (C)compiledValue;
+  }
+
+}


[02/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayServer.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayServer.java b/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayServer.java
deleted file mode 100644
index 2fa803f..0000000
--- a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayServer.java
+++ /dev/null
@@ -1,1029 +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.hadoop.gateway;
-
-import net.lingala.zip4j.core.ZipFile;
-import net.lingala.zip4j.exception.ZipException;
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.ParseException;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.hadoop.gateway.audit.api.Action;
-import org.apache.hadoop.gateway.audit.api.ActionOutcome;
-import org.apache.hadoop.gateway.audit.api.AuditServiceFactory;
-import org.apache.hadoop.gateway.audit.api.Auditor;
-import org.apache.hadoop.gateway.audit.api.ResourceType;
-import org.apache.hadoop.gateway.audit.log4j.audit.AuditConstants;
-import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.config.impl.GatewayConfigImpl;
-import org.apache.hadoop.gateway.deploy.DeploymentException;
-import org.apache.hadoop.gateway.deploy.DeploymentFactory;
-import org.apache.hadoop.gateway.filter.CorrelationHandler;
-import org.apache.hadoop.gateway.filter.PortMappingHelperHandler;
-import org.apache.hadoop.gateway.filter.RequestUpdateHandler;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.i18n.resources.ResourcesFactory;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-import org.apache.hadoop.gateway.services.security.SSLService;
-import org.apache.hadoop.gateway.services.topology.TopologyService;
-import org.apache.hadoop.gateway.topology.Application;
-import org.apache.hadoop.gateway.topology.Topology;
-import org.apache.hadoop.gateway.topology.TopologyEvent;
-import org.apache.hadoop.gateway.topology.TopologyListener;
-import org.apache.hadoop.gateway.trace.AccessHandler;
-import org.apache.hadoop.gateway.trace.ErrorHandler;
-import org.apache.hadoop.gateway.trace.TraceHandler;
-import org.apache.hadoop.gateway.util.Urls;
-import org.apache.hadoop.gateway.util.XmlUtils;
-import org.apache.hadoop.gateway.websockets.GatewayWebsocketHandler;
-import org.apache.log4j.PropertyConfigurator;
-import org.eclipse.jetty.server.ConnectionFactory;
-import org.eclipse.jetty.server.Connector;
-import org.eclipse.jetty.server.HttpConfiguration;
-import org.eclipse.jetty.server.HttpConnectionFactory;
-import org.eclipse.jetty.server.NetworkConnector;
-import org.eclipse.jetty.server.SecureRequestCustomizer;
-import org.eclipse.jetty.server.Server;
-import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.server.handler.ContextHandler;
-import org.eclipse.jetty.server.handler.ContextHandlerCollection;
-import org.eclipse.jetty.server.handler.HandlerCollection;
-import org.eclipse.jetty.server.handler.RequestLogHandler;
-import org.eclipse.jetty.servlets.gzip.GzipHandler;
-import org.eclipse.jetty.util.ssl.SslContextFactory;
-import org.eclipse.jetty.util.thread.QueuedThreadPool;
-import org.eclipse.jetty.webapp.Configuration;
-import org.eclipse.jetty.webapp.WebAppContext;
-import org.jboss.shrinkwrap.api.exporter.ExplodedExporter;
-import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.TransformerException;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.FilenameFilter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Serializable;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.UnknownHostException;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.CertificateException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.ServiceLoader;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.regex.Pattern;
-
-public class GatewayServer {
-  private static final GatewayResources res = ResourcesFactory.get(GatewayResources.class);
-  private static final GatewayMessages log = MessagesFactory.get(GatewayMessages.class);
-  private static final Auditor auditor = AuditServiceFactory.getAuditService().getAuditor(AuditConstants.DEFAULT_AUDITOR_NAME,
-      AuditConstants.KNOX_SERVICE_NAME, AuditConstants.KNOX_COMPONENT_NAME);
-  private static final String DEFAULT_CONNECTOR_NAME = "default";
-
-  private static GatewayServer server;
-  private static GatewayServices services;
-
-  private static Properties buildProperties;
-
-  private Server jetty;
-  private GatewayConfig config;
-  private ContextHandlerCollection contexts;
-  private TopologyService monitor;
-  private TopologyListener listener;
-  private Map<String, WebAppContext> deployments;
-
-  public static void main( String[] args ) {
-    try {
-      configureLogging();
-      logSysProps();
-      CommandLine cmd = GatewayCommandLine.parse( args );
-      if( cmd.hasOption( GatewayCommandLine.HELP_LONG ) ) {
-        GatewayCommandLine.printHelp();
-      } else if( cmd.hasOption( GatewayCommandLine.VERSION_LONG ) ) {
-        printVersion();
-      } else if( cmd.hasOption( GatewayCommandLine.REDEPLOY_LONG  ) ) {
-        redeployTopologies( cmd.getOptionValue( GatewayCommandLine.REDEPLOY_LONG ) );
-      } else {
-        buildProperties = loadBuildProperties();
-        services = instantiateGatewayServices();
-        if (services == null) {
-          log.failedToInstantiateGatewayServices();
-        }
-        GatewayConfig config = new GatewayConfigImpl();
-        if (config.isHadoopKerberosSecured()) {
-          configureKerberosSecurity( config );
-        }
-        Map<String,String> options = new HashMap<>();
-        options.put(GatewayCommandLine.PERSIST_LONG, Boolean.toString(cmd.hasOption(GatewayCommandLine.PERSIST_LONG)));
-        services.init(config, options);
-        if (!cmd.hasOption(GatewayCommandLine.NOSTART_LONG)) {
-          startGateway( config, services );
-        }
-      }
-    } catch ( ParseException e ) {
-      log.failedToParseCommandLine( e );
-      GatewayCommandLine.printHelp();
-    } catch ( Exception e ) {
-      log.failedToStartGateway( e );
-      // Make sure the process exits.
-      System.exit(1);
-    }
-  }
-
-  private static void printVersion() {
-    System.out.println( res.gatewayVersionMessage( // I18N not required.
-        getBuildVersion(),
-        getBuildHash() ) );
-  }
-
-  public static String getBuildHash() {
-    String hash = "unknown";
-    if( buildProperties != null ) {
-      hash = buildProperties.getProperty( "build.hash", hash );
-    }
-    return hash;
-  }
-
-  public static String getBuildVersion() {
-    String version = "unknown";
-    if( buildProperties != null ) {
-      version = buildProperties.getProperty( "build.version", version );
-    }
-    return version;
-  }
-
-  private static GatewayServices instantiateGatewayServices() {
-    ServiceLoader<GatewayServices> loader = ServiceLoader.load( GatewayServices.class );
-    Iterator<GatewayServices> services = loader.iterator();
-    if (services.hasNext()) {
-      return services.next();
-    }
-    return null;
-  }
-
-  public static synchronized GatewayServices getGatewayServices() {
-    return services;
-  }
-
-  private static void logSysProp( String name ) {
-    log.logSysProp( name, System.getProperty( name ) );
-  }
-
-  private static void logSysProps() {
-    logSysProp( "user.name" );
-    logSysProp( "user.dir" );
-    logSysProp( "java.runtime.name" );
-    logSysProp( "java.runtime.version" );
-    logSysProp( "java.home" );
-  }
-
-  private static void configureLogging() {
-    PropertyConfigurator.configure( System.getProperty( "log4j.configuration" ) );
-//    String fileName = config.getGatewayConfDir() + File.separator + "log4j.properties";
-//    File file = new File( fileName );
-//    if( file.isFile() && file.canRead() ) {
-//      FileInputStream stream;
-//      try {
-//        stream = new FileInputStream( file );
-//        Properties properties = new Properties();
-//        properties.load( stream );
-//        PropertyConfigurator.configure( properties );
-//        log.loadedLoggingConfig( fileName );
-//      } catch( IOException e ) {
-//        log.failedToLoadLoggingConfig( fileName );
-//      }
-//    }
-  }
-
-  private static void configureKerberosSecurity( GatewayConfig config ) {
-    System.setProperty(GatewayConfig.HADOOP_KERBEROS_SECURED, "true");
-    System.setProperty(GatewayConfig.KRB5_CONFIG, config.getKerberosConfig());
-    System.setProperty(GatewayConfig.KRB5_DEBUG,
-        Boolean.toString(config.isKerberosDebugEnabled()));
-    System.setProperty(GatewayConfig.KRB5_LOGIN_CONFIG, config.getKerberosLoginConfig());
-    System.setProperty(GatewayConfig.KRB5_USE_SUBJECT_CREDS_ONLY,  "false");
-  }
-
-  private static Properties loadBuildProperties() {
-    Properties properties = new Properties();
-    InputStream inputStream = GatewayServer.class.getClassLoader().getResourceAsStream( "build.properties" );
-    if( inputStream != null ) {
-      try {
-        properties.load( inputStream );
-        inputStream.close();
-      } catch( IOException e ) {
-        // Ignore.
-      }
-    }
-    return properties;
-  }
-
-  public static void redeployTopologies( String topologyName  ) {
-    TopologyService ts = getGatewayServices().getService(GatewayServices.TOPOLOGY_SERVICE);
-    ts.reloadTopologies();
-    ts.redeployTopologies(topologyName);
-  }
-
-  private void cleanupTopologyDeployments() {
-    File deployDir = new File( config.getGatewayDeploymentDir() );
-    TopologyService ts = getGatewayServices().getService(GatewayServices.TOPOLOGY_SERVICE);
-    for( Topology topology : ts.getTopologies() ) {
-      cleanupTopologyDeployments( deployDir, topology );
-    }
-  }
-
-  private void cleanupTopologyDeployments( File deployDir, Topology topology ) {
-    log.cleanupDeployments( topology.getName() );
-    File[] files = deployDir.listFiles( new RegexFilenameFilter( topology.getName() + "\\.(war|topo)\\.[0-9A-Fa-f]+" ) );
-    if( files != null ) {
-      Arrays.sort( files, new FileModificationTimeDescendingComparator() );
-      int verLimit = config.getGatewayDeploymentsBackupVersionLimit();
-      long ageLimit = config.getGatewayDeploymentsBackupAgeLimit();
-      long keepTime = System.currentTimeMillis() - ageLimit;
-      for( int i=1; i<files.length; i++ ) {
-        File file = files[i];
-        if( ( ( verLimit >= 0 ) && ( i > verLimit ) ) ||
-            ( ( ageLimit >= 0 ) && ( file.lastModified() < keepTime ) ) ) {
-          log.cleanupDeployment( file.getAbsolutePath() );
-          FileUtils.deleteQuietly( file );
-        }
-      }
-    }
-  }
-
-  public static GatewayServer startGateway( GatewayConfig config, GatewayServices svcs ) throws Exception {
-    log.startingGateway();
-    server = new GatewayServer( config );
-    synchronized ( server ) {
-      //KM[ Commented this out because is causes problems with
-      // multiple services instance used in a single test process.
-      // I'm not sure what drive including this check though.
-      //if (services == null) {
-      services = svcs;
-      //}
-      //KM]
-      services.start();
-      DeploymentFactory.setGatewayServices(services);
-      server.start();
-      // Coverity CID 1352654
-      URI uri = server.jetty.getURI();
-
-      // Logging for topology <-> port
-      InetSocketAddress[] addresses = new InetSocketAddress[server.jetty
-          .getConnectors().length];
-      for (int i = 0, n = addresses.length; i < n; i++) {
-        NetworkConnector connector = (NetworkConnector) server.jetty
-            .getConnectors()[i];
-        if (connector != null) {
-          for(ConnectionFactory x  : connector.getConnectionFactories()) {
-            if(x instanceof HttpConnectionFactory) {
-                ((HttpConnectionFactory)x).getHttpConfiguration().setSendServerVersion(config.isGatewayServerHeaderEnabled());
-            }
-          }
-          if (connector.getName() == null) {
-            log.startedGateway(
-                connector != null ? connector.getLocalPort() : -1);
-          } else {
-            log.startedGateway(connector != null ? connector.getName() : "",
-                connector != null ? connector.getLocalPort() : -1);
-          }
-        }
-      }
-
-      return server;
-    }
-  }
-
-  public GatewayServer( GatewayConfig config ) {
-    this(config, null);
-  }
-
-  public GatewayServer( GatewayConfig config, Properties options ) {
-      this.config = config;
-      this.listener = new InternalTopologyListener();
-  }
-
-  /**
-   * Create a connector for Gateway Server to listen on.
-   *
-   * @param server       Jetty server
-   * @param config       GatewayConfig
-   * @param port         If value is > 0 then the given value is used else we
-   *                     use the port provided in GatewayConfig.
-   * @param topologyName Connector name, only used when not null
-   * @return
-   * @throws IOException
-   * @throws CertificateException
-   * @throws NoSuchAlgorithmException
-   * @throws KeyStoreException
-   */
-  private static Connector createConnector(final Server server,
-      final GatewayConfig config, final int port, final String topologyName)
-      throws IOException, CertificateException, NoSuchAlgorithmException,
-      KeyStoreException {
-
-    ServerConnector connector;
-
-    // Determine the socket address and check availability.
-    InetSocketAddress address = config.getGatewayAddress();
-    checkAddressAvailability( address );
-
-    final int connectorPort = port > 0 ? port : address.getPort();
-
-    checkPortConflict(connectorPort, topologyName, config);
-
-    HttpConfiguration httpConfig = new HttpConfiguration();
-    httpConfig.setRequestHeaderSize( config.getHttpServerRequestHeaderBuffer() );
-    //httpConfig.setRequestBufferSize( config.getHttpServerRequestBuffer() );
-    httpConfig.setResponseHeaderSize( config.getHttpServerResponseHeaderBuffer() );
-    httpConfig.setOutputBufferSize( config.getHttpServerResponseBuffer() );
-
-    if (config.isSSLEnabled()) {
-      HttpConfiguration httpsConfig = new HttpConfiguration( httpConfig );
-      httpsConfig.setSecureScheme( "https" );
-      httpsConfig.setSecurePort( connectorPort );
-      httpsConfig.addCustomizer( new SecureRequestCustomizer() );
-      SSLService ssl = services.getService("SSLService");
-      String keystoreFileName = config.getGatewaySecurityDir() + File.separatorChar + "keystores" + File.separatorChar + "gateway.jks";
-      SslContextFactory sslContextFactory = (SslContextFactory)ssl.buildSslContextFactory( keystoreFileName );
-      connector = new ServerConnector( server, sslContextFactory, new HttpConnectionFactory( httpsConfig ) );
-    } else {
-      connector = new ServerConnector( server );
-    }
-    connector.setHost( address.getHostName() );
-    connector.setPort( connectorPort );
-
-    if(!StringUtils.isBlank(topologyName)) {
-      connector.setName(topologyName);
-    }
-
-    long idleTimeout = config.getGatewayIdleTimeout();
-    if (idleTimeout > 0l) {
-      connector.setIdleTimeout(idleTimeout);
-    }
-
-    return connector;
-  }
-
-  private static HandlerCollection createHandlers(
-      final GatewayConfig config,
-      final GatewayServices services,
-      final ContextHandlerCollection contexts,
-      final Map<String, Integer> topologyPortMap) {
-    HandlerCollection handlers = new HandlerCollection();
-    RequestLogHandler logHandler = new RequestLogHandler();
-
-    logHandler.setRequestLog( new AccessHandler() );
-
-    TraceHandler traceHandler = new TraceHandler();
-    traceHandler.setHandler( contexts );
-    traceHandler.setTracedBodyFilter( System.getProperty( "org.apache.knox.gateway.trace.body.status.filter" ) );
-
-    CorrelationHandler correlationHandler = new CorrelationHandler();
-    correlationHandler.setHandler( traceHandler );
-
-    /* KNOX-732: Handler for GZip compression */
-    GzipHandler gzipHandler = new GzipHandler();
-    String[] mimeTypes = {};
-    if (config.getMimeTypesToCompress() != null
-        && !config.getMimeTypesToCompress().isEmpty()) {
-      mimeTypes = (String[]) config.getMimeTypesToCompress().toArray();
-    }
-    gzipHandler.addIncludedMimeTypes(mimeTypes);
-    gzipHandler.setHandler(correlationHandler);
-
-    // Used to correct the {target} part of request with Topology Port Mapping feature
-    final PortMappingHelperHandler portMappingHandler = new PortMappingHelperHandler(config);
-    portMappingHandler.setHandler(gzipHandler);
-
-     // If topology to port mapping feature is enabled then we add new Handler {RequestForwardHandler}
-     // to the chain, this handler listens on the configured port (in gateway-site.xml)
-     // and simply forwards requests to the correct context path.
-
-     //  The reason for adding ContextHandler is so that we can add a connector
-     // to it on which the handler listens (exclusively).
-
-
-    if (config.isGatewayPortMappingEnabled()) {
-
-      for (final Map.Entry<String, Integer> entry : topologyPortMap
-          .entrySet()) {
-        log.createJettyHandler(entry.getKey());
-        final ContextHandler topologyContextHandler = new ContextHandler();
-
-        final RequestUpdateHandler updateHandler = new RequestUpdateHandler(
-            config, entry.getKey(), services);
-
-        topologyContextHandler.setHandler(updateHandler);
-        topologyContextHandler.setVirtualHosts(
-            new String[] { "@" + entry.getKey().toLowerCase() });
-
-        handlers.addHandler(topologyContextHandler);
-      }
-
-    }
-
-    handlers.addHandler(logHandler);
-
-    if (config.isWebsocketEnabled()) {      
-      final GatewayWebsocketHandler websocketHandler = new GatewayWebsocketHandler(
-          config, services);
-      websocketHandler.setHandler(portMappingHandler);
-
-      handlers.addHandler(websocketHandler);
-
-    } else {
-      handlers.addHandler(portMappingHandler);
-    }
-
-    return handlers;
-  }
-
-  /**
-   * Sanity Check to make sure configured ports are free and there is not port
-   * conflict.
-   *
-   * @param port
-   * @param topologyName
-   * @param config
-   * @throws IOException
-   */
-  public static void checkPortConflict(final int port,
-      final String topologyName, final GatewayConfig config)
-      throws IOException {
-
-    // Throw an exception if port in use
-    if (isPortInUse(port)) {
-      if (topologyName == null) {
-        log.portAlreadyInUse(port);
-      } else {
-        log.portAlreadyInUse(port, topologyName);
-      }
-      throw new IOException(String.format(" Port %d already in use. ", port));
-    }
-
-    // if topology name is blank which means we have all topologies listening on this port
-    if (StringUtils.isBlank(topologyName)) {
-      // If we have Default Topology old and new configuration (Port Mapping) throw error.
-      if (config.getGatewayPortMappings().containsValue(new Integer(port))
-          && !StringUtils.isBlank(config.getDefaultTopologyName())) {
-        log.portAlreadyInUse(port);
-        throw new IOException(String.format(
-            " Please map port %d using either \"gateway.port.mapping.sandbox\" or "
-                + "\"default.app.topology.name\" property, "
-                + "specifying both is not a valid configuration. ",
-            port));
-      }
-    } else {
-      // Topology name is not blank so check amongst other ports if we have a conflict
-      for (final Map.Entry<String, Integer> entry : config
-          .getGatewayPortMappings().entrySet()) {
-        if (entry.getKey().equalsIgnoreCase(topologyName)) {
-          continue;
-        }
-
-        if (entry.getValue() == port) {
-          log.portAlreadyInUse(port, topologyName);
-          throw new IOException(String.format(
-              " Topologies %s and %s use the same port %d, ports for topologies (if defined) have to be unique. ",
-              entry.getKey(), topologyName, port));
-        }
-
-      }
-
-    }
-
-  }
-
-  private synchronized void start() throws Exception {
-    // Create the global context handler.
-    contexts = new ContextHandlerCollection();
-
-     // A map to keep track of current deployments by cluster name.
-    deployments = new ConcurrentHashMap<>();
-
-    // Start Jetty.
-    jetty = new Server( new QueuedThreadPool( config.getThreadPoolMax() ) );
-
-    /* topologyName is null because all topology listen on this port */
-    jetty.addConnector( createConnector( jetty, config, config.getGatewayPort(), null) );
-
-
-    // Add Annotations processing into the Jetty server to support JSPs
-    Configuration.ClassList classlist = Configuration.ClassList.setServerDefault( jetty );
-    classlist.addBefore(
-        "org.eclipse.jetty.webapp.JettyWebXmlConfiguration",
-        "org.eclipse.jetty.annotations.AnnotationConfiguration" );
-
-    // Load the current topologies.
-    File topologiesDir = calculateAbsoluteTopologiesDir();
-    log.loadingTopologiesFromDirectory(topologiesDir.getAbsolutePath());
-    monitor = services.getService(GatewayServices.TOPOLOGY_SERVICE);
-    monitor.addTopologyChangeListener(listener);
-    monitor.reloadTopologies();
-
-    final Collection<Topology> topologies = monitor.getTopologies();
-    final Map<String, Integer> topologyPortMap = config.getGatewayPortMappings();
-
-    // List of all the topology that are deployed
-    final List<String> deployedTopologyList = new ArrayList<String>();
-
-    for (final Topology t : topologies) {
-      deployedTopologyList.add(t.getName());
-    }
-
-
-    // Check whether the configured topologies for port mapping exist, if not
-    // log WARN message and continue
-    checkMappedTopologiesExist(topologyPortMap, deployedTopologyList);
-
-    final HandlerCollection handlers = createHandlers( config, services, contexts, topologyPortMap);
-
-     // Check whether a topology wants dedicated port,
-     // if yes then we create a connector that listens on the provided port.
-
-    log.gatewayTopologyPortMappingEnabled(config.isGatewayPortMappingEnabled());
-    if (config.isGatewayPortMappingEnabled()) {
-      for (Map.Entry<String, Integer> entry : topologyPortMap.entrySet()) {
-        // Add connector for only valid topologies, i.e. deployed topologies.
-        // and NOT for Default Topology listening on standard gateway port.
-        if(deployedTopologyList.contains(entry.getKey()) && (entry.getValue().intValue() != config.getGatewayPort()) ) {
-          log.createJettyConnector(entry.getKey().toLowerCase(), entry.getValue());
-          jetty.addConnector(createConnector(jetty, config, entry.getValue(),
-              entry.getKey().toLowerCase()));
-        }
-      }
-    }
-
-    jetty.setHandler(handlers);
-
-    try {
-      jetty.start();
-    }
-    catch (IOException e) {
-      log.failedToStartGateway( e );
-      throw e;
-    }
-
-    cleanupTopologyDeployments();
-
-    // Start the topology monitor.
-    log.monitoringTopologyChangesInDirectory(topologiesDir.getAbsolutePath());
-    monitor.startMonitor();
-  }
-
-  public synchronized void stop() throws Exception {
-    log.stoppingGateway();
-    services.stop();
-    monitor.stopMonitor();
-    jetty.stop();
-    jetty.join();
-    log.stoppedGateway();
-  }
-
-  /**
-   * Check whether a port is free
-   *
-   * @param port
-   * @return true if port in use else false
-   */
-  public static boolean isPortInUse(final int port) {
-
-    Socket socket = null;
-    try {
-      socket = new Socket("localhost", port);
-      return true;
-    } catch (final UnknownHostException e) {
-      return false;
-    } catch (final IOException e) {
-      return false;
-    } finally {
-      IOUtils.closeQuietly(socket);
-    }
-
-  }
-
-  /**
-   * Checks whether the topologies defined in gateway-xml as part of Topology
-   * Port mapping feature exists. If it does not Log a message and move on.
-   *
-   * @param configTopologies
-   * @param topologies
-   * @return
-   */
-  private void checkMappedTopologiesExist(
-      final Map<String, Integer> configTopologies,
-      final List<String> topologies) throws IOException {
-
-    for(final Map.Entry<String, Integer> entry : configTopologies.entrySet()) {
-
-      // If the topologies defined in gateway-config.xml are not found in gateway
-      if (!topologies.contains(entry.getKey())) {
-        log.topologyPortMappingCannotFindTopology(entry.getKey(), entry.getValue());
-      }
-
-    }
-
-  }
-
-  public URI getURI() {
-    return jetty.getURI();
-  }
-
-  public InetSocketAddress[] getAddresses() {
-    InetSocketAddress[] addresses = new InetSocketAddress[ jetty.getConnectors().length ];
-    for( int i=0, n=addresses.length; i<n; i++ ) {
-      NetworkConnector connector = (NetworkConnector)jetty.getConnectors()[ i ];
-      String host = connector.getHost();
-      if( host == null ) {
-        addresses[ i ] = new InetSocketAddress( connector.getLocalPort() );
-      } else {
-        addresses[ i ] = new InetSocketAddress( host, connector.getLocalPort() );
-      }
-    }
-    return addresses;
-  }
-
-  private ErrorHandler createErrorHandler() {
-    ErrorHandler errorHandler = new ErrorHandler();
-    errorHandler.setShowStacks( false );
-    errorHandler.setTracedBodyFilter( System.getProperty( "org.apache.knox.gateway.trace.body.status.filter" ) );
-    return errorHandler;
-  }
-
-  private WebAppContext createWebAppContext( Topology topology, File warFile, String warPath ) throws IOException, ZipException, TransformerException, SAXException, ParserConfigurationException {
-    String topoName = topology.getName();
-    WebAppContext context = new WebAppContext();
-    String contextPath;
-    contextPath = "/" + Urls.trimLeadingAndTrailingSlashJoin( config.getGatewayPath(), topoName, warPath );
-    context.setContextPath( contextPath );
-    context.setWar( warFile.getAbsolutePath() );
-    context.setAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE, topoName );
-    context.setAttribute( "org.apache.knox.gateway.frontend.uri", getFrontendUri( context, config ) );
-    context.setAttribute( GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE, config );
-    // Add support for JSPs.
-    context.setAttribute(
-        "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern",
-        ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/[^/]*taglibs.*\\.jar$" );
-    context.setTempDirectory( FileUtils.getFile( warFile, "META-INF", "temp" ) );
-    context.setErrorHandler( createErrorHandler() );
-    context.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
-
-    return context;
-  }
-
-  private static void explodeWar( File source, File target ) throws IOException, ZipException {
-    if( source.isDirectory() ) {
-      FileUtils.copyDirectory( source, target );
-    } else {
-      ZipFile zip = new ZipFile( source );
-      zip.extractAll( target.getAbsolutePath() );
-    }
-  }
-
-  private void mergeWebXmlOverrides( File webInfDir ) throws IOException, SAXException, ParserConfigurationException, TransformerException {
-    File webXmlFile = new File( webInfDir, "web.xml" );
-    Document webXmlDoc;
-    if( webXmlFile.exists() ) {
-      // Backup original web.xml file.
-      File originalWebXmlFile = new File( webInfDir, "original-web.xml" );
-      FileUtils.copyFile( webXmlFile, originalWebXmlFile );
-      webXmlDoc = XmlUtils.readXml( webXmlFile );
-    } else {
-      webXmlDoc = XmlUtils.createDocument();
-      webXmlDoc.appendChild( webXmlDoc.createElement( "web-app" ) );
-    }
-    File overrideWebXmlFile = new File( webInfDir, "override-web.xml" );
-    if( overrideWebXmlFile.exists() ) {
-      Document overrideWebXmlDoc = XmlUtils.readXml( overrideWebXmlFile );
-      Element originalRoot = webXmlDoc.getDocumentElement();
-      Element overrideRoot = overrideWebXmlDoc.getDocumentElement();
-      NodeList overrideNodes = overrideRoot.getChildNodes();
-      for( int i = 0, n = overrideNodes.getLength(); i < n; i++ ) {
-        Node overrideNode = overrideNodes.item( i );
-        if( overrideNode.getNodeType() == Node.ELEMENT_NODE ) {
-          Node importedNode = webXmlDoc.importNode( overrideNode, true );
-          originalRoot.appendChild( importedNode );
-        }
-      }
-      
-      XmlUtils.writeXml( webXmlDoc, new FileWriter(webXmlFile) );
-    }
-  }
-
-  private synchronized void internalDeployApplications( Topology topology, File topoDir ) throws IOException, ZipException, ParserConfigurationException, TransformerException, SAXException {
-    if( topology != null ) {
-      Collection<Application> applications = topology.getApplications();
-      if( applications != null ) {
-        for( Application application : applications ) {
-          List<String> urls = application.getUrls();
-          if( urls == null || urls.isEmpty() ) {
-            internalDeployApplication( topology, topoDir, application, application.getName() );
-          } else {
-            for( String url : urls ) {
-              internalDeployApplication( topology, topoDir, application, url );
-            }
-          }
-        }
-      }
-    }
-  }
-
-  private synchronized void internalDeployApplication( Topology topology, File topoDir, Application application, String url ) throws IOException, ZipException, TransformerException, SAXException, ParserConfigurationException {
-    File appsDir = new File( config.getGatewayApplicationsDir() );
-    File appDir = new File( appsDir, application.getName() );
-    File[] implFiles = appDir.listFiles( new RegexFilenameFilter( "app|app\\..*" ) );
-    if( implFiles == null || implFiles.length == 0 ) {
-      throw new DeploymentException( "Failed to find application in " + appDir );
-    }
-    File implFile = implFiles[0];
-    File warDir = new File( topoDir, Urls.encode( "/" + Urls.trimLeadingAndTrailingSlash( url ) ) );
-    File webInfDir = new File( warDir, "WEB-INF" );
-    explodeWar( implFile, warDir );
-    mergeWebXmlOverrides( webInfDir );
-    createArchiveTempDir( warDir );
-  }
-
-  private synchronized void internalActivateTopology( Topology topology, File topoDir ) throws IOException, ZipException, ParserConfigurationException, TransformerException, SAXException {
-    log.activatingTopology( topology.getName() );
-    File[] files = topoDir.listFiles( new RegexFilenameFilter( "%.*" ) );
-    if( files != null ) {
-      for( File file : files ) {
-        internalActivateArchive( topology, file );
-      }
-    }
-  }
-
-  private synchronized void internalActivateArchive( Topology topology, File warDir ) throws IOException, ZipException, ParserConfigurationException, TransformerException, SAXException {
-    log.activatingTopologyArchive( topology.getName(), warDir.getName() );
-    try {
-      WebAppContext newContext = createWebAppContext( topology, warDir, Urls.decode( warDir.getName() ) );
-      WebAppContext oldContext = deployments.get( newContext.getContextPath() );
-      deployments.put( newContext.getContextPath(), newContext );
-      if( oldContext != null ) {
-        contexts.removeHandler( oldContext );
-      }
-      contexts.addHandler( newContext );
-      if( contexts.isRunning() && !newContext.isRunning() ) {
-          newContext.start();
-      }
-
-    } catch( Exception e ) {
-      auditor.audit( Action.DEPLOY, topology.getName(), ResourceType.TOPOLOGY, ActionOutcome.FAILURE );
-      log.failedToDeployTopology( topology.getName(), e );
-    }
-  }
-
-
-  private synchronized void internalDeactivateTopology( Topology topology ) {
-
-    log.deactivatingTopology( topology.getName() );
-
-    String topoName = topology.getName();
-    String topoPath = "/" + Urls.trimLeadingAndTrailingSlashJoin( config.getGatewayPath(), topoName );
-    String topoPathSlash = topoPath + "/";
-
-    ServiceRegistry sr = getGatewayServices().getService(GatewayServices.SERVICE_REGISTRY_SERVICE);
-    if (sr != null) {
-      sr.removeClusterServices( topoName );
-    }
-
-    // Find all the deployed contexts we need to deactivate.
-    List<WebAppContext> deactivate = new ArrayList<WebAppContext>();
-    if( deployments != null ) {
-      for( WebAppContext app : deployments.values() ) {
-        String appPath = app.getContextPath();
-        if( appPath.equals( topoPath ) || appPath.startsWith( topoPathSlash ) ) {
-          deactivate.add( app );
-        }
-      }
-    }
-
-    // Deactivate the required deployed contexts.
-    for( WebAppContext context : deactivate ) {
-      String contextPath = context.getContextPath();
-      deployments.remove( contextPath );
-      contexts.removeHandler( context );
-      try {
-        context.stop();
-      } catch( Exception e ) {
-        auditor.audit(Action.UNDEPLOY, topology.getName(), ResourceType.TOPOLOGY, ActionOutcome.FAILURE);
-        log.failedToUndeployTopology( topology.getName(), e );
-      }
-    }
-    deactivate.clear();
-
-  }
-
-  // Using an inner class to hide the handleTopologyEvent method from consumers of GatewayServer.
-  private class InternalTopologyListener implements TopologyListener {
-
-    @Override
-    public void handleTopologyEvent( List<TopologyEvent> events ) {
-      synchronized ( GatewayServer.this ) {
-        for( TopologyEvent event : events ) {
-          Topology topology = event.getTopology();
-          File deployDir = calculateAbsoluteDeploymentsDir();
-          if( event.getType().equals( TopologyEvent.Type.DELETED ) ) {
-            handleDeleteDeployment(topology, deployDir);
-          } else {
-            handleCreateDeployment(topology, deployDir);
-          }
-        }
-      }
-    }
-
-    private void handleDeleteDeployment(Topology topology, File deployDir) {
-      log.deletingTopology( topology.getName() );
-      File[] files = deployDir.listFiles( new RegexFilenameFilter( topology.getName() + "\\.(war|topo)\\.[0-9A-Fa-f]+" ) );
-      if( files != null ) {
-        auditor.audit(Action.UNDEPLOY, topology.getName(), ResourceType.TOPOLOGY,
-          ActionOutcome.UNAVAILABLE);
-        internalDeactivateTopology( topology );
-        for( File file : files ) {
-          log.deletingDeployment( file.getAbsolutePath() );
-          FileUtils.deleteQuietly( file );
-        }
-      }
-    }
-
-    private void handleCreateDeployment(Topology topology, File deployDir) {
-      try {
-        File topoDir = calculateDeploymentDir( topology );
-        if( !topoDir.exists() ) {
-          auditor.audit( Action.DEPLOY, topology.getName(), ResourceType.TOPOLOGY, ActionOutcome.UNAVAILABLE );
-
-//          KNOX-564 - Topology should fail to deploy with no providers configured.
-//TODO:APPS:This should only fail if there are services in the topology.
-          if(topology.getProviders().isEmpty()) {
-            throw new DeploymentException("No providers found inside topology.");
-          }
-
-          log.deployingTopology( topology.getName(), topoDir.getAbsolutePath() );
-          internalDeactivateTopology( topology ); // KNOX-152
-
-          EnterpriseArchive ear = DeploymentFactory.createDeployment( config, topology );
-          if( !deployDir.exists() && !deployDir.mkdirs() ) {
-            throw new DeploymentException( "Failed to create topology deployment temporary directory: " + deployDir.getAbsolutePath() );
-          }
-          File tmp = ear.as( ExplodedExporter.class ).exportExploded( deployDir, topoDir.getName() + ".tmp" );
-          if( !tmp.renameTo( topoDir ) ) {
-            FileUtils.deleteQuietly( tmp );
-            throw new DeploymentException( "Failed to create topology deployment directory: " + topoDir.getAbsolutePath() );
-          }
-          internalDeployApplications( topology, topoDir );
-          internalActivateTopology( topology, topoDir );
-          log.deployedTopology( topology.getName());
-        } else {
-          auditor.audit( Action.REDEPLOY, topology.getName(), ResourceType.TOPOLOGY, ActionOutcome.UNAVAILABLE );
-          log.redeployingTopology( topology.getName(), topoDir.getAbsolutePath() );
-          internalActivateTopology( topology, topoDir );
-          log.redeployedTopology( topology.getName() );
-        }
-        cleanupTopologyDeployments( deployDir, topology );
-      } catch( Throwable e ) {
-        auditor.audit( Action.DEPLOY, topology.getName(), ResourceType.TOPOLOGY, ActionOutcome.FAILURE );
-        log.failedToDeployTopology( topology.getName(), e );
-      }
-    }
-
-  }
-
-  private File createArchiveTempDir( File warDir ) {
-    File tempDir = FileUtils.getFile( warDir, "META-INF", "temp" );
-    if( !tempDir.exists() && !tempDir.mkdirs() ) {
-      throw new DeploymentException( "Failed to create archive temporary directory: " + tempDir.getAbsolutePath() );
-    }
-    return tempDir;
-  }
-
-  private static File calculateAbsoluteTopologiesDir( GatewayConfig config ) {
-    File topoDir = new File( config.getGatewayTopologyDir() );
-    topoDir = topoDir.getAbsoluteFile();
-    return topoDir;
-  }
-
-  private static File calculateAbsoluteDeploymentsDir( GatewayConfig config ) {
-    File deployDir = new File( config.getGatewayDeploymentDir() );
-    deployDir = deployDir.getAbsoluteFile();
-    return deployDir;
-  }
-
-  private File calculateAbsoluteTopologiesDir() {
-    return calculateAbsoluteTopologiesDir( config );
-  }
-
-  private File calculateAbsoluteDeploymentsDir() {
-    return calculateAbsoluteDeploymentsDir( config );
-  }
-
-  private File calculateDeploymentDir( Topology topology ) {
-    File dir = new File( calculateAbsoluteDeploymentsDir(), calculateDeploymentName( topology ) );
-    return dir;
-  }
-
-  private String calculateDeploymentExtension( Topology topology ) {
-    return ".topo.";
-  }
-
-  private String calculateDeploymentName( Topology topology ) {
-    String name = topology.getName() + calculateDeploymentExtension( topology ) + Long.toHexString( topology.getTimestamp() );
-    return name;
-  }
-
-  private static void checkAddressAvailability( InetSocketAddress address ) throws IOException {
-    ServerSocket socket = new ServerSocket();
-    socket.bind( address );
-    socket.close();
-  }
-
-  private static class RegexFilenameFilter implements FilenameFilter {
-
-    Pattern pattern;
-
-    RegexFilenameFilter( String regex ) {
-      pattern = Pattern.compile( regex );
-    }
-
-    @Override
-    public boolean accept( File dir, String name ) {
-      return pattern.matcher( name ).matches();
-    }
-  }
-
-  public URI getFrontendUri( WebAppContext context, GatewayConfig config ) {
-    URI frontendUri = null;
-    String frontendStr = config.getFrontendUrl();
-    if( frontendStr != null && !frontendStr.trim().isEmpty() ) {
-      String topoName = (String)context.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE );
-      try {
-        frontendStr = frontendStr.trim();
-        if( frontendStr.endsWith( "/" ) ) {
-          frontendUri = new URI( frontendStr + topoName );
-        } else {
-          frontendUri = new URI( frontendStr + "/" + topoName );
-        }
-      } catch( URISyntaxException e ) {
-        throw new IllegalArgumentException( e );
-      }
-    }
-    return frontendUri;
-  }
-
-  private static class FileModificationTimeDescendingComparator implements Comparator<File>, Serializable {
-    /**
-     * 
-     */
-    private static final long serialVersionUID = -2269785204848916823L;
-
-    @Override
-    public int compare( File left, File right ) {
-      long leftTime = ( left == null ? Long.MIN_VALUE : left.lastModified() );
-      long rightTime = ( right == null ? Long.MIN_VALUE : right.lastModified() );
-      if( leftTime > rightTime ) {
-        return -1;
-      } else if ( leftTime < rightTime ) {
-        return 1;
-      } else {
-        return 0;
-      }
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayServlet.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayServlet.java b/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayServlet.java
deleted file mode 100644
index 79cab09..0000000
--- a/gateway-server/src/main/java/org/apache/hadoop/gateway/GatewayServlet.java
+++ /dev/null
@@ -1,302 +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.hadoop.gateway;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.URISyntaxException;
-import java.util.Enumeration;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.Servlet;
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.hadoop.gateway.audit.api.Action;
-import org.apache.hadoop.gateway.audit.api.ActionOutcome;
-import org.apache.hadoop.gateway.audit.api.AuditService;
-import org.apache.hadoop.gateway.audit.api.AuditServiceFactory;
-import org.apache.hadoop.gateway.audit.api.Auditor;
-import org.apache.hadoop.gateway.audit.api.ResourceType;
-import org.apache.hadoop.gateway.audit.log4j.audit.AuditConstants;
-import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.descriptor.GatewayDescriptor;
-import org.apache.hadoop.gateway.descriptor.GatewayDescriptorFactory;
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.i18n.resources.ResourcesFactory;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.metrics.MetricsService;
-
-public class GatewayServlet implements Servlet, Filter {
-
-  public static final String GATEWAY_DESCRIPTOR_LOCATION_DEFAULT = "gateway.xml";
-  public static final String GATEWAY_DESCRIPTOR_LOCATION_PARAM = "gatewayDescriptorLocation";
-
-  private static final GatewayResources res = ResourcesFactory.get( GatewayResources.class );
-  private static final GatewayMessages LOG = MessagesFactory.get( GatewayMessages.class );
-
-  private static AuditService auditService = AuditServiceFactory.getAuditService();
-  private static Auditor auditor = AuditServiceFactory.getAuditService()
-      .getAuditor( AuditConstants.DEFAULT_AUDITOR_NAME,
-          AuditConstants.KNOX_SERVICE_NAME, AuditConstants.KNOX_COMPONENT_NAME );
-
-  private FilterConfigAdapter filterConfig;
-  private volatile GatewayFilter filter;
-
-  public GatewayServlet( GatewayFilter filter ) {
-    this.filterConfig = null;
-    this.filter = filter;
-  }
-
-  public GatewayServlet() {
-    this( null );
-  }
-
-  public synchronized GatewayFilter getFilter() {
-    return filter;
-  }
-
-  public synchronized void setFilter( GatewayFilter filter ) throws ServletException {
-    Filter prev = filter;
-    if( filterConfig != null ) {
-      filter.init( filterConfig );
-    }
-    this.filter = filter;
-    if( prev != null && filterConfig != null ) {
-      prev.destroy();
-    }
-  }
-
-  @Override
-  public synchronized void init( ServletConfig servletConfig ) throws ServletException {
-    try {
-      if( filter == null ) {
-        filter = createFilter( servletConfig );
-      }
-      filterConfig = new FilterConfigAdapter( servletConfig );
-      if( filter != null ) {
-        filter.init( filterConfig );
-      }
-    } catch( ServletException e ) {
-      LOG.failedToInitializeServletInstace( e );
-      throw e;
-    } catch( RuntimeException e ) {
-      LOG.failedToInitializeServletInstace( e );
-      throw e;
-    }
-  }
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-    try {
-      if( filter == null ) {
-        filter = createFilter( filterConfig );
-      }
-      if( filter != null ) {
-        filter.init( filterConfig );
-      }
-    } catch( ServletException e ) {
-      LOG.failedToInitializeServletInstace( e );
-      throw e;
-    } catch( RuntimeException e ) {
-      LOG.failedToInitializeServletInstace( e );
-      throw e;
-    }
-  }
-
-  @Override
-  public ServletConfig getServletConfig() {
-    return filterConfig.getServletConfig();
-  }
-
-  @Override
-  public void service( ServletRequest servletRequest, ServletResponse servletResponse ) throws ServletException, IOException {
-    try {
-      auditService.createContext();
-      GatewayFilter f = filter;
-      if( f != null ) {
-        try {
-          f.doFilter( servletRequest, servletResponse, null );
-        } catch( IOException e ) {
-          LOG.failedToExecuteFilter( e );
-          throw e;
-        } catch( ServletException e ) {
-          LOG.failedToExecuteFilter( e );
-          throw e;
-        } catch( RuntimeException e ) {
-          LOG.failedToExecuteFilter( e );
-          throw e;
-        }
-      } else {
-        ((HttpServletResponse)servletResponse).setStatus( HttpServletResponse.SC_SERVICE_UNAVAILABLE );
-      }
-      String requestUri = (String)servletRequest.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
-      int status = ((HttpServletResponse)servletResponse).getStatus();
-      auditor.audit( Action.ACCESS, requestUri, ResourceType.URI, ActionOutcome.SUCCESS, res.responseStatus( status ) );
-    } finally {
-      auditService.detachContext();
-    }
-  }
-
-  @Override
-  public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain ) throws IOException, ServletException {
-    try {
-      auditService.createContext();
-      GatewayFilter f = filter;
-      if( f != null ) {
-        try {
-          f.doFilter( servletRequest, servletResponse );
-          //TODO: This should really happen naturally somehow as part of being a filter.  This way will cause problems eventually.
-          chain.doFilter( servletRequest, servletResponse );
-        } catch( IOException e ) {
-          LOG.failedToExecuteFilter( e );
-          throw e;
-        } catch( ServletException e ) {
-          LOG.failedToExecuteFilter( e );
-          throw e;
-        } catch( RuntimeException e ) {
-          LOG.failedToExecuteFilter( e );
-          throw e;
-        }
-      } else {
-        ((HttpServletResponse)servletResponse).setStatus( HttpServletResponse.SC_SERVICE_UNAVAILABLE );
-      }
-      String requestUri = (String)servletRequest.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
-      int status = ((HttpServletResponse)servletResponse).getStatus();
-      auditor.audit( Action.ACCESS, requestUri, ResourceType.URI, ActionOutcome.SUCCESS, res.responseStatus( status ) );
-    } finally {
-      auditService.detachContext();
-    }
-  }
-
-  @Override
-  public String getServletInfo() {
-    return res.gatewayServletInfo();
-  }
-
-  @Override
-  public synchronized void destroy() {
-    if( filter != null ) {
-      filter.destroy();
-    }
-    filter = null;
-  }
-
-  private static GatewayFilter createFilter( InputStream stream, ServletContext servletContext ) throws ServletException {
-    try {
-      GatewayFilter filter = null;
-      if( stream != null ) {
-        try {
-          GatewayDescriptor descriptor = GatewayDescriptorFactory.load( "xml", new InputStreamReader( stream ) );
-          filter = GatewayFactory.create( descriptor );
-        } finally {
-          stream.close();
-        }
-      }
-      GatewayConfig gatewayConfig = (GatewayConfig) servletContext.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
-      if (gatewayConfig.isMetricsEnabled()) {
-        GatewayServices gatewayServices = (GatewayServices) servletContext.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
-        MetricsService metricsService = gatewayServices.getService(GatewayServices.METRICS_SERVICE);
-        if (metricsService != null) {
-          GatewayFilter instrumentedFilter = metricsService.getInstrumented(filter);
-          if (instrumentedFilter != null) {
-            filter = instrumentedFilter;
-          }
-        }
-      }
-      return filter;
-    } catch( IOException e ) {
-      throw new ServletException( e );
-    } catch( URISyntaxException e ) {
-      throw new ServletException( e );
-    }
-  }
-
-  private static GatewayFilter createFilter( FilterConfig filterConfig ) throws ServletException {
-    GatewayFilter filter;
-    InputStream stream;
-    String location = filterConfig.getInitParameter( GATEWAY_DESCRIPTOR_LOCATION_PARAM );
-    if( location != null ) {
-      stream = filterConfig.getServletContext().getResourceAsStream( location );
-      if( stream == null ) {
-        stream = filterConfig.getServletContext().getResourceAsStream( "/WEB-INF/" + location );
-      }
-    } else {
-      stream = filterConfig.getServletContext().getResourceAsStream( GATEWAY_DESCRIPTOR_LOCATION_DEFAULT );
-    }
-    filter = createFilter( stream, filterConfig.getServletContext());
-    return filter;
-  }
-
-  private static GatewayFilter createFilter( ServletConfig servletConfig ) throws ServletException {
-    GatewayFilter filter;
-    InputStream stream;
-    String location = servletConfig.getInitParameter( GATEWAY_DESCRIPTOR_LOCATION_PARAM );
-    if( location != null ) {
-      stream = servletConfig.getServletContext().getResourceAsStream( location );
-      if( stream == null ) {
-        stream = servletConfig.getServletContext().getResourceAsStream( "/WEB-INF/" + location );
-      }
-    } else {
-      stream = servletConfig.getServletContext().getResourceAsStream( GATEWAY_DESCRIPTOR_LOCATION_DEFAULT );
-    }
-    filter = createFilter( stream, servletConfig.getServletContext());
-    return filter;
-  }
-
-  private static class FilterConfigAdapter implements FilterConfig {
-
-    private ServletConfig config;
-
-    private FilterConfigAdapter( ServletConfig config ) {
-      this.config = config;
-    }
-
-    private ServletConfig getServletConfig() {
-      return config;
-    }
-
-    @Override
-    public String getFilterName() {
-      return config.getServletName();
-    }
-
-    @Override
-    public ServletContext getServletContext() {
-      return config.getServletContext();
-    }
-
-    @Override
-    public String getInitParameter( String name ) {
-      return config.getInitParameter( name );
-    }
-
-    @Override
-    public Enumeration<String> getInitParameterNames() {
-      return config.getInitParameterNames();
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-server/src/main/java/org/apache/hadoop/gateway/config/impl/GatewayConfigImpl.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/hadoop/gateway/config/impl/GatewayConfigImpl.java b/gateway-server/src/main/java/org/apache/hadoop/gateway/config/impl/GatewayConfigImpl.java
deleted file mode 100644
index 3b7d19e..0000000
--- a/gateway-server/src/main/java/org/apache/hadoop/gateway/config/impl/GatewayConfigImpl.java
+++ /dev/null
@@ -1,915 +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.hadoop.gateway.config.impl;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.gateway.GatewayMessages;
-import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.joda.time.Period;
-import org.joda.time.format.PeriodFormatter;
-import org.joda.time.format.PeriodFormatterBuilder;
-
-import java.io.File;
-import java.net.InetSocketAddress;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * The configuration for the Gateway.
- *
- * The Gateway configuration variables are described in gateway-default.xml
- *
- * The Gateway specific configuration is split into two layers:
- *
- * 1. gateway-default.xml - All the configuration variables that the
- *    Gateway needs.  These are the defaults that ship with the app
- *    and should only be changed by the app developers.
- *
- * 2. gateway-site.xml - The (possibly empty) configuration that the
- *    system administrator can set variables for their Hadoop cluster.
- *
- * To find the gateway configuration files the following process is used.
- * First, if the GATEWAY_HOME system property contains a valid directory name,
- * an attempt will be made to read the configuration files from that directory.
- * Second, if the GATEWAY_HOME environment variable contains a valid directory name,
- * an attempt will be made to read the configuration files from that directory.
- * Third, an attempt will be made to load the configuration files from the directory
- * specified via the "user.dir" system property.
- * Fourth, an attempt will be made to load the configuration files from the classpath.
- * Last, defaults will be used for all values will be used.
- *
- * If GATEWAY_HOME isn't set via either the system property or environment variable then
- * a value for this will be defaulted.  The default selected will be the directory that
- * contained the last loaded configuration file that was not contained in a JAR.  If
- * no such configuration file is loaded the value of the "user.dir" system property will be used
- * as the value of GATEWAY_HOME.  This is important to consider for any relative file names as they
- * will be resolved relative to the value of GATEWAY_HOME.  One such relative value is the
- * name of the directory containing cluster topologies.  This value default to "clusters".
- */
-public class GatewayConfigImpl extends Configuration implements GatewayConfig {
-
-  private static final String GATEWAY_DEFAULT_TOPOLOGY_NAME_PARAM = "default.app.topology.name";
-  private static final String GATEWAY_DEFAULT_TOPOLOGY_NAME = null;
-
-  private static final GatewayMessages log = MessagesFactory.get( GatewayMessages.class );
-
-  private static final String GATEWAY_CONFIG_DIR_PREFIX = "conf";
-
-  private static final String GATEWAY_CONFIG_FILE_PREFIX = "gateway";
-
-  private static final String DEFAULT_STACKS_SERVICES_DIR = "services";
-
-  private static final String DEFAULT_APPLICATIONS_DIR = "applications";
-
-  public static final String[] GATEWAY_CONFIG_FILENAMES = {
-      GATEWAY_CONFIG_DIR_PREFIX + "/" + GATEWAY_CONFIG_FILE_PREFIX + "-default.xml",
-      GATEWAY_CONFIG_DIR_PREFIX + "/" + GATEWAY_CONFIG_FILE_PREFIX + "-site.xml"
-  };
-
-//  private static final String[] HADOOP_CONF_FILENAMES = {
-//      "core-default.xml",
-//      "core-site.xml"
-////      "hdfs-default.xml",
-////      "hdfs-site.xml",
-////      "mapred-default.xml",
-////      "mapred-site.xml"
-//  };
-
-//  private static final String[] HADOOP_PREFIX_VARS = {
-//      "HADOOP_PREFIX",
-//      "HADOOP_HOME"
-//  };
-
-  public static final String HTTP_HOST = GATEWAY_CONFIG_FILE_PREFIX + ".host";
-  public static final String HTTP_PORT = GATEWAY_CONFIG_FILE_PREFIX + ".port";
-  public static final String HTTP_PATH = GATEWAY_CONFIG_FILE_PREFIX + ".path";
-  public static final String DEPLOYMENT_DIR = GATEWAY_CONFIG_FILE_PREFIX + ".deployment.dir";
-  public static final String SECURITY_DIR = GATEWAY_CONFIG_FILE_PREFIX + ".security.dir";
-  public static final String DATA_DIR = GATEWAY_CONFIG_FILE_PREFIX + ".data.dir";
-  public static final String STACKS_SERVICES_DIR = GATEWAY_CONFIG_FILE_PREFIX + ".services.dir";
-  public static final String GLOBAL_RULES_SERVICES = GATEWAY_CONFIG_FILE_PREFIX + ".global.rules.services";
-  public static final String APPLICATIONS_DIR = GATEWAY_CONFIG_FILE_PREFIX + ".applications.dir";
-  public static final String HADOOP_CONF_DIR = GATEWAY_CONFIG_FILE_PREFIX + ".hadoop.conf.dir";
-  public static final String FRONTEND_URL = GATEWAY_CONFIG_FILE_PREFIX + ".frontend.url";
-  private static final String TRUST_ALL_CERTS = GATEWAY_CONFIG_FILE_PREFIX + ".trust.all.certs";
-  private static final String CLIENT_AUTH_NEEDED = GATEWAY_CONFIG_FILE_PREFIX + ".client.auth.needed";
-  private static final String TRUSTSTORE_PATH = GATEWAY_CONFIG_FILE_PREFIX + ".truststore.path";
-  private static final String TRUSTSTORE_TYPE = GATEWAY_CONFIG_FILE_PREFIX + ".truststore.type";
-  private static final String KEYSTORE_TYPE = GATEWAY_CONFIG_FILE_PREFIX + ".keystore.type";
-  private static final String XFORWARDED_ENABLED = GATEWAY_CONFIG_FILE_PREFIX + ".xforwarded.enabled";
-  private static final String EPHEMERAL_DH_KEY_SIZE = GATEWAY_CONFIG_FILE_PREFIX + ".jdk.tls.ephemeralDHKeySize";
-  private static final String HTTP_CLIENT_MAX_CONNECTION = GATEWAY_CONFIG_FILE_PREFIX + ".httpclient.maxConnections";
-  private static final String HTTP_CLIENT_CONNECTION_TIMEOUT = GATEWAY_CONFIG_FILE_PREFIX + ".httpclient.connectionTimeout";
-  private static final String HTTP_CLIENT_SOCKET_TIMEOUT = GATEWAY_CONFIG_FILE_PREFIX + ".httpclient.socketTimeout";
-  private static final String THREAD_POOL_MAX = GATEWAY_CONFIG_FILE_PREFIX + ".threadpool.max";
-  public static final String HTTP_SERVER_REQUEST_BUFFER = GATEWAY_CONFIG_FILE_PREFIX + ".httpserver.requestBuffer";
-  public static final String HTTP_SERVER_REQUEST_HEADER_BUFFER = GATEWAY_CONFIG_FILE_PREFIX + ".httpserver.requestHeaderBuffer";
-  public static final String HTTP_SERVER_RESPONSE_BUFFER = GATEWAY_CONFIG_FILE_PREFIX + ".httpserver.responseBuffer";
-  public static final String HTTP_SERVER_RESPONSE_HEADER_BUFFER = GATEWAY_CONFIG_FILE_PREFIX + ".httpserver.responseHeaderBuffer";
-  public static final String DEPLOYMENTS_BACKUP_VERSION_LIMIT = GATEWAY_CONFIG_FILE_PREFIX + ".deployment.backup.versionLimit";
-  public static final String DEPLOYMENTS_BACKUP_AGE_LIMIT = GATEWAY_CONFIG_FILE_PREFIX + ".deployment.backup.ageLimit";
-  public static final String METRICS_ENABLED = GATEWAY_CONFIG_FILE_PREFIX + ".metrics.enabled";
-  public static final String JMX_METRICS_REPORTING_ENABLED = GATEWAY_CONFIG_FILE_PREFIX + ".jmx.metrics.reporting.enabled";
-  public static final String GRAPHITE_METRICS_REPORTING_ENABLED = GATEWAY_CONFIG_FILE_PREFIX + ".graphite.metrics.reporting.enabled";
-  public static final String GRAPHITE_METRICS_REPORTING_HOST = GATEWAY_CONFIG_FILE_PREFIX + ".graphite.metrics.reporting.host";
-  public static final String GRAPHITE_METRICS_REPORTING_PORT = GATEWAY_CONFIG_FILE_PREFIX + ".graphite.metrics.reporting.port";
-  public static final String GRAPHITE_METRICS_REPORTING_FREQUENCY = GATEWAY_CONFIG_FILE_PREFIX + ".graphite.metrics.reporting.frequency";
-  public static final String GATEWAY_IDLE_TIMEOUT = GATEWAY_CONFIG_FILE_PREFIX + ".idle.timeout";
-  public static final String REMOTE_IP_HEADER_NAME = GATEWAY_CONFIG_FILE_PREFIX + ".remote.ip.header.name";
-
-  /* @since 0.10 Websocket config variables */
-  public static final String WEBSOCKET_FEATURE_ENABLED = GATEWAY_CONFIG_FILE_PREFIX + ".websocket.feature.enabled";
-  public static final String WEBSOCKET_MAX_TEXT_MESSAGE_SIZE = GATEWAY_CONFIG_FILE_PREFIX + ".websocket.max.text.size";
-  public static final String WEBSOCKET_MAX_BINARY_MESSAGE_SIZE = GATEWAY_CONFIG_FILE_PREFIX + ".websocket.max.binary.size";
-  public static final String WEBSOCKET_MAX_TEXT_MESSAGE_BUFFER_SIZE = GATEWAY_CONFIG_FILE_PREFIX + ".websocket.max.text.buffer.size";
-  public static final String WEBSOCKET_MAX_BINARY_MESSAGE_BUFFER_SIZE = GATEWAY_CONFIG_FILE_PREFIX + ".websocket.max.binary.buffer.size";
-  public static final String WEBSOCKET_INPUT_BUFFER_SIZE = GATEWAY_CONFIG_FILE_PREFIX + ".websocket.input.buffer.size";
-  public static final String WEBSOCKET_ASYNC_WRITE_TIMEOUT = GATEWAY_CONFIG_FILE_PREFIX + ".websocket.async.write.timeout";
-  public static final String WEBSOCKET_IDLE_TIMEOUT = GATEWAY_CONFIG_FILE_PREFIX + ".websocket.idle.timeout";
-
-  /**
-   * Properties for for gateway port mapping feature
-   */
-  public static final String GATEWAY_PORT_MAPPING_PREFIX = GATEWAY_CONFIG_FILE_PREFIX + ".port.mapping.";
-  public static final String GATEWAY_PORT_MAPPING_REGEX = GATEWAY_CONFIG_FILE_PREFIX + "\\.port\\.mapping\\..*";
-  public static final String GATEWAY_PORT_MAPPING_ENABLED = GATEWAY_PORT_MAPPING_PREFIX + "enabled";
-
-  /**
-   * Comma seperated list of MIME Types to be compressed by Knox on the way out.
-   *
-   * @since 0.12
-   */
-  public static final String MIME_TYPES_TO_COMPRESS = GATEWAY_CONFIG_FILE_PREFIX
-      + ".gzip.compress.mime.types";
-
-  // These config property names are not inline with the convention of using the
-  // GATEWAY_CONFIG_FILE_PREFIX as is done by those above. These are left for
-  // backward compatibility. 
-  // LET'S NOT CONTINUE THIS PATTERN BUT LEAVE THEM FOR NOW.
-  private static final String SSL_ENABLED = "ssl.enabled";
-  private static final String SSL_EXCLUDE_PROTOCOLS = "ssl.exclude.protocols";
-  private static final String SSL_INCLUDE_CIPHERS = "ssl.include.ciphers";
-  private static final String SSL_EXCLUDE_CIPHERS = "ssl.exclude.ciphers";
-  // END BACKWARD COMPATIBLE BLOCK
-  
-  public static final String DEFAULT_HTTP_PORT = "8888";
-  public static final String DEFAULT_HTTP_PATH = "gateway";
-  public static final String DEFAULT_DEPLOYMENT_DIR = "deployments";
-  public static final String DEFAULT_SECURITY_DIR = "security";
-  public static final String DEFAULT_DATA_DIR = "data";
-
-  /* Websocket defaults */
-  public static final boolean DEFAULT_WEBSOCKET_FEATURE_ENABLED = false;
-  public static final int DEFAULT_WEBSOCKET_MAX_TEXT_MESSAGE_SIZE = Integer.MAX_VALUE;;
-  public static final int DEFAULT_WEBSOCKET_MAX_BINARY_MESSAGE_SIZE = Integer.MAX_VALUE;;
-  public static final int DEFAULT_WEBSOCKET_MAX_TEXT_MESSAGE_BUFFER_SIZE = 32768;
-  public static final int DEFAULT_WEBSOCKET_MAX_BINARY_MESSAGE_BUFFER_SIZE = 32768;
-  public static final int DEFAULT_WEBSOCKET_INPUT_BUFFER_SIZE = 4096;
-  public static final int DEFAULT_WEBSOCKET_ASYNC_WRITE_TIMEOUT = 60000;
-  public static final int DEFAULT_WEBSOCKET_IDLE_TIMEOUT = 300000;
-
-  public static final boolean DEFAULT_GATEWAY_PORT_MAPPING_ENABLED = true;
-
-  /**
-   * Default list of MIME Type to be compressed.
-   * @since 0.12
-   */
-  public static final String DEFAULT_MIME_TYPES_TO_COMPRESS = "text/html, text/plain, text/xml, text/css, "
-      + "application/javascript, application/x-javascript, text/javascript";
-
-  public static final String COOKIE_SCOPING_ENABLED = GATEWAY_CONFIG_FILE_PREFIX + ".scope.cookies.feature.enabled";
-  public static final boolean DEFAULT_COOKIE_SCOPING_FEATURE_ENABLED = false;
-  private static final String CRYPTO_ALGORITHM = GATEWAY_CONFIG_FILE_PREFIX + ".crypto.algorithm";
-  private static final String CRYPTO_PBE_ALGORITHM = GATEWAY_CONFIG_FILE_PREFIX + ".crypto.pbe.algorithm";
-  private static final String CRYPTO_TRANSFORMATION = GATEWAY_CONFIG_FILE_PREFIX + ".crypto.transformation";
-  private static final String CRYPTO_SALTSIZE = GATEWAY_CONFIG_FILE_PREFIX + ".crypto.salt.size";
-  private static final String CRYPTO_ITERATION_COUNT = GATEWAY_CONFIG_FILE_PREFIX + ".crypto.iteration.count";
-  private static final String CRYPTO_KEY_LENGTH = GATEWAY_CONFIG_FILE_PREFIX + ".crypto.key.length";
-  public static final String SERVER_HEADER_ENABLED = GATEWAY_CONFIG_FILE_PREFIX + ".server.header.enabled";
-
-  private static List<String> DEFAULT_GLOBAL_RULES_SERVICES;
-
-
-  public GatewayConfigImpl() {
-    init();
-  }
-
-  private String getVar( String variableName, String defaultValue ) {
-    String value = get( variableName );
-    if( value == null ) {
-      value = System.getProperty( variableName );
-    }
-    if( value == null ) {
-      value = System.getenv( variableName );
-    }
-    if( value == null ) {
-      value = defaultValue;
-    }
-    return value;
-  }
-
-  private String getGatewayHomeDir() {
-    String home = get(
-        GATEWAY_HOME_VAR,
-        System.getProperty(
-            GATEWAY_HOME_VAR,
-            System.getenv( GATEWAY_HOME_VAR ) ) );
-    return home;
-  }
-
-  private void setGatewayHomeDir( String dir ) {
-    set( GATEWAY_HOME_VAR, dir );
-  }
-
-  @Override
-  public String getGatewayConfDir() {
-    String value = getVar( GATEWAY_CONF_HOME_VAR, getGatewayHomeDir() + File.separator + "conf"  );
-    return value;
-  }
-
-  @Override
-  public String getGatewayDataDir() {
-    String systemValue =
-        System.getProperty(GATEWAY_DATA_HOME_VAR, System.getenv(GATEWAY_DATA_HOME_VAR));
-    String dataDir = null;
-    if (systemValue != null) {
-      dataDir = systemValue;
-    } else {
-      dataDir = get(DATA_DIR, getGatewayHomeDir() + File.separator + DEFAULT_DATA_DIR);
-    }
-    return dataDir;
-  }
-
-  @Override
-  public String getGatewayServicesDir() {
-    return get(STACKS_SERVICES_DIR, getGatewayDataDir() + File.separator + DEFAULT_STACKS_SERVICES_DIR);
-  }
-
-  @Override
-  public String getGatewayApplicationsDir() {
-    return get(APPLICATIONS_DIR, getGatewayDataDir() + File.separator + DEFAULT_APPLICATIONS_DIR);
-  }
-
-  @Override
-  public String getHadoopConfDir() {
-    return get( HADOOP_CONF_DIR );
-  }
-
-  private void init() {
-    // Load environment variables.
-    for( Map.Entry<String, String> e : System.getenv().entrySet() ) {
-      set( "env." + e.getKey(), e.getValue() );
-    }
-    // Load system properties.
-    for( Map.Entry<Object, Object> p : System.getProperties().entrySet() ) {
-      set( "sys." + p.getKey().toString(), p.getValue().toString() );
-    }
-
-    URL lastFileUrl = null;
-    for( String fileName : GATEWAY_CONFIG_FILENAMES ) {
-      lastFileUrl = loadConfig( fileName, lastFileUrl );
-    }
-    //set default services list
-    setDefaultGlobalRulesServices();
-
-    initGatewayHomeDir( lastFileUrl );
-
-    // log whether the scoping cookies to the gateway.path feature is enabled
-    log.cookieScopingFeatureEnabled(isCookieScopingToPathEnabled());
-  }
-
-  private void setDefaultGlobalRulesServices() {
-    DEFAULT_GLOBAL_RULES_SERVICES = new ArrayList<>();
-    DEFAULT_GLOBAL_RULES_SERVICES.add("NAMENODE");
-    DEFAULT_GLOBAL_RULES_SERVICES.add("JOBTRACKER");
-    DEFAULT_GLOBAL_RULES_SERVICES.add("WEBHDFS");
-    DEFAULT_GLOBAL_RULES_SERVICES.add("WEBHCAT");
-    DEFAULT_GLOBAL_RULES_SERVICES.add("OOZIE");
-    DEFAULT_GLOBAL_RULES_SERVICES.add("WEBHBASE");
-    DEFAULT_GLOBAL_RULES_SERVICES.add("HIVE");
-    DEFAULT_GLOBAL_RULES_SERVICES.add("RESOURCEMANAGER");
-  }
-
-  private void initGatewayHomeDir( URL lastFileUrl ) {
-    String home = System.getProperty( GATEWAY_HOME_VAR );
-    if( home != null ) {
-      set( GATEWAY_HOME_VAR, home );
-      log.settingGatewayHomeDir( "system property", home );
-      return;
-    }
-    home = System.getenv( GATEWAY_HOME_VAR );
-    if( home != null ) {
-      set( GATEWAY_HOME_VAR, home );
-      log.settingGatewayHomeDir( "environment variable", home );
-      return;
-    }
-    if( lastFileUrl != null ) {
-      File file = new File( lastFileUrl.getFile() ).getAbsoluteFile();
-      File dir = file.getParentFile().getParentFile(); // Move up two levels to get to parent of conf.
-      if( dir.exists() && dir.canRead() )
-        home = dir.getAbsolutePath();
-      set( GATEWAY_HOME_VAR, home );
-      log.settingGatewayHomeDir( "configuration file location", home );
-      return;
-    }
-    home = System.getProperty( "user.dir" );
-    if( home != null ) {
-      set( GATEWAY_HOME_VAR, home );
-      log.settingGatewayHomeDir( "user.dir system property", home );
-      return;
-    }
-  }
-
-  // 1. GATEWAY_HOME system property
-  // 2. GATEWAY_HOME environment variable
-  // 3. user.dir system property
-  // 4. class path
-  private URL loadConfig( String fileName, URL lastFileUrl ) {
-    lastFileUrl = loadConfigFile( System.getProperty( GATEWAY_HOME_VAR ), fileName );
-    if( lastFileUrl == null ) {
-      lastFileUrl = loadConfigFile( System.getenv( GATEWAY_HOME_VAR ), fileName );
-    }
-    if( lastFileUrl == null ) {
-      lastFileUrl = loadConfigFile( System.getProperty( "user.dir" ), fileName );
-    }
-    if( lastFileUrl == null ) {
-      lastFileUrl = loadConfigResource( fileName );
-    }
-    if( lastFileUrl != null && !"file".equals( lastFileUrl.getProtocol() ) ) {
-      lastFileUrl = null;
-    }
-    return lastFileUrl;
-  }
-
-  private URL loadConfigFile( String dir, String file ) {
-    URL url = null;
-    if( dir != null ) {
-      File f = new File( dir, file );
-      if( f.exists() ) {
-        String path = f.getAbsolutePath();
-        try {
-          url = f.toURI().toURL();
-          addResource( new Path( path ) );
-          log.loadingConfigurationFile( path );
-        } catch ( MalformedURLException e ) {
-          log.failedToLoadConfig( path, e );
-        }
-      }
-    }
-    return url;
-  }
-
-  private URL loadConfigResource( String file ) {
-    URL url = getResource( file );
-    if( url != null ) {
-      log.loadingConfigurationResource( url.toExternalForm() );
-      addResource( url );
-    }
-    return url;
-  }
-
-  @Override
-  public String getGatewayHost() {
-    String host = get( HTTP_HOST, "0.0.0.0" );
-    return host;
-  }
-
-  @Override
-  public int getGatewayPort() {
-    return Integer.parseInt( get( HTTP_PORT, DEFAULT_HTTP_PORT ) );
-  }
-
-  @Override
-  public String getGatewayPath() {
-    return get( HTTP_PATH, DEFAULT_HTTP_PATH );
-  }
-
-  @Override
-  public String getGatewayTopologyDir() {
-    return getGatewayConfDir() + File.separator + "topologies";
-  }
-
-  @Override
-  public String getGatewayDeploymentDir() {
-    return get(DEPLOYMENT_DIR, getGatewayDataDir() + File.separator + DEFAULT_DEPLOYMENT_DIR);
-  }
-
-  @Override
-  public String getGatewaySecurityDir() {
-    return get(SECURITY_DIR, getGatewayDataDir() + File.separator + DEFAULT_SECURITY_DIR);
-  }
-
-  @Override
-  public InetSocketAddress getGatewayAddress() throws UnknownHostException {
-    String host = getGatewayHost();
-    int port = getGatewayPort();
-    InetSocketAddress address = new InetSocketAddress( host, port );
-    return address;
-  }
-
-  @Override
-  public boolean isSSLEnabled() {
-    String enabled = get( SSL_ENABLED, "true" );
-    
-    return "true".equals(enabled);
-  }
-
-  @Override
-  public boolean isHadoopKerberosSecured() {
-    String hadoopKerberosSecured = get( HADOOP_KERBEROS_SECURED, "false" );
-    return "true".equals(hadoopKerberosSecured);
-  }
-
-  @Override
-  public String getKerberosConfig() {
-    return get( KRB5_CONFIG ) ;
-  }
-
-  @Override
-  public boolean isKerberosDebugEnabled() {
-    String kerberosDebugEnabled = get( KRB5_DEBUG, "false" );
-    return "true".equals(kerberosDebugEnabled);
-  }
-  
-  @Override
-  public String getKerberosLoginConfig() {
-    return get( KRB5_LOGIN_CONFIG );
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#getDefaultTopologyName()
-   */
-  @Override
-  public String getDefaultTopologyName() {
-    String name = get(GATEWAY_DEFAULT_TOPOLOGY_NAME_PARAM);
-    return name != null ? name : GATEWAY_DEFAULT_TOPOLOGY_NAME;
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#getDefaultAppRedirectPath()
-   */
-  @Override
-  public String getDefaultAppRedirectPath() {
-    String defTopo = getDefaultTopologyName();
-    if( defTopo == null ) {
-      return null;
-    } else {
-      return "/" + getGatewayPath() + "/" + defTopo;
-    }
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#getFrontendUrl()
-   */
-  @Override
-  public String getFrontendUrl() {
-    String url = get( FRONTEND_URL, null );
-    return url;
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#getExcludedSSLProtocols()
-   */
-  @Override
-  public List<String> getExcludedSSLProtocols() {
-    List<String> protocols = null;
-    String value = get(SSL_EXCLUDE_PROTOCOLS);
-    if (!"none".equals(value)) {
-      protocols = Arrays.asList(value.split("\\s*,\\s*"));
-    }
-    return protocols;
-  }
-
-  @Override
-  public List<String> getIncludedSSLCiphers() {
-    List<String> list = null;
-    String value = get(SSL_INCLUDE_CIPHERS);
-    if (value != null && !value.isEmpty() && !"none".equalsIgnoreCase(value.trim())) {
-      list = Arrays.asList(value.trim().split("\\s*,\\s*"));
-    }
-    return list;
-  }
-
-  @Override
-  public List<String> getExcludedSSLCiphers() {
-    List<String> list = null;
-    String value = get(SSL_EXCLUDE_CIPHERS);
-    if (value != null && !value.isEmpty() && !"none".equalsIgnoreCase(value.trim())) {
-      list = Arrays.asList(value.trim().split("\\s*,\\s*"));
-    }
-    return list;
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#isClientAuthNeeded()
-   */
-  @Override
-  public boolean isClientAuthNeeded() {
-    String clientAuthNeeded = get( CLIENT_AUTH_NEEDED, "false" );
-    return "true".equals(clientAuthNeeded);
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#getTruststorePath()
-   */
-  @Override
-  public String getTruststorePath() {
-    return get( TRUSTSTORE_PATH, null);
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#getTrustAllCerts()
-   */
-  @Override
-  public boolean getTrustAllCerts() {
-    String trustAllCerts = get( TRUST_ALL_CERTS, "false" );
-    return "true".equals(trustAllCerts);
-  }
-  
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#getTruststorePath()
-   */
-  @Override
-  public String getTruststoreType() {
-    return get( TRUSTSTORE_TYPE, "JKS");
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#getTruststorePath()
-   */
-  @Override
-  public String getKeystoreType() {
-    return get( KEYSTORE_TYPE, "JKS");
-  }
-
-  @Override
-  public boolean isXForwardedEnabled() {
-    String xForwardedEnabled = get( XFORWARDED_ENABLED, "true" );
-    return "true".equals(xForwardedEnabled);
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#getEphemeralDHKeySize()
-   */
-  @Override
-  public String getEphemeralDHKeySize() {
-    return get( EPHEMERAL_DH_KEY_SIZE, "2048");
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#getHttpClientMaxConnections()
-   */
-  @Override
-  public int getHttpClientMaxConnections() {
-    return getInt( HTTP_CLIENT_MAX_CONNECTION, 32 );
-  }
-
-  @Override
-  public int getHttpClientConnectionTimeout() {
-    int t = -1;
-    String s = get( HTTP_CLIENT_CONNECTION_TIMEOUT, null );
-    if ( s != null ) {
-      try {
-        t = (int)parseNetworkTimeout( s );
-      } catch ( Exception e ) {
-        // Ignore it and use the default.
-      }
-    }
-    return t;
-  }
-
-  @Override
-  public int getHttpClientSocketTimeout() {
-    int t = -1;
-    String s = get( HTTP_CLIENT_SOCKET_TIMEOUT, null );
-    if ( s != null ) {
-      try {
-        t = (int)parseNetworkTimeout( s );
-      } catch ( Exception e ) {
-        // Ignore it and use the default.
-      }
-    }
-    return t;
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#getThreadPoolMax()
-   */
-  @Override
-  public int getThreadPoolMax() {
-    int i = getInt( THREAD_POOL_MAX, 254 );
-    // Testing has shown that a value lower than 5 prevents Jetty from servicing request.
-    if( i < 5 ) {
-      i = 5;
-    }
-    return i;
-  }
-
-  @Override
-  public int getHttpServerRequestBuffer() {
-    int i = getInt( HTTP_SERVER_REQUEST_BUFFER, 16 * 1024 );
-    return i;
-  }
-
-  @Override
-  public int getHttpServerRequestHeaderBuffer() {
-    int i = getInt( HTTP_SERVER_REQUEST_HEADER_BUFFER, 8 * 1024 );
-    return i;
-  }
-
-  @Override
-  public int getHttpServerResponseBuffer() {
-    int i = getInt( HTTP_SERVER_RESPONSE_BUFFER, 32 * 1024 );
-    return i;
-  }
-
-  @Override
-  public int getHttpServerResponseHeaderBuffer() {
-    int i = getInt( HTTP_SERVER_RESPONSE_HEADER_BUFFER, 8 * 1024 );
-    return i;
-  }
-
-  @Override
-  public int getGatewayDeploymentsBackupVersionLimit() {
-    int i = getInt( DEPLOYMENTS_BACKUP_VERSION_LIMIT, 5 );
-    if( i < 0 ) {
-      i = -1;
-    }
-    return i;
-  }
-
-  @Override
-  public long getGatewayIdleTimeout() {
-    return getLong(GATEWAY_IDLE_TIMEOUT, 300000l);
-  }
-
-  @Override
-  public long getGatewayDeploymentsBackupAgeLimit() {
-    PeriodFormatter f = new PeriodFormatterBuilder().appendDays().toFormatter();
-    String s = get( DEPLOYMENTS_BACKUP_AGE_LIMIT, "-1" );
-    long d;
-    try {
-      Period p = Period.parse( s, f );
-      d = p.toStandardDuration().getMillis();
-      if( d < 0 ) {
-        d = -1;
-      }
-    } catch( Exception e ) {
-      d = -1;
-    }
-    return d;
-  }
-
-  @Override
-  public String getSigningKeystoreName() {
-    return get(SIGNING_KEYSTORE_NAME);
-  }
-
-  @Override
-  public String getSigningKeyAlias() {
-    return get(SIGNING_KEY_ALIAS);
-  }
-
-  @Override
-  public List<String> getGlobalRulesServices() {
-    String value = get( GLOBAL_RULES_SERVICES );
-    if ( value != null && !value.isEmpty() && !"none".equalsIgnoreCase(value.trim()) ) {
-      return Arrays.asList( value.trim().split("\\s*,\\s*") );
-    }
-    return DEFAULT_GLOBAL_RULES_SERVICES;
-  }
-
-  @Override
-  public boolean isMetricsEnabled() {
-    String metricsEnabled = get( METRICS_ENABLED, "false" );
-    return "true".equals(metricsEnabled);
-  }
-
-  @Override
-  public boolean isJmxMetricsReportingEnabled() {
-    String enabled = get( JMX_METRICS_REPORTING_ENABLED, "false" );
-    return "true".equals(enabled);
-  }
-
-  @Override
-  public boolean isGraphiteMetricsReportingEnabled() {
-    String enabled = get( GRAPHITE_METRICS_REPORTING_ENABLED, "false" );
-    return "true".equals(enabled);
-  }
-
-  @Override
-  public String getGraphiteHost() {
-    String host = get( GRAPHITE_METRICS_REPORTING_HOST, "localhost" );
-    return host;
-  }
-
-  @Override
-  public int getGraphitePort() {
-    int i = getInt( GRAPHITE_METRICS_REPORTING_PORT, 32772 );
-    return i;
-  }
-
-  @Override
-  public int getGraphiteReportingFrequency() {
-    int i = getInt( GRAPHITE_METRICS_REPORTING_FREQUENCY, 1 );
-    return i;
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#isWebsocketEnabled()
-   */
-  @Override
-  public boolean isWebsocketEnabled() {
-    final String result = get( WEBSOCKET_FEATURE_ENABLED, Boolean.toString(DEFAULT_WEBSOCKET_FEATURE_ENABLED));
-    return Boolean.parseBoolean(result);
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#websocketMaxTextMessageSize()
-   */
-  @Override
-  public int getWebsocketMaxTextMessageSize() {
-    return getInt( WEBSOCKET_MAX_TEXT_MESSAGE_SIZE, DEFAULT_WEBSOCKET_MAX_TEXT_MESSAGE_SIZE);
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#websocketMaxBinaryMessageSize()
-   */
-  @Override
-  public int getWebsocketMaxBinaryMessageSize() {
-    return getInt( WEBSOCKET_MAX_BINARY_MESSAGE_SIZE, DEFAULT_WEBSOCKET_MAX_BINARY_MESSAGE_SIZE);
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#websocketMaxTextMessageBufferSize()
-   */
-  @Override
-  public int getWebsocketMaxTextMessageBufferSize() {
-    return getInt( WEBSOCKET_MAX_TEXT_MESSAGE_BUFFER_SIZE, DEFAULT_WEBSOCKET_MAX_TEXT_MESSAGE_BUFFER_SIZE);
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#websocketMaxBinaryMessageBufferSize()
-   */
-  @Override
-  public int getWebsocketMaxBinaryMessageBufferSize() {
-    return getInt( WEBSOCKET_MAX_BINARY_MESSAGE_BUFFER_SIZE, DEFAULT_WEBSOCKET_MAX_BINARY_MESSAGE_BUFFER_SIZE);
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#websocketInputBufferSize()
-   */
-  @Override
-  public int getWebsocketInputBufferSize() {
-    return getInt( WEBSOCKET_INPUT_BUFFER_SIZE, DEFAULT_WEBSOCKET_INPUT_BUFFER_SIZE);
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#websocketAsyncWriteTimeout()
-   */
-  @Override
-  public int getWebsocketAsyncWriteTimeout() {
-    return getInt( WEBSOCKET_ASYNC_WRITE_TIMEOUT, DEFAULT_WEBSOCKET_ASYNC_WRITE_TIMEOUT);
-  }
-
-  /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.config.GatewayConfig#websocketIdleTimeout()
-   */
-  @Override
-  public int getWebsocketIdleTimeout() {
-    return getInt( WEBSOCKET_IDLE_TIMEOUT, DEFAULT_WEBSOCKET_IDLE_TIMEOUT);
-  }
-
-  /*
-   * (non-Javadoc)
-   *
-   * @see
-   * org.apache.hadoop.gateway.config.GatewayConfig#getMimeTypesToCompress()
-   */
-  @Override
-  public List<String> getMimeTypesToCompress() {
-    List<String> mimeTypes = null;
-    String value = get(MIME_TYPES_TO_COMPRESS, DEFAULT_MIME_TYPES_TO_COMPRESS);
-    if (value != null && !value.isEmpty()) {
-      mimeTypes = Arrays.asList(value.trim().split("\\s*,\\s*"));
-    }
-    return mimeTypes;
-  }
-
-  /**
-   * Map of Topology names and their ports.
-   *
-   * @return
-   */
-  @Override
-  public Map<String, Integer> getGatewayPortMappings() {
-
-    final Map<String, Integer> result = new ConcurrentHashMap<String, Integer>();
-    final Map<String, String> properties = getValByRegex(GATEWAY_PORT_MAPPING_REGEX);
-
-    // Convert port no. from string to int
-    for(final Map.Entry<String, String> e : properties.entrySet()) {
-      // ignore the GATEWAY_PORT_MAPPING_ENABLED property
-      if(!e.getKey().equalsIgnoreCase(GATEWAY_PORT_MAPPING_ENABLED)) {
-        // extract the topology name and use it as a key
-        result.put(StringUtils.substringAfter(e.getKey(), GATEWAY_PORT_MAPPING_PREFIX), Integer.parseInt(e.getValue()) );
-      }
-
-    }
-
-    return Collections.unmodifiableMap(result);
-  }
-
-  /**
-   * Is the Port Mapping feature on ?
-   *
-   * @return
-   */
-  @Override
-  public boolean isGatewayPortMappingEnabled() {
-    final String result = get( GATEWAY_PORT_MAPPING_ENABLED, Boolean.toString(DEFAULT_GATEWAY_PORT_MAPPING_ENABLED));
-    return Boolean.parseBoolean(result);
-  }
-
-  private static long parseNetworkTimeout(String s ) {
-    PeriodFormatter f = new PeriodFormatterBuilder()
-        .appendMinutes().appendSuffix("m"," min")
-        .appendSeconds().appendSuffix("s"," sec")
-        .appendMillis().toFormatter();
-    Period p = Period.parse( s, f );
-    return p.toStandardDuration().getMillis();
-  }
-
-  @Override
-  public boolean isCookieScopingToPathEnabled() {
-    final boolean result = Boolean.parseBoolean(get(COOKIE_SCOPING_ENABLED,
-            Boolean.toString(DEFAULT_COOKIE_SCOPING_FEATURE_ENABLED)));
-    return result;
-  }
-
-  @Override
-  public String getHeaderNameForRemoteAddress() {
-    String value = getVar(REMOTE_IP_HEADER_NAME, "X-Forwarded-For");
-    return value;
-  }
-
-  @Override
-  public String getAlgorithm() {
-	return getVar(CRYPTO_ALGORITHM, null);
-  }
-
-  @Override
-  public String getPBEAlgorithm() {
-	return getVar(CRYPTO_PBE_ALGORITHM, null);
-  }
-
-  @Override
-  public String getTransformation() {
-	return getVar(CRYPTO_TRANSFORMATION, null);
-  }
-
-  @Override
-  public String getSaltSize() {
-	return getVar(CRYPTO_SALTSIZE, null);
-  }
-
-  @Override
-  public String getIterationCount() {
-	return getVar(CRYPTO_ITERATION_COUNT, null);
-  }
-
-  @Override
-  public String getKeyLength() {
-	return getVar(CRYPTO_KEY_LENGTH, null);
-  }
-
-  @Override
-  public boolean isGatewayServerHeaderEnabled() {
-    return Boolean.parseBoolean(getVar(SERVER_HEADER_ENABLED, "true"));
-  }
-}


[40/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-pseudo/src/test/java/org/apache/knox/gateway/identityasserter/filter/DefaultIdentityAssertionFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-pseudo/src/test/java/org/apache/knox/gateway/identityasserter/filter/DefaultIdentityAssertionFilterTest.java b/gateway-provider-identity-assertion-pseudo/src/test/java/org/apache/knox/gateway/identityasserter/filter/DefaultIdentityAssertionFilterTest.java
new file mode 100644
index 0000000..adfc95d
--- /dev/null
+++ b/gateway-provider-identity-assertion-pseudo/src/test/java/org/apache/knox/gateway/identityasserter/filter/DefaultIdentityAssertionFilterTest.java
@@ -0,0 +1,173 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.identityasserter.filter;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.security.Principal;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+
+import org.apache.knox.gateway.security.GroupPrincipal;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+/**
+ *
+ */
+public class DefaultIdentityAssertionFilterTest {
+
+  @Test
+  public void testInitParameters() throws Exception {
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    IdentityAsserterFilter filter = new IdentityAsserterFilter();
+    Subject subject = new Subject();
+    
+    subject.getPrincipals().add(new PrimaryPrincipal("lmccay"));
+    subject.getPrincipals().add(new GroupPrincipal("users"));
+    subject.getPrincipals().add(new GroupPrincipal("admin"));
+    
+    filter.init(config);
+    String username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    String[] groups = filter.mapGroupPrincipals(username, subject);
+    assertEquals("lmccay", username);
+    assertNull(groups); // means for the caller to use the existing subject groups
+    
+    config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "lmccay,kminder=hdfs;newuser=mapred" ).anyTimes();
+    EasyMock.expect(config.getInitParameter("group.principal.mapping") ).andReturn( "kminder=group1;lmccay=mrgroup,mrducks" ).anyTimes();
+    context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.replay( config );
+    filter.init(config);
+    username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    String[] mappedGroups = filter.mapGroupPrincipals(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName(), subject);
+    assertEquals("hdfs", username);
+    assertTrue("mrgroup not found in groups: " + mappedGroups, groupFoundIn("mrgroup", mappedGroups));
+    assertTrue("mrducks not found in groups: " + mappedGroups, groupFoundIn("mrducks", mappedGroups));
+    assertFalse("group1 WAS found in groups: " + mappedGroups, groupFoundIn("group1", mappedGroups));
+
+    subject = new Subject();
+    
+    subject.getPrincipals().add(new PrimaryPrincipal("kminder"));
+    subject.getPrincipals().add(new GroupPrincipal("users"));
+    subject.getPrincipals().add(new GroupPrincipal("admin"));
+    
+    config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "lmccay,kminder=hdfs;newuser=mapred" ).anyTimes();
+    EasyMock.expect(config.getInitParameter("group.principal.mapping") ).andReturn( "kminder=group1;lmccay=mrgroup,mrducks" ).anyTimes();
+    context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.replay( config );
+    filter.init(config);
+    username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    mappedGroups = filter.mapGroupPrincipals(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName(), subject);
+    assertEquals("hdfs", username);
+    assertTrue("group1 not found in groups: " + mappedGroups, groupFoundIn("group1", mappedGroups));
+  }
+
+  /**
+   * @param string
+   * @return
+   */
+  private boolean groupFoundIn(String expected, String[] mappedGroups) {
+    if (mappedGroups == null) return false;
+    for(int i = 0; i < mappedGroups.length; i++) {
+      if (mappedGroups[i].equals(expected)) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  @Test
+  public void testContextParameters() throws Exception {
+    // for backward compatibility of old deployment contributor's method
+    // of adding init params to the servlet context instead of to the filter.
+    // There is the possibility that previously deployed topologies will have
+    // init params in web.xml at the context level instead of the filter level.
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    IdentityAsserterFilter filter = new IdentityAsserterFilter();
+    Subject subject = new Subject();
+    
+    subject.getPrincipals().add(new PrimaryPrincipal("lmccay"));
+    subject.getPrincipals().add(new GroupPrincipal("users"));
+    subject.getPrincipals().add(new GroupPrincipal("admin"));
+    
+    filter.init(config);
+    String username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    String[] groups = filter.mapGroupPrincipals(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName(), subject);
+//    String[] groups = filter.mapGroupPrincipals(username, subject);
+    assertEquals("lmccay", username);
+    assertNull(groups); // means for the caller to use the existing subject groups
+    
+    config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "lmccay,kminder=hdfs;newuser=mapred" ).anyTimes();
+    EasyMock.expect(context.getInitParameter("group.principal.mapping") ).andReturn( "kminder=group1;lmccay=mrgroup,mrducks" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+    filter.init(config);
+    username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    groups = filter.mapGroupPrincipals(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName(), subject);
+    assertEquals("hdfs", username);
+    assertTrue("mrgroup not found in groups: " + groups, groupFoundIn("mrgroup", groups));
+    assertTrue("mrducks not found in groups: " + groups, groupFoundIn("mrducks", groups));
+    assertFalse("group1 WAS found in groups: " + groups, groupFoundIn("group1", groups));
+
+    subject = new Subject();
+    
+    subject.getPrincipals().add(new PrimaryPrincipal("kminder"));
+    subject.getPrincipals().add(new GroupPrincipal("users"));
+    subject.getPrincipals().add(new GroupPrincipal("admin"));
+    
+    config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "lmccay,kminder=hdfs;newuser=mapred" ).anyTimes();
+    EasyMock.expect(context.getInitParameter("group.principal.mapping") ).andReturn( "kminder=group1;lmccay=mrgroup,mrducks" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+    filter.init(config);
+    username = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    assertEquals("hdfs", username);
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-pseudo/src/test/resources/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-pseudo/src/test/resources/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml b/gateway-provider-identity-assertion-pseudo/src/test/resources/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml
deleted file mode 100644
index cf28b92..0000000
--- a/gateway-provider-identity-assertion-pseudo/src/test/resources/org/apache/hadoop/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml
+++ /dev/null
@@ -1,24 +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.
--->
-<rules>
-
-    <rule name="test-rule-username">
-        <match pattern="*://{host}:{port}/{path=**}?{**}"/>
-        <rewrite template="test-output-scheme://{host}:{port}/test-output-path/{path=**}?user.name={$username}?{**}?test-query-output-name=test-query-output-value"/>
-    </rule>
-
-</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-pseudo/src/test/resources/org/apache/knox/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-pseudo/src/test/resources/org/apache/knox/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml b/gateway-provider-identity-assertion-pseudo/src/test/resources/org/apache/knox/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml
new file mode 100644
index 0000000..cf28b92
--- /dev/null
+++ b/gateway-provider-identity-assertion-pseudo/src/test/resources/org/apache/knox/gateway/identityasserter/function/UsernameFunctionProcessorTest/rewrite.xml
@@ -0,0 +1,24 @@
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one or more
+  contributor license agreements.  See the NOTICE file distributed with
+  this work for additional information regarding copyright ownership.
+  The ASF licenses this file to You under the Apache License, Version 2.0
+  (the "License"); you may not use this file except in compliance with
+  the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+-->
+<rules>
+
+    <rule name="test-rule-username">
+        <match pattern="*://{host}:{port}/{path=**}?{**}"/>
+        <rewrite template="test-output-scheme://{host}:{port}/test-output-path/{path=**}?user.name={$username}?{**}?test-query-output-name=test-query-output-value"/>
+    </rule>
+
+</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-regex/src/main/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-regex/src/main/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributor.java b/gateway-provider-identity-assertion-regex/src/main/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributor.java
deleted file mode 100644
index 6ce5676..0000000
--- a/gateway-provider-identity-assertion-regex/src/main/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributor.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.hadoop.gateway.identityasserter.regex.filter;
-
-import org.apache.hadoop.gateway.identityasserter.common.filter.AbstractIdentityAsserterDeploymentContributor;
-
-public class RegexIdentityAsserterDeploymentContributor extends AbstractIdentityAsserterDeploymentContributor {
-
-  @Override
-  public String getName() {
-    return "Regex";
-  }
-
-  protected String getFilterClassname() {
-    return RegexIdentityAssertionFilter.class.getName();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-regex/src/main/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-regex/src/main/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilter.java b/gateway-provider-identity-assertion-regex/src/main/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilter.java
deleted file mode 100644
index 209178b..0000000
--- a/gateway-provider-identity-assertion-regex/src/main/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilter.java
+++ /dev/null
@@ -1,87 +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.hadoop.gateway.identityasserter.regex.filter;
-
-import javax.security.auth.Subject;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-
-import org.apache.hadoop.gateway.identityasserter.common.filter.CommonIdentityAssertionFilter;
-import org.apache.hadoop.gateway.security.principal.PrincipalMappingException;
-
-import java.util.Map;
-import java.util.StringTokenizer;
-import java.util.TreeMap;
-
-public class RegexIdentityAssertionFilter extends CommonIdentityAssertionFilter {
-
-  private String input = null;
-  private String output = null;
-  private Map<String,String> dict;
-  RegexTemplate template;
-  
-  @Override
-  public void init(FilterConfig filterConfig) throws ServletException {
-    super.init(filterConfig);
-    try {
-      input = filterConfig.getInitParameter( "input" );
-      if( input == null ) {
-        input = "";
-      }
-      output = filterConfig.getInitParameter( "output" );
-      if( output == null ) {
-        output = "";
-      }
-      dict = loadDictionary( filterConfig.getInitParameter( "lookup" ) );
-      template = new RegexTemplate( input, output, dict );
-    } catch ( PrincipalMappingException e ) {
-      throw new ServletException( e );
-    }
-  }
-
-  public String[] mapGroupPrincipals(String mappedPrincipalName, Subject subject) {
-    // Returning null will allow existing Subject group principals to remain the same
-    return null;
-  }
-
-  public String mapUserPrincipal(String principalName) {
-    return template.apply( principalName );
-  }
-
-  private Map<String, String> loadDictionary( String config ) throws PrincipalMappingException {
-    Map<String,String> dict = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
-    if( config != null && !config.isEmpty() ) {
-      try {
-        StringTokenizer t = new StringTokenizer( config, ";" );
-        while( t.hasMoreTokens() ) {
-          String nvp = t.nextToken();
-          String[] a = nvp.split( "=" );
-          dict.put( a[0].trim(), a[1].trim() );
-        }
-        return dict;
-      } catch( Exception e ) {
-        dict.clear();
-        throw new PrincipalMappingException(
-            "Unable to load lookup dictionary from provided configuration: " + config +
-                ".  No principal mapping will be provided.", e );
-      }
-    }
-    return dict;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-regex/src/main/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexTemplate.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-regex/src/main/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexTemplate.java b/gateway-provider-identity-assertion-regex/src/main/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexTemplate.java
deleted file mode 100644
index 0a9912d..0000000
--- a/gateway-provider-identity-assertion-regex/src/main/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexTemplate.java
+++ /dev/null
@@ -1,75 +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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.identityasserter.regex.filter;
-
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class RegexTemplate {
-
-  private static Pattern directPattern = Pattern.compile( "\\{(\\[?\\d+?\\]?)\\}" );
-  private static Pattern indirectPattern = Pattern.compile( "\\[(\\d+?)\\]" );
-
-  Pattern inputPattern;
-  String outputTemplate;
-  Map<String,String> lookupTable;
-
-  public RegexTemplate( String regex, String template ) {
-    this( regex, template, null );
-  }
-
-  public RegexTemplate( String regex, String template, Map<String,String> map ) {
-    this.inputPattern = Pattern.compile( regex );
-    this.outputTemplate = template;
-    this.lookupTable = map;
-  }
-
-  public String apply( String input ) {
-    String output = outputTemplate;
-    Matcher inputMatcher = inputPattern.matcher( input );
-    if( inputMatcher.find() ) {
-      output = expandTemplate( inputMatcher, output );
-    }
-    return output;
-  }
-
-  private String expandTemplate( Matcher inputMatcher, String output ) {
-    Matcher directMatcher = directPattern.matcher( output );
-    while( directMatcher.find() ) {
-      String lookupValue = null;
-      String lookupStr = directMatcher.group( 1 );
-      Matcher indirectMatcher = indirectPattern.matcher( lookupStr );
-      if( indirectMatcher.find() ) {
-        lookupStr = indirectMatcher.group( 1 );
-        int lookupIndex = Integer.parseInt( lookupStr );
-        if( lookupTable != null ) {
-          String lookupKey = inputMatcher.group( lookupIndex );
-          lookupValue = lookupTable.get( lookupKey );
-        }
-      } else {
-        int lookupIndex = Integer.parseInt( lookupStr );
-        lookupValue = inputMatcher.group( lookupIndex );
-      }
-      output = directMatcher.replaceFirst( lookupValue == null ? "" : lookupValue );
-      directMatcher = directPattern.matcher( output );
-    }
-    return output;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-regex/src/main/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-regex/src/main/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributor.java b/gateway-provider-identity-assertion-regex/src/main/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributor.java
new file mode 100644
index 0000000..f40895b
--- /dev/null
+++ b/gateway-provider-identity-assertion-regex/src/main/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributor.java
@@ -0,0 +1,34 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.identityasserter.regex.filter;
+
+import org.apache.knox.gateway.identityasserter.common.filter.AbstractIdentityAsserterDeploymentContributor;
+
+public class RegexIdentityAsserterDeploymentContributor extends
+    AbstractIdentityAsserterDeploymentContributor {
+
+  @Override
+  public String getName() {
+    return "Regex";
+  }
+
+  protected String getFilterClassname() {
+    return RegexIdentityAssertionFilter.class.getName();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-regex/src/main/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-regex/src/main/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilter.java b/gateway-provider-identity-assertion-regex/src/main/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilter.java
new file mode 100644
index 0000000..4cc86ae
--- /dev/null
+++ b/gateway-provider-identity-assertion-regex/src/main/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilter.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.knox.gateway.identityasserter.regex.filter;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+
+import org.apache.knox.gateway.identityasserter.common.filter.CommonIdentityAssertionFilter;
+import org.apache.knox.gateway.security.principal.PrincipalMappingException;
+
+import java.util.Map;
+import java.util.StringTokenizer;
+import java.util.TreeMap;
+
+public class RegexIdentityAssertionFilter extends
+    CommonIdentityAssertionFilter {
+
+  private String input = null;
+  private String output = null;
+  private Map<String,String> dict;
+  RegexTemplate template;
+  
+  @Override
+  public void init(FilterConfig filterConfig) throws ServletException {
+    super.init(filterConfig);
+    try {
+      input = filterConfig.getInitParameter( "input" );
+      if( input == null ) {
+        input = "";
+      }
+      output = filterConfig.getInitParameter( "output" );
+      if( output == null ) {
+        output = "";
+      }
+      dict = loadDictionary( filterConfig.getInitParameter( "lookup" ) );
+      template = new RegexTemplate( input, output, dict );
+    } catch ( PrincipalMappingException e ) {
+      throw new ServletException( e );
+    }
+  }
+
+  public String[] mapGroupPrincipals(String mappedPrincipalName, Subject subject) {
+    // Returning null will allow existing Subject group principals to remain the same
+    return null;
+  }
+
+  public String mapUserPrincipal(String principalName) {
+    return template.apply( principalName );
+  }
+
+  private Map<String, String> loadDictionary( String config ) throws PrincipalMappingException {
+    Map<String,String> dict = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+    if( config != null && !config.isEmpty() ) {
+      try {
+        StringTokenizer t = new StringTokenizer( config, ";" );
+        while( t.hasMoreTokens() ) {
+          String nvp = t.nextToken();
+          String[] a = nvp.split( "=" );
+          dict.put( a[0].trim(), a[1].trim() );
+        }
+        return dict;
+      } catch( Exception e ) {
+        dict.clear();
+        throw new PrincipalMappingException(
+            "Unable to load lookup dictionary from provided configuration: " + config +
+                ".  No principal mapping will be provided.", e );
+      }
+    }
+    return dict;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-regex/src/main/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexTemplate.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-regex/src/main/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexTemplate.java b/gateway-provider-identity-assertion-regex/src/main/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexTemplate.java
new file mode 100644
index 0000000..e8f108e
--- /dev/null
+++ b/gateway-provider-identity-assertion-regex/src/main/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexTemplate.java
@@ -0,0 +1,75 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.identityasserter.regex.filter;
+
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class RegexTemplate {
+
+  private static Pattern directPattern = Pattern.compile( "\\{(\\[?\\d+?\\]?)\\}" );
+  private static Pattern indirectPattern = Pattern.compile( "\\[(\\d+?)\\]" );
+
+  Pattern inputPattern;
+  String outputTemplate;
+  Map<String,String> lookupTable;
+
+  public RegexTemplate( String regex, String template ) {
+    this( regex, template, null );
+  }
+
+  public RegexTemplate( String regex, String template, Map<String,String> map ) {
+    this.inputPattern = Pattern.compile( regex );
+    this.outputTemplate = template;
+    this.lookupTable = map;
+  }
+
+  public String apply( String input ) {
+    String output = outputTemplate;
+    Matcher inputMatcher = inputPattern.matcher( input );
+    if( inputMatcher.find() ) {
+      output = expandTemplate( inputMatcher, output );
+    }
+    return output;
+  }
+
+  private String expandTemplate( Matcher inputMatcher, String output ) {
+    Matcher directMatcher = directPattern.matcher( output );
+    while( directMatcher.find() ) {
+      String lookupValue = null;
+      String lookupStr = directMatcher.group( 1 );
+      Matcher indirectMatcher = indirectPattern.matcher( lookupStr );
+      if( indirectMatcher.find() ) {
+        lookupStr = indirectMatcher.group( 1 );
+        int lookupIndex = Integer.parseInt( lookupStr );
+        if( lookupTable != null ) {
+          String lookupKey = inputMatcher.group( lookupIndex );
+          lookupValue = lookupTable.get( lookupKey );
+        }
+      } else {
+        int lookupIndex = Integer.parseInt( lookupStr );
+        lookupValue = inputMatcher.group( lookupIndex );
+      }
+      output = directMatcher.replaceFirst( lookupValue == null ? "" : lookupValue );
+      directMatcher = directPattern.matcher( output );
+    }
+    return output;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-regex/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-regex/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-identity-assertion-regex/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index 0dd2d2e..0000000
--- a/gateway-provider-identity-assertion-regex/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.identityasserter.regex.filter.RegexIdentityAsserterDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-regex/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-regex/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-identity-assertion-regex/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..4e1b9a4
--- /dev/null
+++ b/gateway-provider-identity-assertion-regex/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.identityasserter.regex.filter.RegexIdentityAsserterDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-regex/src/test/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-regex/src/test/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributorTest.java b/gateway-provider-identity-assertion-regex/src/test/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributorTest.java
deleted file mode 100644
index 6d93359..0000000
--- a/gateway-provider-identity-assertion-regex/src/test/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributorTest.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.hadoop.gateway.identityasserter.regex.filter;
-
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class RegexIdentityAsserterDeploymentContributorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader<ProviderDeploymentContributor> loader = ServiceLoader.load( ProviderDeploymentContributor.class );
-    Iterator<ProviderDeploymentContributor> iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof RegexIdentityAsserterDeploymentContributor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + RegexIdentityAsserterDeploymentContributor.class.getName() + " via service loader." );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-regex/src/test/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-regex/src/test/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilterTest.java b/gateway-provider-identity-assertion-regex/src/test/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilterTest.java
deleted file mode 100644
index f8ba323..0000000
--- a/gateway-provider-identity-assertion-regex/src/test/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilterTest.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.hadoop.gateway.identityasserter.regex.filter;
-
-import org.apache.hadoop.gateway.security.GroupPrincipal;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-import javax.security.auth.Subject;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-
-import java.security.Principal;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-
-public class RegexIdentityAssertionFilterTest {
-
-  @Test
-  public void testExtractUsernameFromEmail() throws Exception {
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    RegexIdentityAssertionFilter filter = new RegexIdentityAssertionFilter();
-
-    Subject subject = new Subject();
-    subject.getPrincipals().add(new PrimaryPrincipal( "member@us.apache.org" ) );
-    subject.getPrincipals().add(new GroupPrincipal( "user" ) );
-    subject.getPrincipals().add( new GroupPrincipal( "admin" ) );
-
-    // First test is with no config.  Since the output template is the empty string that should be the result.
-    filter.init(config);
-    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    String[] groups = filter.mapGroupPrincipals(actual, subject);
-    assertThat( actual, is( "" ) );
-    assertThat( groups, is( nullValue() ) ); // means for the caller to use the existing subject groups
-
-    // Test what is effectively a static mapping
-    config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.expect(config.getInitParameter( "output" ) ).andReturn( "test-output" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-    filter.init( config );
-    actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
-    assertEquals( actual, "test-output" );
-
-    // Test username extraction.
-    config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.expect(config.getInitParameter( "input" ) ).andReturn( "(.*)@.*" ).anyTimes();
-    EasyMock.expect(config.getInitParameter( "output" ) ).andReturn( "prefix_{1}_suffix" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-    filter.init( config );
-    actual = filter.mapUserPrincipal( "member@us.apache.org" );
-    assertEquals( actual, "prefix_member_suffix" );
-
-  }
-
-  @Test
-  public void testMapDomain() throws Exception {
-    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-
-    RegexIdentityAssertionFilter filter = new RegexIdentityAssertionFilter();
-
-    Subject subject = new Subject();
-    subject.getPrincipals().add(new PrimaryPrincipal( "member@us.apache.org" ) );
-    subject.getPrincipals().add(new GroupPrincipal( "user" ) );
-    subject.getPrincipals().add( new GroupPrincipal( "admin" ) );
-
-    String actual;
-
-    // Test dictionary lookup.
-    config = EasyMock.createNiceMock( FilterConfig.class );
-    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    context = EasyMock.createNiceMock(ServletContext.class);
-    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
-    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
-    EasyMock.expect(config.getInitParameter( "input" ) ).andReturn( "(.*)@(.*?)\\..*" ).anyTimes();
-    EasyMock.expect(config.getInitParameter( "output" ) ).andReturn( "prefix_{1}_suffix:{[2]}" ).anyTimes();
-    EasyMock.expect(config.getInitParameter( "lookup" ) ).andReturn( "us=USA;ca=CANADA" ).anyTimes();
-    EasyMock.replay( config );
-    EasyMock.replay( context );
-    filter.init( config );
-    actual = filter.mapUserPrincipal( "member1@us.apache.org" );
-    assertThat( actual, is( "prefix_member1_suffix:USA" ) );
-    actual = filter.mapUserPrincipal( "member2@ca.apache.org" );
-    assertThat( actual, is( "prefix_member2_suffix:CANADA" ) );
-    actual = filter.mapUserPrincipal( "member3@nj.apache.org" );
-    assertThat( actual, is( "prefix_member3_suffix:" ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-regex/src/test/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexTemplateTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-regex/src/test/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexTemplateTest.java b/gateway-provider-identity-assertion-regex/src/test/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexTemplateTest.java
deleted file mode 100644
index b32cd41..0000000
--- a/gateway-provider-identity-assertion-regex/src/test/java/org/apache/hadoop/gateway/identityasserter/regex/filter/RegexTemplateTest.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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.identityasserter.regex.filter;
-
-import org.junit.Test;
-
-import java.util.Map;
-import java.util.TreeMap;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.Is.is;
-
-public class RegexTemplateTest {
-
-  @Test
-  public void testExtractUsernameFromEmailAddress() {
-
-    RegexTemplate template;
-    String actual;
-
-    template = new RegexTemplate( "(.*)@.*", "prefix_{1}_suffix" );
-    actual = template.apply( "member@apache.org" );
-    assertThat( actual, is( "prefix_member_suffix" ) );
-
-    template = new RegexTemplate( "(.*)@.*", "prefix_{0}_suffix" );
-    actual = template.apply( "member@apache.org" );
-    assertThat( actual, is( "prefix_member@apache.org_suffix" ) );
-
-    template = new RegexTemplate( "(.*)@.*", "prefix_{1}_{a}_suffix" );
-    actual = template.apply( "member@apache.org" );
-    assertThat( actual, is( "prefix_member_{a}_suffix" ) );
-
-  }
-
-  @Test
-  public void testExtractUsernameFromEmailAddressAndMapDomain() {
-
-    RegexTemplate template;
-    Map<String,String> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
-    map.put( "us", "USA" );
-    map.put( "ca", "CANADA" );
-
-    String actual;
-
-    template = new RegexTemplate( "(.*)@(.*?)\\..*", "prefix_{1}:{[2]}_suffix", map );
-    actual = template.apply( "member@us.apache.org" );
-    assertThat( actual, is( "prefix_member:USA_suffix" ) );
-
-    actual = template.apply( "member@ca.apache.org" );
-    assertThat( actual, is( "prefix_member:CANADA_suffix" ) );
-
-    actual = template.apply( "member@nj.apache.org" );
-    assertThat( actual, is( "prefix_member:_suffix" ) );
-
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-regex/src/test/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-regex/src/test/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributorTest.java b/gateway-provider-identity-assertion-regex/src/test/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributorTest.java
new file mode 100644
index 0000000..db0c6b3
--- /dev/null
+++ b/gateway-provider-identity-assertion-regex/src/test/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAsserterDeploymentContributorTest.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.knox.gateway.identityasserter.regex.filter;
+
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributor;
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class RegexIdentityAsserterDeploymentContributorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader<ProviderDeploymentContributor> loader = ServiceLoader.load( ProviderDeploymentContributor.class );
+    Iterator<ProviderDeploymentContributor> iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof RegexIdentityAsserterDeploymentContributor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + RegexIdentityAsserterDeploymentContributor.class.getName() + " via service loader." );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-regex/src/test/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-regex/src/test/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilterTest.java b/gateway-provider-identity-assertion-regex/src/test/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilterTest.java
new file mode 100644
index 0000000..3a61c37
--- /dev/null
+++ b/gateway-provider-identity-assertion-regex/src/test/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexIdentityAssertionFilterTest.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.knox.gateway.identityasserter.regex.filter;
+
+import org.apache.knox.gateway.security.GroupPrincipal;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+import javax.security.auth.Subject;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+
+import java.security.Principal;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertEquals;
+
+public class RegexIdentityAssertionFilterTest {
+
+  @Test
+  public void testExtractUsernameFromEmail() throws Exception {
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    RegexIdentityAssertionFilter filter = new RegexIdentityAssertionFilter();
+
+    Subject subject = new Subject();
+    subject.getPrincipals().add(new PrimaryPrincipal( "member@us.apache.org" ) );
+    subject.getPrincipals().add(new GroupPrincipal( "user" ) );
+    subject.getPrincipals().add( new GroupPrincipal( "admin" ) );
+
+    // First test is with no config.  Since the output template is the empty string that should be the result.
+    filter.init(config);
+    String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    String[] groups = filter.mapGroupPrincipals(actual, subject);
+    assertThat( actual, is( "" ) );
+    assertThat( groups, is( nullValue() ) ); // means for the caller to use the existing subject groups
+
+    // Test what is effectively a static mapping
+    config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.expect(config.getInitParameter( "output" ) ).andReturn( "test-output" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+    filter.init( config );
+    actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName());
+    assertEquals( actual, "test-output" );
+
+    // Test username extraction.
+    config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.expect(config.getInitParameter( "input" ) ).andReturn( "(.*)@.*" ).anyTimes();
+    EasyMock.expect(config.getInitParameter( "output" ) ).andReturn( "prefix_{1}_suffix" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+    filter.init( config );
+    actual = filter.mapUserPrincipal( "member@us.apache.org" );
+    assertEquals( actual, "prefix_member_suffix" );
+
+  }
+
+  @Test
+  public void testMapDomain() throws Exception {
+    FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+
+    RegexIdentityAssertionFilter filter = new RegexIdentityAssertionFilter();
+
+    Subject subject = new Subject();
+    subject.getPrincipals().add(new PrimaryPrincipal( "member@us.apache.org" ) );
+    subject.getPrincipals().add(new GroupPrincipal( "user" ) );
+    subject.getPrincipals().add( new GroupPrincipal( "admin" ) );
+
+    String actual;
+
+    // Test dictionary lookup.
+    config = EasyMock.createNiceMock( FilterConfig.class );
+    EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    context = EasyMock.createNiceMock(ServletContext.class);
+    EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
+    EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
+    EasyMock.expect(config.getInitParameter( "input" ) ).andReturn( "(.*)@(.*?)\\..*" ).anyTimes();
+    EasyMock.expect(config.getInitParameter( "output" ) ).andReturn( "prefix_{1}_suffix:{[2]}" ).anyTimes();
+    EasyMock.expect(config.getInitParameter( "lookup" ) ).andReturn( "us=USA;ca=CANADA" ).anyTimes();
+    EasyMock.replay( config );
+    EasyMock.replay( context );
+    filter.init( config );
+    actual = filter.mapUserPrincipal( "member1@us.apache.org" );
+    assertThat( actual, is( "prefix_member1_suffix:USA" ) );
+    actual = filter.mapUserPrincipal( "member2@ca.apache.org" );
+    assertThat( actual, is( "prefix_member2_suffix:CANADA" ) );
+    actual = filter.mapUserPrincipal( "member3@nj.apache.org" );
+    assertThat( actual, is( "prefix_member3_suffix:" ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-regex/src/test/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexTemplateTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-regex/src/test/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexTemplateTest.java b/gateway-provider-identity-assertion-regex/src/test/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexTemplateTest.java
new file mode 100644
index 0000000..3c3b06f
--- /dev/null
+++ b/gateway-provider-identity-assertion-regex/src/test/java/org/apache/knox/gateway/identityasserter/regex/filter/RegexTemplateTest.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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.identityasserter.regex.filter;
+
+import org.junit.Test;
+
+import java.util.Map;
+import java.util.TreeMap;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.Is.is;
+
+public class RegexTemplateTest {
+
+  @Test
+  public void testExtractUsernameFromEmailAddress() {
+
+    RegexTemplate template;
+    String actual;
+
+    template = new RegexTemplate( "(.*)@.*", "prefix_{1}_suffix" );
+    actual = template.apply( "member@apache.org" );
+    assertThat( actual, is( "prefix_member_suffix" ) );
+
+    template = new RegexTemplate( "(.*)@.*", "prefix_{0}_suffix" );
+    actual = template.apply( "member@apache.org" );
+    assertThat( actual, is( "prefix_member@apache.org_suffix" ) );
+
+    template = new RegexTemplate( "(.*)@.*", "prefix_{1}_{a}_suffix" );
+    actual = template.apply( "member@apache.org" );
+    assertThat( actual, is( "prefix_member_{a}_suffix" ) );
+
+  }
+
+  @Test
+  public void testExtractUsernameFromEmailAddressAndMapDomain() {
+
+    RegexTemplate template;
+    Map<String,String> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+    map.put( "us", "USA" );
+    map.put( "ca", "CANADA" );
+
+    String actual;
+
+    template = new RegexTemplate( "(.*)@(.*?)\\..*", "prefix_{1}:{[2]}_suffix", map );
+    actual = template.apply( "member@us.apache.org" );
+    assertThat( actual, is( "prefix_member:USA_suffix" ) );
+
+    actual = template.apply( "member@ca.apache.org" );
+    assertThat( actual, is( "prefix_member:CANADA_suffix" ) );
+
+    actual = template.apply( "member@nj.apache.org" );
+    assertThat( actual, is( "prefix_member:_suffix" ) );
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributor.java b/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributor.java
deleted file mode 100644
index e58665b..0000000
--- a/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributor.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.hadoop.gateway.identityasserter.switchcase;
-
-import org.apache.hadoop.gateway.identityasserter.common.filter.AbstractIdentityAsserterDeploymentContributor;
-
-public class SwitchCaseIdentityAsserterDeploymentContributor extends AbstractIdentityAsserterDeploymentContributor {
-
-  public String getName() {
-    return "SwitchCase";
-  }
-
-  protected String getFilterClassname() {
-    return SwitchCaseIdentityAssertionFilter.class.getName();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilter.java b/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilter.java
deleted file mode 100644
index 09163b7..0000000
--- a/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilter.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.hadoop.gateway.identityasserter.switchcase;
-
-import java.util.Set;
-import javax.security.auth.Subject;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-
-import org.apache.hadoop.gateway.identityasserter.common.filter.CommonIdentityAssertionFilter;
-import org.apache.hadoop.gateway.security.GroupPrincipal;
-
-public class SwitchCaseIdentityAssertionFilter extends CommonIdentityAssertionFilter {
-
-  private static final String USER_INIT_PARAM = "principal.case";
-  private static final String GROUP_INIT_PARAM = "group.principal.case";
-
-  private enum SwitchCase { UPPER, LOWER, NONE }
-
-  private SwitchCase userCase = SwitchCase.LOWER;
-  private SwitchCase groupCase = SwitchCase.LOWER;
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-    super.init(filterConfig);
-
-    String s;
-    s = filterConfig.getInitParameter( USER_INIT_PARAM );
-    if ( s != null ) {
-      s = s.trim().toUpperCase();
-      try {
-        userCase = SwitchCase.valueOf( s );
-        groupCase = userCase;
-      } catch ( IllegalArgumentException e ) {
-        // Ignore it and use the default.
-      }
-    }
-    s = filterConfig.getInitParameter( GROUP_INIT_PARAM );
-    if ( s != null ) {
-      s = s.trim().toUpperCase();
-      try {
-        groupCase = SwitchCase.valueOf( s );
-      } catch ( IllegalArgumentException e ) {
-        // Ignore it and use the default.
-      }
-    }
-  }
-
-  @Override
-  public String mapUserPrincipal( String principalName ) {
-    return switchCase( principalName, userCase );
-  }
-
-  @Override
-  public String[] mapGroupPrincipals( String mappedPrincipalName, Subject subject ) {
-    String[] groupNames = null;
-    if ( groupCase != SwitchCase.NONE ) {
-      Set<GroupPrincipal> groups = subject.getPrincipals( GroupPrincipal.class );
-      if( groups != null && groups.size() > 0 ) {
-        groupNames = new String[ groups.size() ];
-        int i = 0;
-        for( GroupPrincipal group : groups ) {
-          groupNames[ i++ ] = switchCase( group.getName(), groupCase );
-        }
-      }
-    }
-    return groupNames;
-  }
-
-  private String switchCase( String name, SwitchCase switchCase ) {
-    if ( name != null ) {
-      switch( switchCase ) {
-        case UPPER:
-          return name.toUpperCase();
-        case LOWER:
-          return name.toLowerCase();
-      }
-    }
-    return name;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributor.java b/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributor.java
new file mode 100644
index 0000000..a9677a5
--- /dev/null
+++ b/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributor.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.knox.gateway.identityasserter.switchcase;
+
+import org.apache.knox.gateway.identityasserter.common.filter.AbstractIdentityAsserterDeploymentContributor;
+
+public class SwitchCaseIdentityAsserterDeploymentContributor extends
+    AbstractIdentityAsserterDeploymentContributor {
+
+  public String getName() {
+    return "SwitchCase";
+  }
+
+  protected String getFilterClassname() {
+    return SwitchCaseIdentityAssertionFilter.class.getName();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilter.java b/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilter.java
new file mode 100644
index 0000000..9405c49
--- /dev/null
+++ b/gateway-provider-identity-assertion-switchcase/src/main/java/org/apache/knox/gateway/identityasserter/switchcase/SwitchCaseIdentityAssertionFilter.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.knox.gateway.identityasserter.switchcase;
+
+import java.util.Set;
+import javax.security.auth.Subject;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+
+import org.apache.knox.gateway.identityasserter.common.filter.CommonIdentityAssertionFilter;
+import org.apache.knox.gateway.security.GroupPrincipal;
+
+public class SwitchCaseIdentityAssertionFilter extends
+    CommonIdentityAssertionFilter {
+
+  private static final String USER_INIT_PARAM = "principal.case";
+  private static final String GROUP_INIT_PARAM = "group.principal.case";
+
+  private enum SwitchCase { UPPER, LOWER, NONE }
+
+  private SwitchCase userCase = SwitchCase.LOWER;
+  private SwitchCase groupCase = SwitchCase.LOWER;
+
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+    super.init(filterConfig);
+
+    String s;
+    s = filterConfig.getInitParameter( USER_INIT_PARAM );
+    if ( s != null ) {
+      s = s.trim().toUpperCase();
+      try {
+        userCase = SwitchCase.valueOf( s );
+        groupCase = userCase;
+      } catch ( IllegalArgumentException e ) {
+        // Ignore it and use the default.
+      }
+    }
+    s = filterConfig.getInitParameter( GROUP_INIT_PARAM );
+    if ( s != null ) {
+      s = s.trim().toUpperCase();
+      try {
+        groupCase = SwitchCase.valueOf( s );
+      } catch ( IllegalArgumentException e ) {
+        // Ignore it and use the default.
+      }
+    }
+  }
+
+  @Override
+  public String mapUserPrincipal( String principalName ) {
+    return switchCase( principalName, userCase );
+  }
+
+  @Override
+  public String[] mapGroupPrincipals( String mappedPrincipalName, Subject subject ) {
+    String[] groupNames = null;
+    if ( groupCase != SwitchCase.NONE ) {
+      Set<GroupPrincipal> groups = subject.getPrincipals( GroupPrincipal.class );
+      if( groups != null && groups.size() > 0 ) {
+        groupNames = new String[ groups.size() ];
+        int i = 0;
+        for( GroupPrincipal group : groups ) {
+          groupNames[ i++ ] = switchCase( group.getName(), groupCase );
+        }
+      }
+    }
+    return groupNames;
+  }
+
+  private String switchCase( String name, SwitchCase switchCase ) {
+    if ( name != null ) {
+      switch( switchCase ) {
+        case UPPER:
+          return name.toUpperCase();
+        case LOWER:
+          return name.toLowerCase();
+      }
+    }
+    return name;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-switchcase/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-switchcase/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-identity-assertion-switchcase/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index 98c62ef..0000000
--- a/gateway-provider-identity-assertion-switchcase/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,18 +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.
-##########################################################################
-org.apache.hadoop.gateway.identityasserter.switchcase.SwitchCaseIdentityAsserterDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-switchcase/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-switchcase/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-identity-assertion-switchcase/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..3e36c87
--- /dev/null
+++ b/gateway-provider-identity-assertion-switchcase/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,18 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+org.apache.knox.gateway.identityasserter.switchcase.SwitchCaseIdentityAsserterDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributorTest.java b/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributorTest.java
deleted file mode 100644
index 3c9aacc..0000000
--- a/gateway-provider-identity-assertion-switchcase/src/test/java/org/apache/hadoop/gateway/identityasserter/switchcase/SwitchCaseIdentityAsserterDeploymentContributorTest.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.hadoop.gateway.identityasserter.switchcase;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor;
-import org.junit.Test;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class SwitchCaseIdentityAsserterDeploymentContributorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader<ProviderDeploymentContributor> loader = ServiceLoader.load( ProviderDeploymentContributor.class );
-    Iterator<ProviderDeploymentContributor> iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof SwitchCaseIdentityAsserterDeploymentContributor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + SwitchCaseIdentityAsserterDeploymentContributor.class.getName() + " via service loader." );
-  }
-}


[53/64] knox git commit: KNOX-989 - Report metrics at service level (/webhdfs/v1) instead of url with args (/webhdfs/v1/?op=LISTSTATUS) (Mohammad Kamrul Islam via Sandeep More)

Posted by mo...@apache.org.
KNOX-989 - Report metrics at service level (/webhdfs/v1) instead of url with args (/webhdfs/v1/?op=LISTSTATUS) (Mohammad Kamrul Islam via Sandeep More)


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

Branch: refs/heads/KNOX-998-Package_Restructuring
Commit: ac532bd73c5da8997f865e048b36c76fd3c11301
Parents: bea3974
Author: Sandeep More <mo...@apache.org>
Authored: Fri Aug 25 12:08:17 2017 -0400
Committer: Sandeep More <mo...@apache.org>
Committed: Fri Aug 25 12:09:21 2017 -0400

----------------------------------------------------------------------
 .../instr/InstrHttpClientBuilderProvider.java   |  3 +-
 .../services/metrics/impl/instr/InstrUtils.java | 54 ++++++++++++++++++++
 .../impl/instr/InstrumentedGatewayFilter.java   |  2 +-
 3 files changed, 57 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/knox/blob/ac532bd7/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrHttpClientBuilderProvider.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrHttpClientBuilderProvider.java b/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrHttpClientBuilderProvider.java
index eb3ec57..e96c05e 100644
--- a/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrHttpClientBuilderProvider.java
+++ b/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrHttpClientBuilderProvider.java
@@ -57,7 +57,8 @@ public class InstrHttpClientBuilderProvider implements InstrumentationProvider<H
         }
         RequestLine requestLine = request.getRequestLine();
         URIBuilder uriBuilder = new URIBuilder(requestLine.getUri());
-        return MetricRegistry.name("service", new String[]{name, context + uriBuilder.removeQuery().build().toString(), methodNameString(request)});
+        String resourcePath = InstrUtils.getResourcePath(uriBuilder.removeQuery().build().toString());
+        return MetricRegistry.name("service", new String[]{name, context + resourcePath, methodNameString(request)});
       } catch (URISyntaxException e) {
         throw new IllegalArgumentException(e);
       }

http://git-wip-us.apache.org/repos/asf/knox/blob/ac532bd7/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrUtils.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrUtils.java b/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrUtils.java
new file mode 100644
index 0000000..20e359b
--- /dev/null
+++ b/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrUtils.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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.hadoop.gateway.services.metrics.impl.instr;
+
+import com.google.common.base.Strings;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class InstrUtils {
+
+    //This regular expression pattern is used to parse the *first* two elements
+    //of a path. For example, if the path is “/webhdfs/v1/d1/d2/d2/d4”, this pattern
+    //can be used to get the first two ("/webhdfs/v1/"). The "?" in pattern
+    //ensures not to be greedy in matching.
+    private static Pattern p = Pattern.compile("/.*?/.*?/");
+
+    /**
+     * This function parses the pathinfo provided  in any servlet context and
+     * returns the segment that is related to the resource.
+     * For example, if the path is "/webhdfs/v1/d1/d2/d2/d4". it returns "/webhdfs/v1"
+     *
+     * @param fullPath
+     * @return
+     */
+    public static String getResourcePath(String fullPath) {
+        String resourcePath = "";
+        if (!Strings.isNullOrEmpty(fullPath)) {
+            Matcher m = p.matcher(fullPath);
+            if (m.find()) {
+                resourcePath = m.group(0);
+            } else {
+                resourcePath = fullPath;
+            }
+        }
+        return resourcePath;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/ac532bd7/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrumentedGatewayFilter.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrumentedGatewayFilter.java b/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrumentedGatewayFilter.java
index a3c75f6..063d79a 100644
--- a/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrumentedGatewayFilter.java
+++ b/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrumentedGatewayFilter.java
@@ -89,7 +89,7 @@ public class InstrumentedGatewayFilter extends GatewayFilter {
     builder.append(request.getServletContext().getContextPath());
     if (request instanceof HttpServletRequest) {
       HttpServletRequest httpServletRequest = (HttpServletRequest) request;
-      builder.append(httpServletRequest.getPathInfo());
+      builder.append(InstrUtils.getResourcePath(httpServletRequest.getPathInfo()));
       builder.append(".");
       builder.append(httpServletRequest.getMethod());
       builder.append("-requests");


[19/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlFilterReaderBaseTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlFilterReaderBaseTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlFilterReaderBaseTest.java
deleted file mode 100644
index deed693..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlFilterReaderBaseTest.java
+++ /dev/null
@@ -1,765 +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.hadoop.gateway.filter.rewrite.impl.html;
-
-import org.apache.commons.digester3.Digester;
-import org.apache.commons.digester3.ExtendedBaseRules;
-import org.apache.commons.digester3.binder.DigesterLoader;
-import org.apache.commons.io.IOUtils;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepFlow;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteCheckDescriptorExt;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteControlDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptorExt;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteFilterContentDescriptorImpl;
-import org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlRewriteRulesDigester;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
-import org.hamcrest.Matchers;
-import org.junit.Before;
-import org.junit.Test;
-import org.xml.sax.SAXException;
-import org.xmlmatchers.namespace.SimpleNamespaceContext;
-
-import javax.xml.namespace.QName;
-import javax.xml.parsers.ParserConfigurationException;
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Pattern;
-
-import static org.hamcrest.CoreMatchers.hasItem;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.contains;
-import static org.hamcrest.Matchers.equalTo;
-import static org.junit.Assert.assertEquals;
-import static org.xmlmatchers.XmlMatchers.hasXPath;
-import static org.xmlmatchers.transform.XmlConverters.the;
-
-public class HtmlFilterReaderBaseTest {
-
-  public static class NoopXmlFilterReader extends HtmlFilterReaderBase {
-    public NoopXmlFilterReader( Reader reader ) throws IOException, ParserConfigurationException {
-      super( reader );
-    }
-
-    @Override
-    protected String filterText( QName elementName, String text, String ruleName ) {
-      return text;
-    }
-
-    @Override
-    protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
-      return attributeValue;
-    }
-
-    @Override
-    public String filterValueString( String name, String value, String ruleName ) {
-      return value;
-    }
-  }
-
-  public static class MapXmlFilterReader extends HtmlFilterReaderBase {
-    private Map<String,String> map;
-
-    public MapXmlFilterReader( Reader reader, Map<String,String> map ) throws IOException, ParserConfigurationException {
-      super( reader );
-      this.map = map;
-    }
-
-    @Override
-    protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
-      return map.get( attributeValue.trim() );
-    }
-
-    @Override
-    protected String filterText( QName elementName, String text, String ruleName ) {
-      return map.get( text.trim() );
-    }
-
-    @Override
-    public String filterValueString( String name, String value, String ruleName ) {
-      return map.get( value );
-    }
-  }
-
-  public static class MatchRuleXmlFilterReader extends HtmlFilterReaderBase {
-    private Map<String, Map<String,String>> rules;
-    public MatchRuleXmlFilterReader( Reader reader, Map<String, Map<String,String>> rules, UrlRewriteFilterContentDescriptor config ) throws IOException, ParserConfigurationException {
-      super( reader, config );
-      this.rules = rules;
-    }
-
-    @Override
-    protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
-      return filterValueString( attributeName.getLocalPart(), attributeValue, ruleName );
-    }
-
-    @Override
-    protected String filterText( QName elementName, String text, String ruleName ) {
-      return filterValueString( elementName.getLocalPart(), text, ruleName );
-    }
-
-    @Override
-    public String filterValueString( String name, String value, String ruleName ) {
-      Map<String, String> rule = rules.get( ruleName );
-      if ( rule == null ){
-        return value;
-      }
-      for ( Map.Entry<String, String> entry : rule.entrySet() ) {
-        if ( Pattern.compile( entry.getKey() ).matcher( value ).matches() ) {
-          return entry.getValue();
-        }
-      }
-      return value;
-    }
-  }
-
-  @Test
-  public void testSimple() throws IOException, ParserConfigurationException {
-    String inputXml = "<root/>";
-    StringReader inputReader = new StringReader( inputXml );
-    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
-    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-    assertThat( the( outputHtml ), hasXPath( "/root" ) );
-  }
-
-  @Test
-  public void testSimpleNested() throws IOException, ParserConfigurationException {
-    String inputXml = "<root><child1><child11/><child12/></child1><child2><child21/><child22/></child2></root>";
-    StringReader inputReader = new StringReader( inputXml );
-    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
-    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-    assertThat( the( outputHtml ), hasXPath( "/root" ) );
-    assertThat( the( outputHtml ), hasXPath( "/root/child1" ) );
-    assertThat( the( outputHtml ), hasXPath( "/root/child1/child11" ) );
-    assertThat( the( outputHtml ), hasXPath( "/root/child1/child12" ) );
-    assertThat( the( outputHtml ), hasXPath( "/root/child2" ) );
-    assertThat( the( outputHtml ), hasXPath( "/root/child2/child21" ) );
-    assertThat( the( outputHtml ), hasXPath( "/root/child2/child22" ) );
-  }
-
-  @Test
-  public void testSimpleWithNamespace() throws IOException, ParserConfigurationException {
-    String inputXml = "<ns:root xmlns:ns='http://hortonworks.com/xml/ns'></ns:root>";
-    StringReader inputReader = new StringReader( inputXml );
-    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
-    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-
-    //System.out.println( outputHtml );
-    SimpleNamespaceContext ns = new SimpleNamespaceContext();
-    ns.bind( "ns", "http://hortonworks.com/xml/ns" );
-    assertThat( the( outputHtml ), hasXPath( "/ns:root", ns ) );
-  }
-
-  @Test
-  public void testSimpleTextNode() throws IOException, ParserConfigurationException {
-    String inputXml = "<root>text</root>";
-    StringReader inputReader = new StringReader( inputXml );
-    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
-    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( outputHtml );
-    assertThat( the( outputHtml ), hasXPath( "/root/text()", equalTo( "text" ) ) );
-  }
-
-  @Test
-  public void testSimpleAttribute() throws IOException, ParserConfigurationException {
-    String inputXml = "<root name='value'/>";
-    StringReader inputReader = new StringReader( inputXml );
-    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
-    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( outputHtml );
-    assertThat( the( outputHtml ), hasXPath( "/root/@name", equalTo( "value" ) ) );
-  }
-
-  @Test
-  public void testSimpleBooleanAttribute() throws IOException, ParserConfigurationException {
-    String inputXml = "<root name/>";
-    StringReader inputReader = new StringReader(inputXml);
-    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader(inputReader);
-    String outputHtml = new String(IOUtils.toCharArray(filterReader));
-    assertEquals(inputXml, outputHtml);
-  }
-
-  @Test
-  public void testComplexBooleanAttribute() throws IOException, ParserConfigurationException {
-    String inputXml = "<root boolean non-boolean='value' empty=''/>";
-    StringReader inputReader = new StringReader(inputXml);
-    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader(inputReader);
-    String outputHtml = new String(IOUtils.toCharArray(filterReader));
-    assertEquals(inputXml, outputHtml);
-  }
-
-  @Test
-  public void testMappedText() throws IOException, ParserConfigurationException {
-    Map<String,String> map = new HashMap<>();
-    map.put( "input-text", "output-text" );
-    String inputXml = "<root>input-text</root>";
-    StringReader inputReader = new StringReader( inputXml );
-    HtmlFilterReaderBase filterReader = new MapXmlFilterReader( inputReader, map );
-    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( outputHtml );
-    assertThat( the( outputHtml ), hasXPath( "/root/text()", equalTo( "output-text" ) ) );
-  }
-
-  @Test
-  public void testMappedAttribute() throws IOException, ParserConfigurationException {
-    Map<String,String> map = new HashMap<>();
-    map.put( "input-text", "output-text" );
-    String inputXml = "<root attribute='input-text'/>";
-    StringReader inputReader = new StringReader( inputXml );
-    HtmlFilterReaderBase filterReader = new MapXmlFilterReader( inputReader, map );
-    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( outputHtml );
-    assertThat( the( outputHtml ), hasXPath( "/root/@attribute", equalTo( "output-text" ) ) );
-  }
-
-  @Test
-  public void testCombined() throws IOException, ParserConfigurationException {
-    Map<String,String> map = new HashMap<>();
-    map.put( "attr1-input", "attr1-output" );
-    map.put( "attr2-input", "attr2-output" );
-    map.put( "attr3-input", "attr3-output" );
-    map.put( "attr4-input", "attr4-output" );
-    map.put( "attr5-input", "attr5-output" );
-    map.put( "attr6-input", "attr6-output" );
-    map.put( "attr7-input", "attr7-output" );
-    map.put( "root-input1", "root-output1" );
-    map.put( "root-input2", "root-output2" );
-    map.put( "root-input3", "root-output3" );
-    map.put( "child1-input", "child1-output" );
-    map.put( "child2-input", "child2-output" );
-
-    String inputXml =
-          "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
-            "<!-- Comment -->\n" +
-            "<ns1:root xmlns:ns1='http://hortonworks.com/xml/ns1' attr1='attr1-input' ns1:attr2='attr2-input'>\n" +
-            "  root-input1\n" +
-            "  <child1 attr3='attr3-input' ns1:attr4='attr4-input'>\n" +
-            "    child1-input\n" +
-            "  </child1>\n" +
-            "  root-input2\n" +
-            "  <ns2:child2 xmlns:ns2='http://hortonworks.com/xml/ns2' attr5='attr5-input' ns1:attr6='attr6-input' ns2:attr7='attr7-input'>\n" +
-            "    child2-input\n" +
-            "  </ns2:child2>\n" +
-            "  root-input3\n" +
-            "</ns1:root>";
-    //System.out.println( inputXml );
-
-    StringReader inputReader = new StringReader( inputXml );
-    HtmlFilterReaderBase filterReader = new MapXmlFilterReader( inputReader, map );
-    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( outputXml );
-    //System.out.flush();
-
-    SimpleNamespaceContext ns = new SimpleNamespaceContext();
-    ns.bind( "n1", "http://hortonworks.com/xml/ns1" );
-    ns.bind( "n2", "http://hortonworks.com/xml/ns2" );
-
-    assertThat( the( outputXml ), hasXPath( "/n1:root", ns ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/@attr1", ns, equalTo( "attr1-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/@n1:attr2", ns, equalTo( "attr2-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/text()[1]", ns, equalTo( "root-output1" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/text()[2]", ns, equalTo( "root-output2" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/text()[3]", ns, equalTo( "root-output3" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/child1", ns ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/child1/@attr3", ns, equalTo( "attr3-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/child1/@n1:attr4", ns, equalTo( "attr4-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/child1/text()", ns, equalTo( "child1-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2", ns ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/@attr5", ns, equalTo( "attr5-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/@n1:attr6", ns, equalTo( "attr6-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/@n2:attr7", ns, equalTo( "attr7-output" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/text()", ns, equalTo( "child2-output" ) ) );
-  }
-
-  @Test
-  public void testSimpleJavaScriptText() throws IOException, ParserConfigurationException {
-    String inputXml = "<root><script type=\"text/javascript\">input-js-text</script></root>";
-    StringReader inputReader = new StringReader( inputXml );
-    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
-    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
-    assertThat( the( outputXml ), hasXPath( "/root/script/text()", equalTo( "input-js-text" ) ) );
-  }
-
-  @Test
-  public void testMatchedJavaScriptText() throws IOException, ParserConfigurationException {
-    Map<String, Map<String, String>> rules = new HashMap<>();
-    Map<String, String> map = new HashMap<>();
-    map.put( "(https?://[^/':,]+:[\\d]+)?/cluster/app", "https://knoxhost:8443/cluster/app" );
-    rules.put( "test-rule", map );
-    String inputXml =
-        "<root>\n" +
-        "  <script type=\"text/javascript\">\n" +
-        "    var appsTableData=[\n" +
-        "      [\"<a href='/cluster/app/application_1436831599487_0008'>application_1436831599487_0008</a>\",\"hdfs\",\"Spark Pi\",\"SPARK\",\"<a href='http://testhost:8088/cluster/app/application_1436831599487_0008'>History</a>\"],\n" +
-        "      [\"<a href='/cluster/app/application_1436831599487_0006'>application_1436831599487_0006</a>\",\"hdfs\",\"Spark Pi\",\"SPARK\",\"<a href='http://testhost:8088/cluster/app/application_1436831599487_0006'>History</a>\"],\n" +
-        "      [\"<a href='/cluster/app/application_1436831599487_0007'>application_1436831599487_0007</a>\",\"hdfs\",\"Spark Pi\",\"SPARK\",\"<a href='http://testhost:8088/cluster/app/application_1436831599487_0007'>History</a>\"]\n" +
-        "    ]\n" +
-        "  </script>\n" +
-        "</root>\n";
-    StringReader inputReader = new StringReader( inputXml );
-    UrlRewriteFilterContentDescriptor config = new UrlRewriteFilterContentDescriptorImpl();
-    config.addApply( "(https?://[^/':,]+:[\\d]+)?/cluster/app", "test-rule" );
-    HtmlFilterReaderBase filterReader = new MatchRuleXmlFilterReader( inputReader, rules, config );
-    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
-    String expectedOutput =
-        "<root>\n" +
-        "  <script type=\"text/javascript\">\n" +
-        "    var appsTableData=[\n" +
-        "      [\"<a href='https://knoxhost:8443/cluster/app/application_1436831599487_0008'>application_1436831599487_0008</a>\",\"hdfs\",\"Spark Pi\",\"SPARK\",\"<a href='https://knoxhost:8443/cluster/app/application_1436831599487_0008'>History</a>\"],\n" +
-        "      [\"<a href='https://knoxhost:8443/cluster/app/application_1436831599487_0006'>application_1436831599487_0006</a>\",\"hdfs\",\"Spark Pi\",\"SPARK\",\"<a href='https://knoxhost:8443/cluster/app/application_1436831599487_0006'>History</a>\"],\n" +
-        "      [\"<a href='https://knoxhost:8443/cluster/app/application_1436831599487_0007'>application_1436831599487_0007</a>\",\"hdfs\",\"Spark Pi\",\"SPARK\",\"<a href='https://knoxhost:8443/cluster/app/application_1436831599487_0007'>History</a>\"]\n" +
-        "    ]\n" +
-        "  </script>\n" +
-        "</root>\n";
-    assertThat( outputXml, is( expectedOutput ) );
-  }
-
-  @Test
-  public void testMRJobHistoryUIJavaScriptText() throws IOException, ParserConfigurationException {
-    Map<String, Map<String, String>> rules = new HashMap<>();
-    Map<String, String> map = new HashMap<>();
-    map.put( "https?://[^/':,]+:[\\d]+", "https://knoxhost:8443/gateway/nodemanagerui/node?host=knoxhost" );
-    rules.put( "test-rule", map );
-    String inputXml =
-        "<root>\n" +
-        "  <script type=\"text/javascript\">\n" +
-        "    var appsTableData=[\n" +
-        "      [\"<a href='http://testhost:8042'>/default-rack/node</a>\",\"<a href='http://testhost:8042'>testhost:8042</a>\"],\n" +
-        "    ]\n" +
-        "  </script>\n" +
-        "</root>\n";
-    StringReader inputReader = new StringReader( inputXml );
-    UrlRewriteFilterContentDescriptor config = new UrlRewriteFilterContentDescriptorImpl();
-    config.addApply("https?://[^/':,]+:[\\d]+", "test-rule");
-    HtmlFilterReaderBase filterReader = new MatchRuleXmlFilterReader( inputReader, rules, config );
-    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
-    String expectedOutput =
-        "<root>\n" +
-        "  <script type=\"text/javascript\">\n" +
-        "    var appsTableData=[\n" +
-        "      [\"<a href='https://knoxhost:8443/gateway/nodemanagerui/node?host=knoxhost'>/default-rack/node</a>\",\"<a href='https://knoxhost:8443/gateway/nodemanagerui/node?host=knoxhost'>testhost:8042</a>\"],\n" +
-        "    ]\n" +
-        "  </script>\n" +
-        "</root>\n";
-    assertThat( outputXml, is( expectedOutput ) );
-  }
-
-  public static class XmlRewriteRulesDescriptorDigesterTest {
-
-    private static DigesterLoader loader = DigesterLoader.newLoader( new XmlRewriteRulesDigester() );
-    private static Digester digester = loader.newDigester( new ExtendedBaseRules() );
-
-    @Before
-    public void setupTest() {
-      digester.setValidating( false );
-    }
-
-    @Test
-    public void testRuleParsing() throws IOException, SAXException {
-      Reader reader = new StringReader( "<rules/>" );
-      UrlRewriteRulesDescriptor config = digester.parse( reader );
-      assertThat( config.getRules().isEmpty(), is( true ) );
-
-      reader = new StringReader( "<rules><rule></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().size(), is( 1 ) );
-      UrlRewriteRuleDescriptor rule = config.getRules().get( 0 );
-      assertThat( rule, notNullValue() );
-      assertThat( rule.name(), nullValue() );
-      assertThat( rule.pattern(), nullValue() );
-      assertThat( rule.directions(), nullValue() );
-      assertThat( rule.flow(), nullValue() );
-
-      reader = new StringReader( "<rules><rule name=\"test-name\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule, notNullValue() );
-      assertThat( rule.name(), is( "test-name" ) );
-      assertThat( rule.pattern(), nullValue() );
-      assertThat( rule.directions(), nullValue() );
-      assertThat( rule.flow(), nullValue() );
-
-      reader = new StringReader( "<rules><rule pattern=\"test-pattern\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule, notNullValue() );
-      assertThat( rule.name(), nullValue() );
-      assertThat( rule.pattern(), is( "test-pattern" ) );
-      assertThat( rule.directions(), nullValue() );
-      assertThat( rule.flow(), nullValue() );
-
-      reader = new StringReader( "<rules><rule dir=\"request\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule, notNullValue() );
-      assertThat( rule.name(), nullValue() );
-      assertThat( rule.pattern(), nullValue() );
-      assertThat( rule.directions().size(), is( 1 ) );
-      assertThat( rule.directions(), contains( UrlRewriter.Direction.IN ) );
-      assertThat( rule.flow(), nullValue() );
-
-      reader = new StringReader( "<rules><rule flow=\"all\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule, notNullValue() );
-      assertThat( rule.name(), nullValue() );
-      assertThat( rule.pattern(), nullValue() );
-      assertThat( rule.directions(), nullValue() );
-      assertThat( rule.flow(), Matchers.is( UrlRewriteStepFlow.ALL ) );
-    }
-
-    @Test
-    public void testDirectionParsing() throws IOException, SAXException {
-      Reader reader;
-      UrlRewriteRulesDescriptor config;
-
-      reader = new StringReader( "<rules><rule dir=\"request\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"Request\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"in\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"req\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"Req\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"REQ\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"inbound\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"Inbound\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"INBOUND\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"in\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"In\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"IN\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"i\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-      reader = new StringReader( "<rules><rule dir=\"I\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-
-
-      reader = new StringReader( "<rules><rule dir=\"response\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"Response\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"out\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"res\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"Res\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"RES\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"outbound\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"Outbound\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"OUTBOUND\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"out\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"Out\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"OUT\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"o\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-      reader = new StringReader( "<rules><rule dir=\"O\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
-
-
-      reader = new StringReader( "<rules><rule dir=\"request,response\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), hasItem( UrlRewriter.Direction.IN ) );
-      assertThat( config.getRules().get( 0 ).directions(), hasItem( UrlRewriter.Direction.OUT ) );
-    }
-
-    @Test
-    public void testFlowParsing() throws IOException, SAXException {
-      Reader reader;
-      UrlRewriteRulesDescriptor config;
-
-      reader = new StringReader( "<rules><rule dir=\"request\"></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
-    }
-
-    @Test
-    public void testMatchParsing() throws IOException, SAXException {
-      Reader reader;
-      UrlRewriteRulesDescriptor config;
-      UrlRewriteRuleDescriptor rule;
-      UrlRewriteMatchDescriptorExt match;
-      List<? extends UrlRewriteStepDescriptor> steps;
-
-      reader = new StringReader( "<rules><rule><match></match></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config, notNullValue() );
-      assertThat( config.getRules(), notNullValue() );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule.steps(), notNullValue() );
-      assertThat( rule.steps().size(), is( 1 ) );
-      match = (UrlRewriteMatchDescriptorExt)rule.steps().get( 0 );
-      assertThat( match, notNullValue() );
-      //assertThat( match.type(), nullValue() );
-      assertThat( match.operation(), nullValue() );
-      assertThat( match.pattern(), nullValue() );
-
-      reader = new StringReader( "<rules><rule><match type=\"test-type\" op=\"test-op\" pattern=\"test-pattern\"></match></rule></rules>" );
-      config = digester.parse( reader );
-      match = (UrlRewriteMatchDescriptorExt)config.getRules().get( 0 ).steps().get( 0 );
-      //assertThat( match.type(), is("test-type") );
-      assertThat( match.operation(), is( "test-op" ) );
-      assertThat( match.pattern(), is( "test-pattern" ) );
-
-      reader = new StringReader( "<rules><rule name=\"test\"><match><match pattern=\"test-pattern\"></match></match></rule></rules>" );
-      config = digester.parse( reader );
-      steps = ((UrlRewriteMatchDescriptor)config.getRule( "test" ).steps().get( 0 )).steps();
-      assertThat( steps, notNullValue() );
-      assertThat( steps.size(), is( 1 ) );
-      assertThat( steps.get( 0 ), notNullValue() );
-      match = (UrlRewriteMatchDescriptorExt)steps.get( 0 );
-      assertThat( match.pattern(), is( "test-pattern" ) );
-    }
-
-    @Test
-    public void testCheckParsing() throws IOException, SAXException {
-      Reader reader;
-      UrlRewriteRulesDescriptor config;
-      UrlRewriteRuleDescriptor rule;
-      List<UrlRewriteStepDescriptor> steps;
-      UrlRewriteCheckDescriptorExt step;
-
-      reader = new StringReader( "<rules><rule><check></check></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config, notNullValue() );
-      assertThat( config.getRules(), notNullValue() );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule.steps(), notNullValue() );
-      assertThat( rule.steps().size(), is( 1 ) );
-      step = (UrlRewriteCheckDescriptorExt)rule.steps().get( 0 );
-      assertThat( step, notNullValue() );
-      //assertThat( step.type(), nullValue() );
-      assertThat( step.operation(), nullValue() );
-      assertThat( step.input(), nullValue() );
-      assertThat( step.value(), nullValue() );
-
-      reader = new StringReader( "<rules><rule><check type=\"test-type\" op=\"test-op\" input=\"test-input\" value=\"test-value\"></check></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config, notNullValue() );
-      assertThat( config.getRules(), notNullValue() );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule.steps(), notNullValue() );
-      assertThat( rule.steps().size(), is( 1 ) );
-      step = (UrlRewriteCheckDescriptorExt)rule.steps().get( 0 );
-      assertThat( step, notNullValue() );
-      //assertThat( step.type(), is( "test-type" ) );
-      assertThat( step.operation(), is( "test-op" ) );
-      assertThat( step.input(), is( "test-input" ) );
-      assertThat( step.value(), is( "test-value" ) );
-    }
-
-    @Test
-    public void testActionParsing() throws IOException, SAXException {
-      Reader reader;
-      UrlRewriteRulesDescriptor config;
-      UrlRewriteRuleDescriptor rule;
-      UrlRewriteActionDescriptorBase step;
-
-      reader = new StringReader( "<rules><rule><action></action></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config, notNullValue() );
-      assertThat( config.getRules(), notNullValue() );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule.steps(), notNullValue() );
-      assertThat( rule.steps().size(), is( 1 ) );
-      step = (UrlRewriteActionDescriptorBase)rule.steps().get( 0 );
-      assertThat( step, notNullValue() );
-      //assertThat( step.type(), nullValue() );
-      assertThat( step.parameter(), nullValue() );
-
-      reader = new StringReader( "<rules><rule><action type=\"test-type\" param=\"test-param\"></action></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config, notNullValue() );
-      assertThat( config.getRules(), notNullValue() );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule.steps(), notNullValue() );
-      assertThat( rule.steps().size(), is( 1 ) );
-      step = (UrlRewriteActionDescriptorBase)rule.steps().get( 0 );
-      assertThat( step, notNullValue() );
-      //assertThat( step.type(), is( "test-type" ) );
-      assertThat( step.parameter(), is( "test-param" ) );
-    }
-
-    @Test
-    public void testControlParsing() throws IOException, SAXException {
-      Reader reader;
-      UrlRewriteRulesDescriptor config;
-      UrlRewriteRuleDescriptor rule;
-      List<UrlRewriteStepDescriptor> steps;
-
-      reader = new StringReader( "<rules><rule><control></control></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config, notNullValue() );
-      assertThat( config.getRules(), notNullValue() );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule.steps(), notNullValue() );
-      assertThat( rule.steps().size(), is( 1 ) );
-      UrlRewriteControlDescriptor step = (UrlRewriteControlDescriptor)rule.steps().get( 0 );
-      assertThat( step, notNullValue() );
-      assertThat(  step.flow(), nullValue() );
-
-      reader = new StringReader( "<rules><rule><control flow=\"or\"></control></rule></rules>" );
-      config = digester.parse( reader );
-      assertThat( config, notNullValue() );
-      assertThat( config.getRules(), notNullValue() );
-      assertThat( config.getRules().size(), is( 1 ) );
-      rule = config.getRules().get( 0 );
-      assertThat( rule.steps(), notNullValue() );
-      assertThat( rule.steps().size(), is( 1 ) );
-      step = (UrlRewriteControlDescriptor)rule.steps().get( 0 );
-      assertThat( step, notNullValue() );
-      assertThat( step.flow(), is( UrlRewriteStepFlow.OR ) );
-    }
-  }
-  
-  @Test
-  public void testTagNameLetterCase() throws Exception {
-    String inputXml = "<Root/>";
-    StringReader inputReader = new StringReader( inputXml );
-    
-    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
-    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
-    assertThat( the( outputXml ), hasXPath( "/Root" ) );
-  }
-  
-  @Test
-  public void testXmlWithHtmlTagNames() throws Exception {
-    String inputXml = "<root><br><table name=\"table1\"></table><table name=\"table2\"></table></br></root>";
-    StringReader inputReader = new StringReader( inputXml );
-    
-    HtmlFilterReaderBase filterReader = new NoopXmlFilterReader( inputReader );
-    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
-    assertThat( the( outputXml ), hasXPath( "/root/br/table[1]/@name", equalTo( "table1" ) ) );
-    assertThat( the( outputXml ), hasXPath( "/root/br/table[2]/@name", equalTo( "table2" ) ) );
-  }
-
-  private class TestXmlFilterReader extends HtmlFilterReaderBase {
-
-    protected TestXmlFilterReader( Reader reader, UrlRewriteFilterContentDescriptor contentConfig ) throws IOException, ParserConfigurationException {
-      super( reader );
-    }
-
-    @Override
-    protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
-      return "attr:" + ruleName + "{" + attributeValue + "}";
-    }
-
-    @Override
-    protected String filterText( QName elementName, String text, String ruleName ) {
-      return "text:" + ruleName + "{" + text + "}";
-    }
-
-    @Override
-    public String filterValueString( String name, String value, String ruleName ) {
-      return value;
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessorTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessorTest.java
deleted file mode 100644
index e26d584..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessorTest.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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.filter.rewrite.impl.html;
-
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.fail;
-
-public class HtmlImportFunctionProcessorTest {
-
-  @SuppressWarnings("rawtypes")
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof HtmlImportFunctionProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + HtmlImportFunctionProcessor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    HtmlImportFunctionProcessor processor = new HtmlImportFunctionProcessor();
-    assertThat( processor.name(), is( "import" ) );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlPrefixProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlPrefixProcessorTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlPrefixProcessorTest.java
deleted file mode 100644
index 3954fd3..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/html/HtmlPrefixProcessorTest.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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * 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.hadoop.gateway.filter.rewrite.impl.html;
-
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
-import org.junit.Test;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.fail;
-
-public class HtmlPrefixProcessorTest {
-
-  public HtmlPrefixProcessorTest() {
-    super();
-  }
-
-  @SuppressWarnings("rawtypes")
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof HtmlPrefixProcessor) {
-        return;
-      }
-    }
-    fail( "Failed to find " + HtmlPrefixProcessor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testName() throws Exception {
-    HtmlPrefixProcessor processor = new HtmlPrefixProcessor();
-    assertThat( processor.name(), is( "prefix" ) );
-  }
-
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReaderTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReaderTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReaderTest.java
deleted file mode 100644
index 08458a8..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptFilterReaderTest.java
+++ /dev/null
@@ -1,118 +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.hadoop.gateway.filter.rewrite.impl.javascript;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.regex.Pattern;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteFilterContentDescriptorImpl;
-
-import org.junit.Test;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-public class JavaScriptFilterReaderTest {
-  public static class NoopJsFilterReader extends JavaScriptFilterReader {
-    public NoopJsFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException {
-      super( reader, config );
-    }
-
-    @Override
-    public String filterValueString( String name, String value, String ruleName ) {
-      return value;
-    }
-  }
-
-  public static class MatchRuleJsFilterReader extends JavaScriptFilterReader {
-    private Map<String, Map<String,String>> rules;
-    public MatchRuleJsFilterReader( Reader reader, Map<String, Map<String,String>> rules, UrlRewriteFilterContentDescriptor config ) throws IOException {
-      super( reader, config );
-      this.rules = rules;
-    }
-
-    @Override
-    public String filterValueString( String name, String value, String ruleName ) {
-      Map<String, String> rule = rules.get( ruleName );
-      if ( rule == null ) {
-        return value;
-      }
-      for ( Map.Entry<String, String> entry : rule.entrySet() ) {
-        if ( Pattern.compile( entry.getKey() ).matcher( value ).matches() ) {
-          return entry.getValue();
-        }
-      }
-      return value;
-    }
-  }
-
-  @Test
-  public void testSimple() throws IOException {
-    String inputJs = "function load_page() {}\n";
-    StringReader inputReader = new StringReader( inputJs );
-    UrlRewriteFilterContentDescriptor config = new UrlRewriteFilterContentDescriptorImpl();
-    JavaScriptFilterReader filterReader = new NoopJsFilterReader( inputReader, config );
-    String outputJs = new String( IOUtils.toCharArray( filterReader ) );
-    assertThat( outputJs, is ( inputJs ) );
-  }
-
-  @Test
-  public void testSimpleMultipleLines() throws IOException {
-    String inputJs =
-        "var url = '/webhdfs/v1' + abs_path + '?op=GET_BLOCK_LOCATIONS';\n" +
-        "$.ajax({\"url\": url, \"crossDomain\": true}).done(function(data) {}).error(network_error_handler(url));\n";
-    StringReader inputReader = new StringReader( inputJs );
-    UrlRewriteFilterContentDescriptor config = new UrlRewriteFilterContentDescriptorImpl();
-    config.addApply( "/webhdfs/v1", "test-rule" );
-    JavaScriptFilterReader filterReader = new NoopJsFilterReader( inputReader, config );
-    String outputJs = new String( IOUtils.toCharArray( filterReader ) );
-    assertThat( outputJs, is ( inputJs ) );
-  }
-
-  @Test
-  public void testMatchedJsContent() throws IOException {
-    Map<String, Map<String, String>> rules = new HashMap<>();
-    Map<String, String> map = new HashMap<>();
-    map.put( "(https?://[^/':,]+:[\\d]+)?/cluster/app", "https://knoxhost:8443/cluster/app" );
-    map.put( "/webhdfs/v1", "https://knoxhost:8443/webhdfs/v1" );
-    rules.put( "test-rule", map );
-    String inputJs =
-        "var url = '/webhdfs/v1' + abs_path + '?op=GET_BLOCK_LOCATIONS';\n" +
-        "$.ajax({\"url\": url, \"crossDomain\": true}).done(function(data) {\n" +
-        "  var url = http://testhost:8088/cluster/app/application_1436831599487_0001;\n" +
-        "}).error(network_error_handler(url));\n";
-    StringReader inputReader = new StringReader( inputJs );
-    UrlRewriteFilterContentDescriptor config = new UrlRewriteFilterContentDescriptorImpl();
-    config.addApply( "(https?://[^/':,]+:[\\d]+)?/cluster/app", "test-rule" );
-    config.addApply( "/webhdfs/v1", "test-rule" );
-    JavaScriptFilterReader filterReader = new MatchRuleJsFilterReader( inputReader, rules, config );
-    String outputJs = new String( IOUtils.toCharArray( filterReader ) );
-    String expectedOutputJs =
-        "var url = 'https://knoxhost:8443/webhdfs/v1' + abs_path + '?op=GET_BLOCK_LOCATIONS';\n" +
-        "$.ajax({\"url\": url, \"crossDomain\": true}).done(function(data) {\n" +
-        "  var url = https://knoxhost:8443/cluster/app/application_1436831599487_0001;\n" +
-        "}).error(network_error_handler(url));\n";
-    assertThat( outputJs, is ( expectedOutputJs ) );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest.java
deleted file mode 100644
index 064b09a..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReaderTest.java
+++ /dev/null
@@ -1,364 +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.hadoop.gateway.filter.rewrite.impl.json;
-
-import com.jayway.jsonassert.JsonAssert;
-import org.apache.commons.io.IOUtils;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterBufferDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterDetectDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptorFactory;
-import org.apache.hadoop.test.TestUtils;
-import org.junit.Test;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.StringReader;
-import java.math.BigInteger;
-import java.nio.charset.Charset;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.contains;
-import static org.hamcrest.Matchers.containsString;
-import static org.junit.Assert.fail;
-
-public class JsonFilterReaderTest {
-
-  @Test
-  public void testValueNumberWithBuffering() throws Exception {
-    String input = "{ \"apps\" : {\"app\":[{\"id\":\"one\", \"progress\":100.0, \"startedTime\":1399975176760}]} }";
-
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
-    UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "$.apps.app[*]" );
-    UrlRewriteFilterApplyDescriptor applyConfig = bufferConfig.addApply( "$.id", "test-rule" );
-
-    JsonFilterReader filter = new JsonFilterReader( new StringReader( input ), contentConfig );
-    String output = IOUtils.toString( filter );
-    assertThat( output, containsString( "\"startedTime\":1399975176760}" ) );
-  }
-
-
-  @Test
-  public void testSimple() throws IOException {
-    String inputJson = "{ \"test-name\" : \"test-value\" }";
-    StringReader inputReader = new StringReader( inputJson );
-    JsonFilterReader filterReader = new TestJsonFilterReader( inputReader, null );
-    String outputJson = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( "JSON=" + outputJson );
-
-    JsonAssert.with( outputJson ).assertThat( "name<test-name>", is( "value:null<test-value>" ) );
-  }
-
-  @Test
-  public void testRootArray() throws Exception {
-    String inputJson = "[\"test-value-1\",\"test-value-2\",\"test-value-3\"]";
-    StringReader inputReader = new StringReader( inputJson );
-    JsonFilterReader filterReader = new TestJsonFilterReader( inputReader, null );
-    String outputJson = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( "JSON=" + outputJson );
-    JsonAssert.with( outputJson ).assertThat( "$.[0]", is( "value:null<test-value-1>" ) );
-    JsonAssert.with( outputJson ).assertThat( "$.[1]", is( "value:null<test-value-2>" ) );
-    JsonAssert.with( outputJson ).assertThat( "$.[2]", is( "value:null<test-value-3>" ) );
-
-    inputJson = "[777,42]";
-    inputReader = new StringReader( inputJson );
-    filterReader = new TestJsonFilterReader( inputReader, null );
-    outputJson = new String( IOUtils.toCharArray( filterReader ) );
-    //System.out.println( "JSON=" + outputJson );
-    JsonAssert.with( outputJson ).assertThat( "$.[0]", is( 777 ) );
-    JsonAssert.with( outputJson ).assertThat( "$.[1]", is( 42 ) );
-  }
-
-  @Test
-  public void testEmptyObject() throws IOException {
-    String inputJson = "{}";
-    StringReader inputReader = new StringReader( inputJson );
-    JsonFilterReader filterReader = new TestJsonFilterReader( inputReader, null );
-    String outputJson = new String( IOUtils.toCharArray( filterReader ) );
-
-    assertThat( outputJson, is( "{}" ) );
-  }
-
-  @Test
-  public void testEmptyArray() throws IOException {
-    String inputJson = "[]";
-    StringReader inputReader = new StringReader( inputJson );
-    JsonFilterReader filterReader = new TestJsonFilterReader( inputReader, null );
-    String outputJson = new String( IOUtils.toCharArray( filterReader ) );
-
-    assertThat( outputJson, is( "[]" ) );
-  }
-
-  @Test
-  public void testUnscopedStreaming() throws IOException {
-    InputStream stream = TestUtils.getResourceStream( this.getClass(), "simple-values.json" );
-    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
-
-    //System.out.println( "INPUT=" + input );
-
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter=1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
-    UrlRewriteFilterApplyDescriptor applyConfig = contentConfig.addApply( "$['test-str']", "test-rule" );
-
-    JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
-    String output = IOUtils.toString( filter );
-
-    //System.out.println( "OUTPUT=" + output );
-
-    JsonAssert.with( output ).assertThat( "name<test-str>", is( "value:null<text>" ) );
-  }
-
-  @Test
-  public void testNamesWithDots() throws IOException {
-    InputStream stream = TestUtils.getResourceStream( this.getClass(), "dotted-field-name.json" );
-    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
-
-    //System.out.println( "INPUT=" + input );
-
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "test-filter" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "application/json" );
-    //NOTE: The field names are rewritten first so the values rules need to match the rewritten name.
-    contentConfig.addApply( "$.name<testField>", "test-rule" );
-    contentConfig.addApply( "$.name<test_field>", "test-rule" );
-    contentConfig.addApply( "$.name<test-field>", "test-rule" );
-    contentConfig.addApply( "$['name<test.field>']", "test-rule" );
-
-    JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
-    String output = IOUtils.toString( filter );
-
-    //System.out.println( "OUTPUT=" + output );
-
-    JsonAssert.with( output ).assertThat( "$['name<testField>']", is( "value:test-rule<testField value>" ) );
-    JsonAssert.with( output ).assertThat( "$['name<test_field>']", is( "value:test-rule<test_field value>" ) );
-    JsonAssert.with( output ).assertThat( "$['name<test-field>']", is( "value:test-rule<test-field value>" ) );
-    JsonAssert.with( output ).assertThat( "$['name<test.field>']", is( "value:test-rule<test.field value>" ) );
-  }
-
-//  @Test
-//  public void testJsonPathObject() throws IOException {
-//    InputStream stream = TestUtils.getResourceStream( this.getClass(), "complex.json" );
-//    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
-//
-//    Object o;
-//
-//    o = JsonPath.read( "$", input, JsonNode.class );
-//    assertThat( o, instanceOf( ObjectNode.class ) );
-//    assertThat( o.toString(), startsWith( "{" ) );
-//    System.out.println( o.getClass() + "=" + o );
-//
-//    o = JsonPath.read( "$['test-str']", input, JsonNode.class );
-//    System.out.println( o.getClass() + "=" + o );
-//
-//    o = JsonPath.read( "$['test-obj-multi']", input, JsonNode.class );
-//    System.out.println( o.getClass() + "=" + o );
-//
-//    o = JsonPath.read( "$['val']", (JsonNode)o, JsonNode.class );
-//    System.out.println( o.getClass() + "=" + o );
-//
-//    JsonPath p = JsonPath.compile( "$['test-obj-multi']['val']" );
-//    o = JsonPath.read( "$['test-obj-multi']['val']", input, JsonNode.class );
-//    JsonNode pp = ((JsonNode)o).findParent("val");
-//    System.out.println( "$['test-obj-multi']['val']=" + o.getClass() + "=" + o );
-//
-//  }
-//
-//  @Test
-//  public void testJsonPathArray() throws IOException {
-//    InputStream stream = TestUtils.getResourceStream( this.getClass(), "array.json" );
-//    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
-//
-//    Object o;
-//
-//    o = JsonPath.read( "$", input, JsonNode.class );
-//    System.out.println( o.getClass() + "=" + o );
-//
-//    o = JsonPath.read( "$[0]", input, JsonNode.class );
-//    System.out.println( o.getClass() + "=" + o );
-//
-//    o = JsonPath.read( "$[*]", input, JsonNode.class );
-//    System.out.println( "$[*]=" + o.getClass() + "=" + o );
-//
-//    o = JsonPath.read( "$['obj1-fld1']", (JsonNode)o, JsonNode.class );
-//    System.out.println( o.getClass() + "=" + o );
-//
-//    o = JsonPath.read( "$[0]['obj1-fld1']", input, JsonNode.class );
-//    System.out.println( o.getClass() + "=" + o );
-//
-//  }
-
-  @Test
-  public void testBuffered() throws IOException {
-    InputStream stream = TestUtils.getResourceStream( this.getClass(), "simple-values.json" );
-    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
-
-    //System.out.println( "INPUT=" + input );
-
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
-    UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "$" );
-    UrlRewriteFilterApplyDescriptor applyConfig = bufferConfig.addApply( "$['name<test-str>']", "test-rule" );
-    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
-
-    JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
-    String output = IOUtils.toString( filter );
-
-    //System.out.println( "OUTPUT=" + output );
-
-    JsonAssert.with( output ).assertThat( "name<test-str>", is( "value:test-rule<text>" ) );
-  }
-
-  @Test
-  public void testBufferedDetectApply() throws IOException {
-    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties.json" );
-    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
-
-    //System.out.println( "INPUT=" + input );
-
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
-    UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "$.name<properties>.*.name<property>" );
-    UrlRewriteFilterDetectDescriptor detectConfig = bufferConfig.addDetect( "$.name<property-name>", "test-name-2" );
-    UrlRewriteFilterApplyDescriptor applyConfig = detectConfig.addApply( "$.name<property-value>", "test-rule-2" );
-
-    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
-
-    JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
-    String output = IOUtils.toString( filter );
-
-    //System.out.println( "OUTPUT=" + output );
-
-    JsonAssert.with( output ).assertThat( "name<properties>[0].name<property>.name<property-name>", is( "test-name-1" ) );
-    JsonAssert.with( output ).assertThat( "name<properties>[0].name<property>.name<property-value>", is( "test-value-1" ) );
-    JsonAssert.with( output ).assertThat( "name<properties>[1].name<property>.name<property-name>", is( "test-name-2" ) );
-    JsonAssert.with( output ).assertThat( "name<properties>[1].name<property>.name<property-value>", is( "value:test-rule-2<test-value-2>" ) );
-    JsonAssert.with( output ).assertThat( "name<properties>[2].name<property>.name<property-name>", is( "test-name-3" ) );
-    JsonAssert.with( output ).assertThat( "name<properties>[2].name<property>.name<property-value>", is( "test-value-3" ) );
-  }
-
-  @Test
-  public void testBufferedApply() throws IOException {
-    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties.json" );
-    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
-
-    //System.out.println( "INPUT=" + input );
-
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
-    UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "$.name<properties>.*.name<property>" );
-    UrlRewriteFilterApplyDescriptor applyConfig = bufferConfig.addApply( "$.name<property-value>", "test-rule" );
-
-    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
-
-    JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
-    String output = IOUtils.toString( filter );
-
-    //System.out.println( "OUTPUT=" + output );
-
-    JsonAssert.with( output ).assertThat( "name<properties>[0].name<property>.name<property-name>", is( "test-name-1" ) );
-    JsonAssert.with( output ).assertThat( "name<properties>[0].name<property>.name<property-value>", is( "value:test-rule<test-value-1>" ) );
-    JsonAssert.with( output ).assertThat( "name<properties>[1].name<property>.name<property-name>", is( "test-name-2" ) );
-    JsonAssert.with( output ).assertThat( "name<properties>[1].name<property>.name<property-value>", is( "value:test-rule<test-value-2>" ) );
-    JsonAssert.with( output ).assertThat( "name<properties>[2].name<property>.name<property-name>", is( "test-name-3" ) );
-    JsonAssert.with( output ).assertThat( "name<properties>[2].name<property>.name<property-value>", is( "value:test-rule<test-value-3>" ) );
-  }
-
-  @Test
-  public void testBufferedMultiApply() throws IOException {
-    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties.json" );
-    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
-
-    //System.out.println( "INPUT=" + input );
-
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
-    UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "$.name<properties>" );
-    UrlRewriteFilterApplyDescriptor applyConfig = bufferConfig.addApply( "$.*.name<property>.name<property-value>", "test-rule" );
-
-    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
-
-    JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
-    String output = IOUtils.toString( filter );
-
-    //System.out.println( "OUTPUT=" + output );
-
-    JsonAssert.with( output ).assertThat( "name<properties>[0].name<property>.name<property-name>", is( "test-name-1" ) );
-    JsonAssert.with( output ).assertThat( "name<properties>[0].name<property>.name<property-value>", is( "value:test-rule<test-value-1>" ) );
-    JsonAssert.with( output ).assertThat( "name<properties>[1].name<property>.name<property-name>", is( "test-name-2" ) );
-    JsonAssert.with( output ).assertThat( "name<properties>[1].name<property>.name<property-value>", is( "value:test-rule<test-value-2>" ) );
-    JsonAssert.with( output ).assertThat( "name<properties>[2].name<property>.name<property-name>", is( "test-name-3" ) );
-    JsonAssert.with( output ).assertThat( "name<properties>[2].name<property>.name<property-value>", is( "value:test-rule<test-value-3>" ) );
-  }
-
-  @Test
-  public void testInvalidConfigShouldThrowException() throws Exception {
-    String input = "{\"test-name\":\"test-value\"}";
-
-    //System.out.println( "INPUT=" + input );
-
-    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
-    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
-    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "*/json" );
-    contentConfig.addApply( "/root/@url", "test-rule" );
-
-    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
-
-    try {
-      JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
-      IOUtils.toString( filter );
-      fail( "Should have thrown an IllegalArgumentException." );
-    } catch ( IOException e ) {
-      fail( "Should have thrown an IllegalArgumentException." );
-    } catch ( IllegalArgumentException e ) {
-      assertThat( e.getMessage(), containsString( "/root/@url" ) );
-    }
-  }
-
-  @Test
-  public void testEscapeCharactersBugKnox616() throws Exception {
-    String input, output;
-    JsonFilterReader filter;
-
-    input = "{ \"test-name\" : \"\\\"\" }";
-    filter = new NoopJsonFilterReader( new StringReader( input ), null );
-    output = IOUtils.toString( filter );
-    assertThat( output, is( "{\"test-name\":\"\\\"\"}" ) );
-
-    input = "{\"test-name\":\"\\b\"}";
-    filter = new NoopJsonFilterReader( new StringReader( input ), null );
-    output = IOUtils.toString( filter );
-    assertThat( output, is( "{\"test-name\":\"\\b\"}" ) );
-  }
-
-//  private void dump( ObjectMapper mapper, JsonGenerator generator, JsonNode node ) throws IOException {
-//    mapper.writeTree( generator, node );
-//    System.out.println();
-//  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/NoopJsonFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/NoopJsonFilterReader.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/NoopJsonFilterReader.java
deleted file mode 100644
index b9734e1..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/NoopJsonFilterReader.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.hadoop.gateway.filter.rewrite.impl.json;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-
-import java.io.IOException;
-import java.io.Reader;
-
-public class NoopJsonFilterReader extends JsonFilterReader {
-
-  public NoopJsonFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException {
-    super( reader, config );
-  }
-
-  protected String filterFieldName( String name ) {
-    return name;
-  }
-
-  protected String filterValueString( String name, String value, String rule ) {
-    return value;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/TestJsonFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/TestJsonFilterReader.java b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/TestJsonFilterReader.java
deleted file mode 100644
index e335429..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/TestJsonFilterReader.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.hadoop.gateway.filter.rewrite.impl.json;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-
-import java.io.IOException;
-import java.io.Reader;
-
-public class TestJsonFilterReader extends JsonFilterReader {
-
-  public TestJsonFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException {
-    super( reader, config );
-  }
-
-  protected String filterFieldName( String name ) {
-    return "name<" + name + ">";
-  }
-
-  protected String filterValueString( String name, String value, String rule ) {
-    return "value:" + rule + "<" + value + ">";
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/rewrite.xml b/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/rewrite.xml
deleted file mode 100644
index 0da28b2..0000000
--- a/gateway-provider-rewrite/src/test/java/org/apache/hadoop/gateway/filter/rewrite/impl/rewrite.xml
+++ /dev/null
@@ -1,106 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<!--
-   Licensed to the Apache Software Foundation (ASF) under one or more
-   contributor license agreements.  See the NOTICE file distributed with
-   this work for additional information regarding copyright ownership.
-   The ASF licenses this file to You under the Apache License, Version 2.0
-   (the "License"); you may not use this file except in compliance with
-   the License.  You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an "AS IS" BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
--->
-<rules>
-
-    <filter>
-        <role>rewrite</role>
-        <name>url-rewrite</name>
-        <class>org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteServletFilter</class>
-        <param><name>url.rule</name><value>{rule-name}</value></param>
-        <param><name>request.filter</name><value>{filters-name}</value></param>
-        <param><name>response.filter</name><value>{filters-name}</value></param>
-    </filter>
-
-    <!--
-    If no filter/rule specified it should attempt to filter everything like it did before.
-    -->
-
-    <filter name="WEBHDFS/request">
-        <content type="http/header">
-            <apply target="Location" rule="{rewrite-rule-name}"/>
-            <apply>...</apply>
-        </content>
-        <content type="http/cookie">
-            <apply target="hadoop.auth" rule="{rewrite-rule-name}"/>
-        </content>
-        <content type="*/json" name="{filter-impl-name}">
-            <select node="/config/property">
-                <choice source="name" pattern="YarnNodeManager ">
-                    <apply target="value[2]" rule="{rewrite-rule-name}"/>
-                    <apply target="value[3]" rule="{rewrite-rule-name}"/>
-                </choice>
-                <choice>...</choice>
-            </select>
-        </content>
-    </filter>
-
-    <!--
-    If there isn't a ContentFilter for the required type it is a failure.
-    The default ContentFilter ie type="*/*" can be present to transparently stream content.
-    The most specific content filter applies.
-
-    The most specific apply choice applies.
-    Missing rule="" uses URL pattern matching.
-    The rule="*" uses URL pattern matching.
-    The rule="-" prevents any rule being applied.
-
-    ContentParser
-    ContentParserFactory
-    ContentParserEvent
-
-    ContentFilter
-    ContentFilterFactory
-    ContentFilterAction
-    ContentFilterApply
-    ContentFilterChoice
-    ContentFilterSelect
-    ContentFilterSelectNode
-
-    ContentPath
-    ContentPathNode
-    ContentPathMatcher
-    ContentPathParser
-    -->
-
-    <rule dir="IN" name="WEBHDFS/webhdfs/namenode/root/inbound" pattern="*://*:*/**/webhdfs/{version}/?{**}">
-        <rewrite template="http://vm:50070/webhdfs/{version}/?{**}"/>
-    </rule>
-    <rule dir="IN" name="WEBHDFS/webhdfs/namenode/file/inbound" pattern="*://*:*/**/webhdfs/{version}/{path=**}?{**}">
-        <rewrite template="http://vm:50070/webhdfs/{version}/{path=**}?{**}"/>
-    </rule>
-    <rule dir="IN" name="WEBHDFS/webhdfs/datanode/inbound" pattern="*://*:*/**/webhdfs/data/{version}/{path=**}?**">
-        <decode-query/>
-        <match pattern="*://*:*/**/webhdfs/data/{version}/{path=**}?{host}&amp;{port}&amp;{**}"/>
-        <rewrite template="http://{host}:{port}/{path=**}?{**}"/>
-    </rule>
-    <rule dir="OUT" name="WEBHDFS/webhdfs/datanode/outbound" pattern="*://*:*/**?**">
-        <match pattern="*://{host}:{port}/{path=**}?{**}"/>
-        <rewrite template="{$frontend[url]}/webhdfs/data/{version}/{path=**}?{host}&amp;{port}&amp;{**}"/>
-        <encode-query/>
-    </rule>
-    <rule dir="IN" name="WEBHCAT/webhcat/request" pattern="*://*:*/**/templeton/{version}/{path=**}?{**}">
-        <rewrite template="http://vm:50111/templeton/{version}/{path=**}?{**}"/>
-    </rule>
-    <rule dir="IN" name="OOZIE/oozie/root/inbound" pattern="*://*:*/**/oozie/{**}?{**}">
-        <rewrite template="http://vm:11000/oozie/{**}?{**}"/>
-    </rule>
-    <rule dir="IN" name="OOZIE/oozie/v1/inbound" pattern="*://*:*/**/oozie/v1/{**}?{**}">
-        <rewrite template="http://vm:11000/oozie/v1/{**}?{**}"/>
-    </rule>
-
-</rules>
\ No newline at end of file


[64/64] knox git commit: KNOX-998 - Some more refactoring, making sure all the Unit Tests run and build passes !

Posted by mo...@apache.org.
KNOX-998 - Some more refactoring, making sure all the Unit Tests run and build passes !


Project: http://git-wip-us.apache.org/repos/asf/knox/repo
Commit: http://git-wip-us.apache.org/repos/asf/knox/commit/2e6713b6
Tree: http://git-wip-us.apache.org/repos/asf/knox/tree/2e6713b6
Diff: http://git-wip-us.apache.org/repos/asf/knox/diff/2e6713b6

Branch: refs/heads/KNOX-998-Package_Restructuring
Commit: 2e6713b6c33b54533e6d81ab575ce292aaa43f0d
Parents: 912c536
Author: Sandeep More <mo...@apache.org>
Authored: Thu Aug 31 16:39:06 2017 -0400
Committer: Sandeep More <mo...@apache.org>
Committed: Thu Aug 31 16:39:06 2017 -0400

----------------------------------------------------------------------
 .gitignore                                      |   2 +-
 .../applications/knoxauth/app/redirecting.jsp   |   2 +-
 .../src/main/resources/META-INF/launcher.cfg    |   2 +-
 gateway-demo-ldap/pom.xml                       |   4 +-
 .../src/main/resources/log4j.properties         |   4 +-
 .../ha/dispatch/i18n/HaDispatchMessages.java    |   2 +-
 .../ha/provider/impl/i18n/HaMessages.java       |   2 +-
 .../knox/gateway/IdentityAsserterMessages.java  |   2 +-
 .../gateway/ConcatIdentityAsserterMessages.java |   2 +-
 ...adoopGroupProviderDeploymentContributor.java |   2 +-
 .../filter/HadoopGroupProviderMessages.java     |   2 +-
 .../knox/gateway/IdentityAsserterMessages.java  |   2 +-
 .../hostmap/impl/HostmapFunctionProcessor.java  |   4 +-
 .../ServiceMappedHostFunctionProcessor.java     |   4 +-
 .../gateway/encrypturi/EncryptUriMessages.java  |   2 +-
 .../securequery/SecureQueryMessages.java        |   2 +-
 .../filter/rewrite/i18n/UrlRewriteMessages.java |   2 +-
 .../src/test/resources/log4j.properties         |   8 +-
 .../AnonymousAuthDeploymentContributor.java     |   2 +-
 .../impl/AclsAuthzDeploymentContributor.java    |   2 +-
 .../filter/AclsAuthorizationMessages.java       |   2 +-
 .../gateway/hadoopauth/HadoopAuthMessages.java  |   2 +-
 .../provider/federation/jwt/JWTMessages.java    |   2 +-
 .../knox/gateway/pac4j/Pac4jMessages.java       |   2 +-
 .../pac4j/filter/Pac4jIdentityAdapter.java      |  12 +-
 .../gateway/picketlink/PicketlinkMessages.java  |   2 +-
 .../knox/gateway/preauth/PreAuthMessages.java   |   2 +-
 .../deploy/HeaderPreAuthContributor.java        |   2 +-
 .../HeaderPreAuthFederationFilterTest.java      |   2 +-
 .../provider/federation/PreAuthServiceTest.java |   2 +-
 .../deploy/impl/ShiroDeploymentContributor.java |   6 +-
 .../shirorealm/impl/i18n/KnoxShiroMessages.java |   2 +-
 .../gateway/webappsec/WebAppSecMessages.java    |   2 +-
 .../webappsec/deploy/WebAppSecContributor.java  |   5 +-
 .../home/conf/gateway-log4j.properties          |  20 +-
 .../home/conf/knoxcli-log4j.properties          |   4 +-
 .../src/main/resources/META-INF/launcher.cfg    |   2 +-
 .../services/metrics/impl/instr/InstrUtils.java |  54 ------
 .../apache/knox/gateway/GatewayMessages.java    |   2 +-
 .../ServiceDefinitionDeploymentContributor.java |   2 +-
 .../gateway/services/CLIGatewayServices.java    |   4 +-
 .../services/DefaultGatewayServices.java        |   4 +-
 .../GatewayServicesContextListener.java         |   4 +-
 .../hostmap/impl/DefaultHostMapperService.java  |   6 +-
 .../security/impl/DefaultAliasService.java      |   6 +-
 .../impl/DefaultTokenAuthorityService.java      |   8 +-
 .../knox/gateway/trace/AccessHandler.java       |   2 +-
 .../apache/knox/gateway/trace/TraceHandler.java |   2 +-
 .../org/apache/knox/gateway/util/KnoxCLI.java   |   4 +-
 .../websockets/WebsocketLogMessages.java        |   2 +-
 .../src/main/resources/conf/log4j.properties    |   2 +-
 .../org/apache/knox/gateway/GatewayServer.xml   |   2 +-
 .../org/apache/knox/gateway/GatewayFuncTest.xml |   4 +-
 .../apache/knox/gateway/util/KnoxCLITest.java   |   4 +-
 .../src/test/resources/conf-demo/conf/shiro.ini |   2 +-
 .../conf-demo/conf/topologies/admin.xml         |   4 +-
 .../conf-demo/conf/topologies/sandbox.xml       |   4 +-
 .../src/test/resources/log4j.properties         |   2 +-
 .../org/apache/knox/gateway/GatewayFuncTest.xml |   2 +-
 .../xml/simple-topology-ambari-format.conf      |   2 +-
 .../xml/simple-topology-knox-format.xml         |   2 +-
 gateway-server/src/test/resources/shiro.ini     |   2 +-
 .../AdminServiceDeploymentContributor.java      |   2 +-
 .../resources/services/ambari/2.2.0/service.xml |   2 +-
 .../services/ambariui/2.2.0/service.xml         |   2 +-
 .../services/atlas-api/0.8.0/service.xml        |   2 +-
 .../resources/services/atlas/0.8.0/service.xml  |   2 +-
 .../resources/services/hbase/0.98.0/service.xml |   2 +-
 .../services/hbaseui/1.1.0/service.xml          |   2 +-
 .../resources/services/hdfsui/2.7.0/service.xml |   2 +-
 .../resources/services/hive/0.13.0/service.xml  |   2 +-
 .../resources/services/ranger/0.5.0/service.xml |   2 +-
 .../services/rangerui/0.5.0/service.xml         |   2 +-
 .../resources/services/solr/5.5.0/service.xml   |   2 +-
 .../resources/services/storm/0.9.3/service.xml  |   2 +-
 .../services/webhdfs/2.4.0/service.xml          |   2 +-
 .../services/yarn-rm/2.5.0/service.xml          |   2 +-
 .../resources/services/yarnui/2.7.0/service.xml |   2 +-
 .../services/zeppelinui/0.6.0/service.xml       |   2 +-
 .../definition/ServiceDefinitionTest.java       |   8 +-
 .../resources/services/foo/1.0.0/service.xml    |   2 +-
 .../service/health/HealthServiceMessages.java   |   2 +-
 .../HealthServiceDeploymentContributor.java     |   2 +-
 .../service/knoxsso/KnoxSSOMessages.java        |   2 +-
 .../KnoxSSOServiceDeploymentContributor.java    |   2 +-
 .../service/knoxsso/KnoxSSOutMessages.java      |   2 +-
 .../KnoxSSOutServiceDeploymentContributor.java  |   2 +-
 .../service/knoxtoken/TokenServiceMessages.java |   2 +-
 .../TokenServiceDeploymentContributor.java      |   2 +-
 .../apache/knox/gateway/rm/i18n/RMMessages.java |   2 +-
 .../ServiceTestDeploymentContributor.java       |   2 +-
 .../VaultServiceDeploymentContributor.java      |   2 +-
 .../knox/gateway/hdfs/i18n/WebHdfsMessages.java |   2 +-
 .../src/main/resources/META-INF/launcher.cfg    |   2 +-
 gateway-shell-release/home/bin/knoxshell.sh     |   6 +-
 .../main/resources/samples/ExampleHBase.groovy  |   6 +-
 .../samples/ExampleOozieWorkflow.groovy         |   8 +-
 .../resources/samples/ExampleWebHCatJob.groovy  |   8 +-
 .../samples/ExampleWebHCatJobTeragen.groovy     |   8 +-
 .../resources/samples/ExampleWebHCatPig.groovy  |   8 +-
 .../samples/ExampleWebHCatQueue.groovy          |   6 +-
 .../samples/ExampleWebHCatSqoop.groovy          |   8 +-
 .../resources/samples/ExampleWebHdfsLs.groovy   |   6 +-
 .../samples/ExampleWebHdfsPutGet.groovy         |   6 +-
 .../samples/SampleComplexCommand.groovy         |   6 +-
 .../main/resources/samples/SampleScript.groovy  |   4 +-
 .../main/resources/samples/SampleService.groovy |   2 +-
 .../samples/SampleSimpleCommand.groovy          |   6 +-
 .../HiveJDBCSample.groovy                       |   2 +-
 .../groovy/jdbc/sandbox/HiveJDBCSample.groovy   |   2 +-
 .../HiveJDBCSample.java                         |   2 +-
 .../hive/java/jdbc/sandbox/HiveJDBCSample.java  |   2 +-
 .../samples/sandbox-with-knox-inside.xml        |   4 +-
 .../apache/knox/gateway/SpiGatewayMessages.java |   2 +-
 .../knox/gateway/config/GatewayConfig.java      |   2 +-
 .../ServiceDeploymentContributorBase.java       |   2 +-
 .../knox/gateway/i18n/GatewaySpiMessages.java   |   2 +-
 .../principal/SimplePrincipalMapper.java        |   6 +-
 .../knox/gateway/services/GatewayServices.java  |   4 +-
 .../token/impl/JWTProviderMessages.java         |   2 +-
 .../gateway/topology/topology_binding-json.xml  |   2 +-
 .../gateway/topology/topology_binding-xml.xml   |   2 +-
 .../apache/knox/gateway/SecureClusterTest.java  |   2 +-
 .../java/org/apache/knox/gateway/ShellTest.java |   2 +-
 .../knox/gateway/GatewayBasicFuncTest.java      |  18 +-
 .../knox/gateway/GatewayHealthFuncTest.java     |   2 +-
 .../GatewayPortMappingDisableFeatureTest.java   |   2 +-
 .../gateway/GatewayPortMappingFuncTest.java     |   2 +-
 .../TestJerseyServiceDeploymentContributor.java |   2 +-
 .../apache/knox/gateway/WebHdfsHaFuncTest.java  |   2 +-
 .../deploy/DeploymentFactoryFuncTest.java       | 194 +++++++++----------
 .../src/test/resources/log4j.properties         |   8 +-
 .../solr/query_response.xml                     |  20 --
 .../gateway/GatewayBasicFuncTest/changes.txt    |   2 +-
 .../solr/query_response.xml                     |  20 ++
 gateway-test/src/test/resources/shiro.ini       |   2 +-
 .../gateway/i18n/GatewayUtilCommonMessages.java |   2 +-
 .../knox/gateway/util/urltemplate/Messages.java |   2 +-
 .../util/urltemplate/MatcherTest.java.orig      |   2 +-
 .../gateway/util/urltemplate/RewriterTest.java  |   2 +-
 .../src/main/resources/META-INF/launcher.cfg    |   2 +-
 141 files changed, 345 insertions(+), 394 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/.gitignore
----------------------------------------------------------------------
diff --git a/.gitignore b/.gitignore
index 61d27c8..b518a2f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -31,7 +31,7 @@ target
 install
 patch
 candidate
-org.apache.hadoop.gateway.security.EmbeddedApacheDirectoryServer/
+org.apache.knox.gateway.security.EmbeddedApacheDirectoryServer/
 velocity.log
 *.pyc
 *.py~

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-applications/src/main/resources/applications/knoxauth/app/redirecting.jsp
----------------------------------------------------------------------
diff --git a/gateway-applications/src/main/resources/applications/knoxauth/app/redirecting.jsp b/gateway-applications/src/main/resources/applications/knoxauth/app/redirecting.jsp
index e3a0673..f9dc732 100644
--- a/gateway-applications/src/main/resources/applications/knoxauth/app/redirecting.jsp
+++ b/gateway-applications/src/main/resources/applications/knoxauth/app/redirecting.jsp
@@ -40,7 +40,7 @@
 
         <script type="text/javascript" src="js/knoxauth.js"></script>
 	<%
-        Topology topology = (Topology)request.getSession().getServletContext().getAttribute("org.apache.hadoop.gateway.topology");
+        Topology topology = (Topology)request.getSession().getServletContext().getAttribute("org.apache.knox.gateway.topology");
         String whitelist = null;
 	    Collection services = topology.getServices();
         for (Object service : services) {

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-demo-ldap-launcher/src/main/resources/META-INF/launcher.cfg
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap-launcher/src/main/resources/META-INF/launcher.cfg b/gateway-demo-ldap-launcher/src/main/resources/META-INF/launcher.cfg
index 3a06075..35b32f3 100644
--- a/gateway-demo-ldap-launcher/src/main/resources/META-INF/launcher.cfg
+++ b/gateway-demo-ldap-launcher/src/main/resources/META-INF/launcher.cfg
@@ -12,6 +12,6 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-main.class = org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer
+main.class = org.apache.knox.gateway.security.ldap.SimpleLdapDirectoryServer
 class.path = ../lib/*.jar;../dep/*.jar;../ext;../ext/*.jar
 log4j.configuration=${launcher.dir}/../conf/${launcher.name}-log4j.properties

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-demo-ldap/pom.xml
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap/pom.xml b/gateway-demo-ldap/pom.xml
index a1ddba5..5936a20 100644
--- a/gateway-demo-ldap/pom.xml
+++ b/gateway-demo-ldap/pom.xml
@@ -52,7 +52,7 @@
                     </execution>
                 </executions>
                 <configuration>
-                    <mainClass>org.apache.hadoop.gateway.security.EmbeddedApacheDirectoryServer</mainClass>
+                    <mainClass>org.apache.knox.gateway.security.EmbeddedApacheDirectoryServer</mainClass>
                 </configuration>
             </plugin>
         </plugins>
@@ -74,7 +74,7 @@
                                 <transformer
                                         implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                     <manifestEntries>
-                                        <Main-Class>org.apache.hadoop.gateway.security.EmbeddedApacheDirectoryServer
+                                        <Main-Class>org.apache.knox.gateway.security.EmbeddedApacheDirectoryServer
                                         </Main-Class>
                                     </manifestEntries>
                                 </transformer>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-demo-ldap/src/main/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/gateway-demo-ldap/src/main/resources/log4j.properties b/gateway-demo-ldap/src/main/resources/log4j.properties
index 40b5546..529380f 100644
--- a/gateway-demo-ldap/src/main/resources/log4j.properties
+++ b/gateway-demo-ldap/src/main/resources/log4j.properties
@@ -21,5 +21,5 @@ log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
 log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %-5p %m%n
 
 #log4j.logger.org.apache.directory=INFO
-#log4j.logger.org.apache.hadoop.gateway=INFO
-#log4j.logger.org.apache.hadoop.gateway=DEBUG
\ No newline at end of file
+#log4j.logger.org.apache.knox.gateway=INFO
+#log4j.logger.org.apache.knox.gateway=DEBUG
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/dispatch/i18n/HaDispatchMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/dispatch/i18n/HaDispatchMessages.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/dispatch/i18n/HaDispatchMessages.java
index 8efc773..c3bb50c 100644
--- a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/dispatch/i18n/HaDispatchMessages.java
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/dispatch/i18n/HaDispatchMessages.java
@@ -22,7 +22,7 @@ import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 import org.apache.knox.gateway.i18n.messages.StackTrace;
 
-@Messages(logger = "org.apache.hadoop.gateway")
+@Messages(logger = "org.apache.knox.gateway")
 public interface HaDispatchMessages {
   @Message(level = MessageLevel.INFO, text = "Initializing Ha Dispatch for: {0}")
   void initializingForResourceRole(String resourceRole);

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/i18n/HaMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/i18n/HaMessages.java b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/i18n/HaMessages.java
index 3848c46..018d5c6 100644
--- a/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/i18n/HaMessages.java
+++ b/gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/i18n/HaMessages.java
@@ -21,7 +21,7 @@ import org.apache.knox.gateway.i18n.messages.Message;
 import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 
-@Messages(logger = "org.apache.hadoop.gateway")
+@Messages(logger = "org.apache.knox.gateway")
 public interface HaMessages {
 
    @Message(level = MessageLevel.ERROR, text = "Failed to Write HA Descriptor: {0}")

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java
index e614c25..196e91e 100644
--- a/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java
+++ b/gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java
@@ -22,7 +22,7 @@ import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 import org.apache.knox.gateway.i18n.messages.StackTrace;
 
-@Messages(logger="org.apache.hadoop.gateway")
+@Messages(logger="org.apache.knox.gateway")
 public interface IdentityAsserterMessages {
 
   @Message( level = MessageLevel.WARN, text = "Skipping unencodable parameter {0}={1}, {2}: {3}" )

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/ConcatIdentityAsserterMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/ConcatIdentityAsserterMessages.java b/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/ConcatIdentityAsserterMessages.java
index a1d9db1..341e52d 100644
--- a/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/ConcatIdentityAsserterMessages.java
+++ b/gateway-provider-identity-assertion-concat/src/main/java/org/apache/knox/gateway/ConcatIdentityAsserterMessages.java
@@ -22,7 +22,7 @@ import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 import org.apache.knox.gateway.i18n.messages.StackTrace;
 
-@Messages(logger="org.apache.hadoop.gateway")
+@Messages(logger="org.apache.knox.gateway")
 public interface ConcatIdentityAsserterMessages {
 
   @Message( level = MessageLevel.WARN, text = "Skipping unencodable parameter {0}={1}, {2}: {3}" )

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributor.java b/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributor.java
index d04713d..d9388a1 100644
--- a/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributor.java
+++ b/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderDeploymentContributor.java
@@ -53,7 +53,7 @@ public class HadoopGroupProviderDeploymentContributor
   /*
    * (non-Javadoc)
    * 
-   * @see org.apache.hadoop.gateway.identityasserter.common.filter.
+   * @see org.apache.knox.gateway.identityasserter.common.filter.
    * AbstractIdentityAsserterDeploymentContributor#getFilterClassname()
    */
   @Override

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderMessages.java b/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderMessages.java
index 311b00a..c46a987 100644
--- a/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderMessages.java
+++ b/gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderMessages.java
@@ -28,7 +28,7 @@ import org.apache.knox.gateway.i18n.messages.StackTrace;
  * @since 0.11
  */
 
-@Messages(logger="org.apache.hadoop.gateway")
+@Messages(logger="org.apache.knox.gateway")
 public interface HadoopGroupProviderMessages {
 
   @Message( level = MessageLevel.ERROR, text = "Error getting groups for principal {0}" )

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java b/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java
index e614c25..196e91e 100644
--- a/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java
+++ b/gateway-provider-identity-assertion-pseudo/src/main/java/org/apache/knox/gateway/IdentityAsserterMessages.java
@@ -22,7 +22,7 @@ import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 import org.apache.knox.gateway.i18n.messages.StackTrace;
 
-@Messages(logger="org.apache.hadoop.gateway")
+@Messages(logger="org.apache.knox.gateway")
 public interface IdentityAsserterMessages {
 
   @Message( level = MessageLevel.WARN, text = "Skipping unencodable parameter {0}={1}, {2}: {3}" )

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessor.java b/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessor.java
index 5b16b47..7fe9eef 100644
--- a/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessor.java
+++ b/gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessor.java
@@ -74,10 +74,10 @@ public class HostmapFunctionProcessor
       result = new ArrayList<String>( parameters.size() );
       for( String parameter : parameters ) {
         switch( context.getDirection() ) {
-          case UrlRewriter.Direction.IN:
+          case IN:
             parameter = hostMapper.resolveInboundHostName( parameter );
             break;
-          case UrlRewriter.Direction.OUT:
+          case OUT:
             parameter = hostMapper.resolveOutboundHostName( parameter );
             break;
         }

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessor.java b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessor.java
index 39c162c..e12dc62 100644
--- a/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessor.java
+++ b/gateway-provider-rewrite-func-service-registry/src/main/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessor.java
@@ -66,10 +66,10 @@ public class ServiceMappedHostFunctionProcessor
             String hostStr = host.getFirstValue().getPattern();
             if( hostmap != null ) {
               switch( context.getDirection() ) {
-                case UrlRewriter.Direction.IN:
+                case IN:
                   parameter = hostmap.resolveInboundHostName( hostStr );
                   break;
-                case UrlRewriter.Direction.OUT:
+                case OUT:
                   parameter = hostmap.resolveOutboundHostName( hostStr );
                   break;
               }

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/EncryptUriMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/EncryptUriMessages.java b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/EncryptUriMessages.java
index afcc384..37c7fbc 100644
--- a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/EncryptUriMessages.java
+++ b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/EncryptUriMessages.java
@@ -22,7 +22,7 @@ import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 import org.apache.knox.gateway.i18n.messages.StackTrace;
 
-@Messages(logger="org.apache.hadoop.gateway.encrypturi")
+@Messages(logger="org.apache.knox.gateway.encrypturi")
 public interface EncryptUriMessages {
 
   @Message( level = MessageLevel.ERROR, text = "Failed to create or verify the presence of a password for URL encryption: {0}" )

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryMessages.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryMessages.java
index 62f0e9f..2375011 100644
--- a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryMessages.java
+++ b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/knox/gateway/securequery/SecureQueryMessages.java
@@ -22,7 +22,7 @@ import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 import org.apache.knox.gateway.i18n.messages.StackTrace;
 
-@Messages(logger="org.apache.hadoop.gateway.securequery")
+@Messages(logger="org.apache.knox.gateway.securequery")
 public interface SecureQueryMessages {
 
   @Message( level = MessageLevel.ERROR, text = "Failed to create or verify the presence of a password for query string encryption: {0}" )

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/i18n/UrlRewriteMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/i18n/UrlRewriteMessages.java b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/i18n/UrlRewriteMessages.java
index 35247c9..ad8b60e 100644
--- a/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/i18n/UrlRewriteMessages.java
+++ b/gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/i18n/UrlRewriteMessages.java
@@ -25,7 +25,7 @@ import org.apache.knox.gateway.i18n.messages.Messages;
 import org.apache.knox.gateway.i18n.messages.StackTrace;
 import org.apache.knox.gateway.util.urltemplate.Template;
 
-@Messages(logger="org.apache.hadoop.gateway")
+@Messages(logger="org.apache.knox.gateway")
 public interface UrlRewriteMessages {
 
   @Message( level = MessageLevel.DEBUG, text = "Failed to parse value as URL: {0}" )

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-rewrite/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/log4j.properties b/gateway-provider-rewrite/src/test/resources/log4j.properties
index c2cbce6..be84440 100644
--- a/gateway-provider-rewrite/src/test/resources/log4j.properties
+++ b/gateway-provider-rewrite/src/test/resources/log4j.properties
@@ -22,10 +22,10 @@ log4j.appender.stdout=org.apache.log4j.ConsoleAppender
 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
 log4j.appender.stdout.layout.ConversionPattern=%5p [%c] %m%n
 
-#log4j.logger.org.apache.hadoop.gateway=DEBUG
-#log4j.logger.org.apache.hadoop.gateway.http=TRACE
-#log4j.logger.org.apache.hadoop.gateway.http.request.body=OFF
-#log4j.logger.org.apache.hadoop.gateway.http.response.body=OFF
+#log4j.logger.org.apache.knox.gateway=DEBUG
+#log4j.logger.org.apache.knox.gateway.http=TRACE
+#log4j.logger.org.apache.knox.gateway.http.request.body=OFF
+#log4j.logger.org.apache.knox.gateway.http.response.body=OFF
 
 #log4j.logger.org.apache.directory=DEBUG
 #log4j.logger.org.eclipse.jetty=DEBUG

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-authc-anon/src/main/java/org/apache/knox/gateway/deploy/AnonymousAuthDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authc-anon/src/main/java/org/apache/knox/gateway/deploy/AnonymousAuthDeploymentContributor.java b/gateway-provider-security-authc-anon/src/main/java/org/apache/knox/gateway/deploy/AnonymousAuthDeploymentContributor.java
index e0c0609..533064e 100755
--- a/gateway-provider-security-authc-anon/src/main/java/org/apache/knox/gateway/deploy/AnonymousAuthDeploymentContributor.java
+++ b/gateway-provider-security-authc-anon/src/main/java/org/apache/knox/gateway/deploy/AnonymousAuthDeploymentContributor.java
@@ -32,7 +32,7 @@ public class AnonymousAuthDeploymentContributor extends ProviderDeploymentContri
   private static final String ROLE = "authentication";
   private static final String NAME = "Anonymous";
 
-  private static final String FILTER_CLASSNAME = "AnonymousAuthFilter";
+  private static final String FILTER_CLASSNAME = "org.apache.knox.gateway.filter.AnonymousAuthFilter";
 
   @Override
   public String getRole() {

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/deploy/impl/AclsAuthzDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/deploy/impl/AclsAuthzDeploymentContributor.java b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/deploy/impl/AclsAuthzDeploymentContributor.java
index fc5e549..e15ddfe 100644
--- a/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/deploy/impl/AclsAuthzDeploymentContributor.java
+++ b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/deploy/impl/AclsAuthzDeploymentContributor.java
@@ -31,7 +31,7 @@ import java.util.Map.Entry;
 
 public class AclsAuthzDeploymentContributor extends ProviderDeploymentContributorBase {
 
-  private static final String FILTER_CLASSNAME = "AclsAuthorizationFilter";
+  private static final String FILTER_CLASSNAME = "org.apache.knox.gateway.filter.AclsAuthorizationFilter";
 
   @Override
   public String getRole() {

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationMessages.java b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationMessages.java
index 206348d..7104443 100644
--- a/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationMessages.java
+++ b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationMessages.java
@@ -21,7 +21,7 @@ import org.apache.knox.gateway.i18n.messages.Message;
 import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 
-@Messages(logger="org.apache.hadoop.gateway")
+@Messages(logger="org.apache.knox.gateway")
 public interface AclsAuthorizationMessages {
 
   @Message( level = MessageLevel.INFO, text = "Initializing AclsAuthz Provider for: {0}" )

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/HadoopAuthMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/HadoopAuthMessages.java b/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/HadoopAuthMessages.java
index 6141686..57755a5 100755
--- a/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/HadoopAuthMessages.java
+++ b/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/HadoopAuthMessages.java
@@ -21,7 +21,7 @@ import org.apache.knox.gateway.i18n.messages.Message;
 import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 
-@Messages(logger="org.apache.hadoop.gateway.provider.global.hadoopauth")
+@Messages(logger="org.apache.knox.gateway.provider.global.hadoopauth")
 public interface HadoopAuthMessages {
   
   @Message( level = MessageLevel.INFO, text = "Initializing Hadoop Auth Property, name: {0},  value: {1}" )

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/JWTMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/JWTMessages.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/JWTMessages.java
index 39df1bb..e1e0dcb 100644
--- a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/JWTMessages.java
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/JWTMessages.java
@@ -23,7 +23,7 @@ import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 import org.apache.knox.gateway.i18n.messages.StackTrace;
 
-@Messages(logger="org.apache.hadoop.gateway.provider.federation.jwt")
+@Messages(logger="org.apache.knox.gateway.provider.federation.jwt")
 public interface JWTMessages {
   @Message( level = MessageLevel.WARN, text = "Failed to validate the audience attribute." )
   void failedToValidateAudience();

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/Pac4jMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/Pac4jMessages.java b/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/Pac4jMessages.java
index 32e07e6..78b3c56 100644
--- a/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/Pac4jMessages.java
+++ b/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/Pac4jMessages.java
@@ -26,7 +26,7 @@ import org.apache.knox.gateway.i18n.messages.Messages;
  *
  * @since 0.8.0
  */
-@Messages(logger="org.apache.hadoop.gateway.pac4j")
+@Messages(logger="org.apache.knox.gateway.pac4j")
 public interface Pac4jMessages {
 
   @Message( level = MessageLevel.ERROR, text = "pac4j callback URL required")

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/filter/Pac4jIdentityAdapter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/filter/Pac4jIdentityAdapter.java b/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/filter/Pac4jIdentityAdapter.java
index 87d0e8e..90395f1 100644
--- a/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/filter/Pac4jIdentityAdapter.java
+++ b/gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/filter/Pac4jIdentityAdapter.java
@@ -17,16 +17,15 @@
  */
 package org.apache.knox.gateway.pac4j.filter;
 
-import org.apache.hadoop.gateway.audit.api.*;
 import org.apache.knox.gateway.audit.api.Action;
 import org.apache.knox.gateway.audit.api.ActionOutcome;
+import org.apache.knox.gateway.audit.api.AuditService;
+import org.apache.knox.gateway.audit.api.AuditServiceFactory;
 import org.apache.knox.gateway.audit.api.Auditor;
 import org.apache.knox.gateway.audit.api.ResourceType;
 import org.apache.knox.gateway.audit.log4j.audit.AuditConstants;
 import org.apache.knox.gateway.filter.AbstractGatewayFilter;
 import org.apache.knox.gateway.security.PrimaryPrincipal;
-import org.apache.knox.gateway.audit.api.AuditService;
-import org.apache.knox.gateway.audit.api.AuditServiceFactory;
 import org.pac4j.core.config.ConfigSingleton;
 import org.pac4j.core.context.J2EContext;
 import org.pac4j.core.profile.ProfileManager;
@@ -35,7 +34,12 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import javax.security.auth.Subject;
-import javax.servlet.*;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/PicketlinkMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/PicketlinkMessages.java b/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/PicketlinkMessages.java
index bcb347c..86f2854 100644
--- a/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/PicketlinkMessages.java
+++ b/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/PicketlinkMessages.java
@@ -22,7 +22,7 @@ import org.apache.knox.gateway.i18n.messages.MessageLevel;
 import org.apache.knox.gateway.i18n.messages.Messages;
 import org.apache.knox.gateway.i18n.messages.StackTrace;
 
-@Messages(logger="org.apache.hadoop.gateway.picketlink")
+@Messages(logger="org.apache.knox.gateway.picketlink")
 public interface PicketlinkMessages {
 
   @Message( level = MessageLevel.DEBUG, text = "Found Original URL in reequest: {0}")

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/PreAuthMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/PreAuthMessages.java b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/PreAuthMessages.java
index dfe4ca9..adcc5e2 100644
--- a/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/PreAuthMessages.java
+++ b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/PreAuthMessages.java
@@ -19,6 +19,6 @@ package org.apache.knox.gateway.preauth;
 
 import org.apache.knox.gateway.i18n.messages.Messages;
 
-@Messages(logger="org.apache.hadoop.gateway.provider.global.csrf")
+@Messages(logger="org.apache.knox.gateway.provider.global.csrf")
 public interface PreAuthMessages {
 }

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/deploy/HeaderPreAuthContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/deploy/HeaderPreAuthContributor.java b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/deploy/HeaderPreAuthContributor.java
index 2a5cebd..e9177e8 100644
--- a/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/deploy/HeaderPreAuthContributor.java
+++ b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/deploy/HeaderPreAuthContributor.java
@@ -33,7 +33,7 @@ public class HeaderPreAuthContributor extends
     ProviderDeploymentContributorBase {
   private static final String ROLE = "federation";
   private static final String NAME = "HeaderPreAuth";
-  private static final String PREAUTH_FILTER_CLASSNAME = "HeaderPreAuthFederationFilter";
+  private static final String PREAUTH_FILTER_CLASSNAME = "org.apache.knox.gateway.preauth.filter.HeaderPreAuthFederationFilter";
 
   @Override
   public String getRole() {

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/HeaderPreAuthFederationFilterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/HeaderPreAuthFederationFilterTest.java b/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/HeaderPreAuthFederationFilterTest.java
index efa0774..79e6fe8 100644
--- a/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/HeaderPreAuthFederationFilterTest.java
+++ b/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/HeaderPreAuthFederationFilterTest.java
@@ -18,7 +18,7 @@
 package org.apache.knox.gateway.provider.federation;
 
 import junit.framework.TestCase;
-import org.apache.hadoop.gateway.preauth.filter.*;
+import org.apache.knox.gateway.preauth.filter.*;
 import org.apache.knox.gateway.preauth.filter.DefaultValidator;
 import org.apache.knox.gateway.preauth.filter.HeaderPreAuthFederationFilter;
 import org.apache.knox.gateway.preauth.filter.IPValidator;

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/PreAuthServiceTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/PreAuthServiceTest.java b/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/PreAuthServiceTest.java
index 5a5cced..bf023e7 100644
--- a/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/PreAuthServiceTest.java
+++ b/gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/PreAuthServiceTest.java
@@ -18,7 +18,7 @@
 package org.apache.knox.gateway.provider.federation;
 
 import junit.framework.TestCase;
-import org.apache.hadoop.gateway.preauth.filter.*;
+import org.apache.knox.gateway.preauth.filter.*;
 import org.apache.knox.gateway.preauth.filter.DefaultValidator;
 import org.apache.knox.gateway.preauth.filter.IPValidator;
 import org.apache.knox.gateway.preauth.filter.PreAuthService;

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/deploy/impl/ShiroDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/deploy/impl/ShiroDeploymentContributor.java b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/deploy/impl/ShiroDeploymentContributor.java
index 111b13b..26e6deb 100644
--- a/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/deploy/impl/ShiroDeploymentContributor.java
+++ b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/deploy/impl/ShiroDeploymentContributor.java
@@ -37,9 +37,9 @@ public class ShiroDeploymentContributor extends ProviderDeploymentContributorBas
 
   private static final String LISTENER_CLASSNAME = "org.apache.shiro.web.env.EnvironmentLoaderListener";
   private static final String SHIRO_FILTER_CLASSNAME = "org.apache.shiro.web.servlet.ShiroFilter";
-  private static final String POST_FILTER_CLASSNAME = "ShiroSubjectIdentityAdapter";
-  private static final String COOKIE_FILTER_CLASSNAME = "ResponseCookieFilter";
-  private static final String REDIRECT_FILTER_CLASSNAME = "RedirectToUrlFilter";
+  private static final String POST_FILTER_CLASSNAME = "org.apache.knox.gateway.filter.ShiroSubjectIdentityAdapter";
+  private static final String COOKIE_FILTER_CLASSNAME = "org.apache.knox.gateway.filter.ResponseCookieFilter";
+  private static final String REDIRECT_FILTER_CLASSNAME = "org.apache.knox.gateway.filter.RedirectToUrlFilter";
   private static final String SESSION_TIMEOUT = "sessionTimeout";
   private static final String REMEMBER_ME = "rememberme";
   private static final String SHRIO_CONFIG_FILE_NAME = "shiro.ini";

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/impl/i18n/KnoxShiroMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/impl/i18n/KnoxShiroMessages.java b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/impl/i18n/KnoxShiroMessages.java
index 736a544..fb5bba2 100644
--- a/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/impl/i18n/KnoxShiroMessages.java
+++ b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/impl/i18n/KnoxShiroMessages.java
@@ -26,7 +26,7 @@ import org.apache.knox.gateway.i18n.messages.StackTrace;
 import org.apache.shiro.authc.AuthenticationToken;
 import org.apache.shiro.subject.Subject;
 
-@Messages(logger = "org.apache.hadoop.gateway")
+@Messages(logger = "org.apache.knox.gateway")
 public interface KnoxShiroMessages {
 
   @Message(level = MessageLevel.ERROR, text = "Shiro unable to login: {0}")

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/WebAppSecMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/WebAppSecMessages.java b/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/WebAppSecMessages.java
index 8ea2467..0f70b66 100644
--- a/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/WebAppSecMessages.java
+++ b/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/WebAppSecMessages.java
@@ -19,6 +19,6 @@ package org.apache.knox.gateway.webappsec;
 
 import org.apache.knox.gateway.i18n.messages.Messages;
 
-@Messages(logger="org.apache.hadoop.gateway.provider.global.csrf")
+@Messages(logger="org.apache.knox.gateway.provider.global.csrf")
 public interface WebAppSecMessages {
 }

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/deploy/WebAppSecContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/deploy/WebAppSecContributor.java b/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/deploy/WebAppSecContributor.java
index 57d76fa..383dffe 100644
--- a/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/deploy/WebAppSecContributor.java
+++ b/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/deploy/WebAppSecContributor.java
@@ -34,15 +34,16 @@ public class WebAppSecContributor extends
   private static final String ROLE = "webappsec";
   private static final String NAME = "WebAppSec";
   private static final String CSRF_SUFFIX = "_CSRF";
-  private static final String CSRF_FILTER_CLASSNAME = "CSRFPreventionFilter";
+  private static final String CSRF_FILTER_CLASSNAME = "org.apache.knox.gateway.webappsec.filter.CSRFPreventionFilter";
   private static final String CSRF_ENABLED = "csrf.enabled";
   private static final String CORS_SUFFIX = "_CORS";
   private static final String CORS_FILTER_CLASSNAME = "com.thetransactioncompany.cors.CORSFilter";
   private static final String CORS_ENABLED = "cors.enabled";
   private static final String XFRAME_OPTIONS_SUFFIX = "_XFRAMEOPTIONS";
-  private static final String XFRAME_OPTIONS_FILTER_CLASSNAME = "XFrameOptionsFilter";
+  private static final String XFRAME_OPTIONS_FILTER_CLASSNAME = "org.apache.knox.gateway.webappsec.filter.XFrameOptionsFilter";
   private static final String XFRAME_OPTIONS_ENABLED = "xframe.options.enabled";
 
+
   @Override
   public String getRole() {
     return ROLE;

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-release/home/conf/gateway-log4j.properties
----------------------------------------------------------------------
diff --git a/gateway-release/home/conf/gateway-log4j.properties b/gateway-release/home/conf/gateway-log4j.properties
index 85c623e..ece2fbb 100644
--- a/gateway-release/home/conf/gateway-log4j.properties
+++ b/gateway-release/home/conf/gateway-log4j.properties
@@ -20,8 +20,8 @@ app.audit.file=${launcher.name}-audit.log
 
 log4j.rootLogger=ERROR, drfa
 
-log4j.logger.org.apache.hadoop.gateway=INFO
-#log4j.logger.org.apache.hadoop.gateway=DEBUG
+log4j.logger.org.apache.knox.gateway=INFO
+#log4j.logger.org.apache.knox.gateway=DEBUG
 
 #log4j.logger.org.eclipse.jetty=DEBUG
 #log4j.logger.org.apache.shiro=DEBUG
@@ -47,15 +47,15 @@ log4j.appender.auditfile.Append = true
 log4j.appender.auditfile.DatePattern = '.'yyyy-MM-dd
 log4j.appender.auditfile.layout = org.apache.knox.gateway.audit.log4j.layout.AuditLayout
 
-#log4j.logger.org.apache.hadoop.gateway.access=TRACE,httpaccess
-#log4j.additivity.org.apache.hadoop.gateway.access=false
+#log4j.logger.org.apache.knox.gateway.access=TRACE,httpaccess
+#log4j.additivity.org.apache.knox.gateway.access=false
 
-#log4j.logger.org.apache.hadoop.gateway.http=TRACE,httpserver
-#log4j.additivity.org.apache.hadoop.gateway.http=false
-##log4j.logger.org.apache.hadoop.gateway.http.request.headers=OFF
-##log4j.logger.org.apache.hadoop.gateway.http.response.headers=OFF
-##log4j.logger.org.apache.hadoop.gateway.http.request.body=OFF
-##log4j.logger.org.apache.hadoop.gateway.http.response.body=OFF
+#log4j.logger.org.apache.knox.gateway.http=TRACE,httpserver
+#log4j.additivity.org.apache.knox.gateway.http=false
+##log4j.logger.org.apache.knox.gateway.http.request.headers=OFF
+##log4j.logger.org.apache.knox.gateway.http.response.headers=OFF
+##log4j.logger.org.apache.knox.gateway.http.request.body=OFF
+##log4j.logger.org.apache.knox.gateway.http.response.body=OFF
 
 #log4j.logger.org.apache.http.wire=DEBUG,httpclient
 #log4j.additivity.org.apache.http.wire=false

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-release/home/conf/knoxcli-log4j.properties
----------------------------------------------------------------------
diff --git a/gateway-release/home/conf/knoxcli-log4j.properties b/gateway-release/home/conf/knoxcli-log4j.properties
index c7fab24..4a8317e 100644
--- a/gateway-release/home/conf/knoxcli-log4j.properties
+++ b/gateway-release/home/conf/knoxcli-log4j.properties
@@ -19,8 +19,8 @@ app.log.file=${launcher.name}.log
 
 log4j.rootLogger=ERROR, drfa
 
-log4j.logger.org.apache.hadoop.gateway=INFO
-#log4j.logger.org.apache.hadoop.gateway=DEBUG
+log4j.logger.org.apache.knox.gateway=INFO
+#log4j.logger.org.apache.knox.gateway=DEBUG
 
 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server-launcher/src/main/resources/META-INF/launcher.cfg
----------------------------------------------------------------------
diff --git a/gateway-server-launcher/src/main/resources/META-INF/launcher.cfg b/gateway-server-launcher/src/main/resources/META-INF/launcher.cfg
index fd22919..c866c62 100644
--- a/gateway-server-launcher/src/main/resources/META-INF/launcher.cfg
+++ b/gateway-server-launcher/src/main/resources/META-INF/launcher.cfg
@@ -12,7 +12,7 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-main.class = org.apache.hadoop.gateway.GatewayServer
+main.class = org.apache.knox.gateway.GatewayServer
 class.path = ../conf;../lib/*.jar;../dep/*.jar;../ext;../ext/*.jar
 GATEWAY_HOME=${launcher.dir}/..
 log4j.configuration=${GATEWAY_HOME}/conf/${launcher.name}-log4j.properties

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrUtils.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrUtils.java b/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrUtils.java
deleted file mode 100644
index 20e359b..0000000
--- a/gateway-server/src/main/java/org/apache/hadoop/gateway/services/metrics/impl/instr/InstrUtils.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
- * <p/>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p/>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT 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.hadoop.gateway.services.metrics.impl.instr;
-
-import com.google.common.base.Strings;
-
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class InstrUtils {
-
-    //This regular expression pattern is used to parse the *first* two elements
-    //of a path. For example, if the path is “/webhdfs/v1/d1/d2/d2/d4”, this pattern
-    //can be used to get the first two ("/webhdfs/v1/"). The "?" in pattern
-    //ensures not to be greedy in matching.
-    private static Pattern p = Pattern.compile("/.*?/.*?/");
-
-    /**
-     * This function parses the pathinfo provided  in any servlet context and
-     * returns the segment that is related to the resource.
-     * For example, if the path is "/webhdfs/v1/d1/d2/d2/d4". it returns "/webhdfs/v1"
-     *
-     * @param fullPath
-     * @return
-     */
-    public static String getResourcePath(String fullPath) {
-        String resourcePath = "";
-        if (!Strings.isNullOrEmpty(fullPath)) {
-            Matcher m = p.matcher(fullPath);
-            if (m.find()) {
-                resourcePath = m.group(0);
-            } else {
-                resourcePath = fullPath;
-            }
-        }
-        return resourcePath;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/main/java/org/apache/knox/gateway/GatewayMessages.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/knox/gateway/GatewayMessages.java b/gateway-server/src/main/java/org/apache/knox/gateway/GatewayMessages.java
index 8fef9bb..66828cd 100644
--- a/gateway-server/src/main/java/org/apache/knox/gateway/GatewayMessages.java
+++ b/gateway-server/src/main/java/org/apache/knox/gateway/GatewayMessages.java
@@ -33,7 +33,7 @@ import java.util.Set;
 /**
  *
  */
-@Messages(logger="org.apache.hadoop.gateway")
+@Messages(logger="org.apache.knox.gateway")
 public interface GatewayMessages {
 
   @Message( level = MessageLevel.FATAL, text = "Failed to parse command line: {0}" )

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/main/java/org/apache/knox/gateway/deploy/impl/ServiceDefinitionDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/knox/gateway/deploy/impl/ServiceDefinitionDeploymentContributor.java b/gateway-server/src/main/java/org/apache/knox/gateway/deploy/impl/ServiceDefinitionDeploymentContributor.java
index 322bb08..9ac71bd 100644
--- a/gateway-server/src/main/java/org/apache/knox/gateway/deploy/impl/ServiceDefinitionDeploymentContributor.java
+++ b/gateway-server/src/main/java/org/apache/knox/gateway/deploy/impl/ServiceDefinitionDeploymentContributor.java
@@ -56,7 +56,7 @@ public class ServiceDefinitionDeploymentContributor extends ServiceDeploymentCon
 
   private static final String XFORWARDED_FILTER_ROLE = "xforwardedheaders";
 
-  private static final String DEFAULT_HA_DISPATCH_CLASS = "org.apache.hadoop.gateway.ha.dispatch.DefaultHaDispatch";
+  private static final String DEFAULT_HA_DISPATCH_CLASS = "org.apache.knox.gateway.ha.dispatch.DefaultHaDispatch";
 
   private static final String COOKIE_SCOPING_FILTER_NAME = "CookieScopeServletFilter";
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/main/java/org/apache/knox/gateway/services/CLIGatewayServices.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/knox/gateway/services/CLIGatewayServices.java b/gateway-server/src/main/java/org/apache/knox/gateway/services/CLIGatewayServices.java
index 49664b1..3f29930 100644
--- a/gateway-server/src/main/java/org/apache/knox/gateway/services/CLIGatewayServices.java
+++ b/gateway-server/src/main/java/org/apache/knox/gateway/services/CLIGatewayServices.java
@@ -98,7 +98,7 @@ public class CLIGatewayServices implements GatewayServices {
   }
   
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.GatewayServices#getServiceNames()
+   * @see org.apache.knox.gateway.GatewayServices#getServiceNames()
    */
   @Override
   public Collection<String> getServiceNames() {
@@ -106,7 +106,7 @@ public class CLIGatewayServices implements GatewayServices {
   }
   
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.GatewayServices#getService(java.lang.String)
+   * @see org.apache.knox.gateway.GatewayServices#getService(java.lang.String)
    */
   @Override
   public <T> T getService(String serviceName) {

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/main/java/org/apache/knox/gateway/services/DefaultGatewayServices.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/knox/gateway/services/DefaultGatewayServices.java b/gateway-server/src/main/java/org/apache/knox/gateway/services/DefaultGatewayServices.java
index 894f993..09c0505 100644
--- a/gateway-server/src/main/java/org/apache/knox/gateway/services/DefaultGatewayServices.java
+++ b/gateway-server/src/main/java/org/apache/knox/gateway/services/DefaultGatewayServices.java
@@ -163,7 +163,7 @@ public class DefaultGatewayServices implements GatewayServices {
   }
   
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.GatewayServices#getServiceNames()
+   * @see org.apache.knox.gateway.GatewayServices#getServiceNames()
    */
   @Override
   public Collection<String> getServiceNames() {
@@ -171,7 +171,7 @@ public class DefaultGatewayServices implements GatewayServices {
   }
   
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.GatewayServices#getService(java.lang.String)
+   * @see org.apache.knox.gateway.GatewayServices#getService(java.lang.String)
    */
   @Override
   public <T> T getService(String serviceName) {

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/main/java/org/apache/knox/gateway/services/GatewayServicesContextListener.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/knox/gateway/services/GatewayServicesContextListener.java b/gateway-server/src/main/java/org/apache/knox/gateway/services/GatewayServicesContextListener.java
index 96771fa..ec94a09 100644
--- a/gateway-server/src/main/java/org/apache/knox/gateway/services/GatewayServicesContextListener.java
+++ b/gateway-server/src/main/java/org/apache/knox/gateway/services/GatewayServicesContextListener.java
@@ -30,10 +30,10 @@ public class GatewayServicesContextListener implements ServletContextListener {
   public void contextInitialized(ServletContextEvent sce) {
     GatewayServices gs = GatewayServer.getGatewayServices();
     sce.getServletContext().setAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE, gs);
-    String topologyName = (String) sce.getServletContext().getAttribute("org.apache.hadoop.gateway.gateway.cluster");
+    String topologyName = (String) sce.getServletContext().getAttribute("org.apache.knox.gateway.gateway.cluster");
     TopologyService ts = gs.getService(GatewayServices.TOPOLOGY_SERVICE);
     Topology topology = getTopology(ts, topologyName);
-    sce.getServletContext().setAttribute("org.apache.hadoop.gateway.topology", topology);
+    sce.getServletContext().setAttribute("org.apache.knox.gateway.topology", topology);
   }
 
   private Topology getTopology(TopologyService ts, String topologyName) {

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/main/java/org/apache/knox/gateway/services/hostmap/impl/DefaultHostMapperService.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/knox/gateway/services/hostmap/impl/DefaultHostMapperService.java b/gateway-server/src/main/java/org/apache/knox/gateway/services/hostmap/impl/DefaultHostMapperService.java
index 6a53483..22df1e8 100644
--- a/gateway-server/src/main/java/org/apache/knox/gateway/services/hostmap/impl/DefaultHostMapperService.java
+++ b/gateway-server/src/main/java/org/apache/knox/gateway/services/hostmap/impl/DefaultHostMapperService.java
@@ -55,7 +55,7 @@ public class DefaultHostMapperService implements HostMapperService {
   }
 
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.services.hostmap.HostMappingService#getHostMapper(java.lang.String)
+   * @see org.apache.knox.gateway.services.hostmap.HostMappingService#getHostMapper(java.lang.String)
    */
   @Override
   public HostMapper getHostMapper( String clusterName ) {
@@ -63,7 +63,7 @@ public class DefaultHostMapperService implements HostMapperService {
   }
 
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.services.hostmap.HostMappingService#registerHostMapperForCluster(java.lang.String, HostMapper)
+   * @see org.apache.knox.gateway.services.hostmap.HostMappingService#registerHostMapperForCluster(java.lang.String, HostMapper)
    */
   @Override
   public void registerHostMapperForCluster( String clusterName, HostMapper hostMapper ) {
@@ -71,7 +71,7 @@ public class DefaultHostMapperService implements HostMapperService {
   }
 
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.services.hostmap.HostMappingService#removeHostMapperForCluster(java.lang.String)
+   * @see org.apache.knox.gateway.services.hostmap.HostMappingService#removeHostMapperForCluster(java.lang.String)
    */
   @Override
   public void removeHostMapperForCluster( String clusterName ) {

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/main/java/org/apache/knox/gateway/services/security/impl/DefaultAliasService.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/knox/gateway/services/security/impl/DefaultAliasService.java b/gateway-server/src/main/java/org/apache/knox/gateway/services/security/impl/DefaultAliasService.java
index 9c7121a..f52a7b3 100644
--- a/gateway-server/src/main/java/org/apache/knox/gateway/services/security/impl/DefaultAliasService.java
+++ b/gateway-server/src/main/java/org/apache/knox/gateway/services/security/impl/DefaultAliasService.java
@@ -73,7 +73,7 @@ public class DefaultAliasService implements AliasService {
   }
 
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.services.security.impl.AliasService#getAliasForCluster(java.lang.String, java.lang.String)
+   * @see org.apache.knox.gateway.services.security.impl.AliasService#getAliasForCluster(java.lang.String, java.lang.String)
    */
   @Override
   public char[] getPasswordFromAliasForCluster(String clusterName, String alias)
@@ -82,7 +82,7 @@ public class DefaultAliasService implements AliasService {
   }
 
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.services.security.impl.AliasService#getAliasForCluster(java.lang.String, java.lang.String, boolean)
+   * @see org.apache.knox.gateway.services.security.impl.AliasService#getAliasForCluster(java.lang.String, java.lang.String, boolean)
    */
   @Override
   public char[] getPasswordFromAliasForCluster(String clusterName, String alias, boolean generate)
@@ -135,7 +135,7 @@ public class DefaultAliasService implements AliasService {
   }
 
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.services.security.impl.AliasService#addAliasForCluster(java.lang.String, java.lang.String, java.lang.String)
+   * @see org.apache.knox.gateway.services.security.impl.AliasService#addAliasForCluster(java.lang.String, java.lang.String, java.lang.String)
    */
   @Override
   public void addAliasForCluster(String clusterName, String alias, String value) {

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/main/java/org/apache/knox/gateway/services/token/impl/DefaultTokenAuthorityService.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/knox/gateway/services/token/impl/DefaultTokenAuthorityService.java b/gateway-server/src/main/java/org/apache/knox/gateway/services/token/impl/DefaultTokenAuthorityService.java
index 79560aa..44f4d4b 100644
--- a/gateway-server/src/main/java/org/apache/knox/gateway/services/token/impl/DefaultTokenAuthorityService.java
+++ b/gateway-server/src/main/java/org/apache/knox/gateway/services/token/impl/DefaultTokenAuthorityService.java
@@ -60,7 +60,7 @@ public class DefaultTokenAuthorityService implements JWTokenAuthority, Service {
   }
 
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.provider.federation.jwt.JWTokenAuthority#issueToken(javax.security.auth.Subject, java.lang.String)
+   * @see org.apache.knox.gateway.provider.federation.jwt.JWTokenAuthority#issueToken(javax.security.auth.Subject, java.lang.String)
    */
   @Override
   public JWTToken issueToken(Subject subject, String algorithm) throws TokenServiceException {
@@ -69,7 +69,7 @@ public class DefaultTokenAuthorityService implements JWTokenAuthority, Service {
   }
   
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.provider.federation.jwt.JWTokenAuthority#issueToken(java.security.Principal, java.lang.String)
+   * @see org.apache.knox.gateway.provider.federation.jwt.JWTokenAuthority#issueToken(java.security.Principal, java.lang.String)
    */
   @Override
   public JWTToken issueToken(Principal p, String algorithm) throws TokenServiceException {
@@ -77,7 +77,7 @@ public class DefaultTokenAuthorityService implements JWTokenAuthority, Service {
   }
   
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.provider.federation.jwt.JWTokenAuthority#issueToken(java.security.Principal, java.lang.String, long expires)
+   * @see org.apache.knox.gateway.provider.federation.jwt.JWTokenAuthority#issueToken(java.security.Principal, java.lang.String, long expires)
    */
   @Override
   public JWTToken issueToken(Principal p, String algorithm, long expires) throws TokenServiceException {
@@ -90,7 +90,7 @@ public class DefaultTokenAuthorityService implements JWTokenAuthority, Service {
   }
 
   /* (non-Javadoc)
-   * @see org.apache.hadoop.gateway.provider.federation.jwt.JWTokenAuthority#issueToken(java.security.Principal, java.lang.String, java.lang.String)
+   * @see org.apache.knox.gateway.provider.federation.jwt.JWTokenAuthority#issueToken(java.security.Principal, java.lang.String, java.lang.String)
    */
   @Override
   public JWTToken issueToken(Principal p, String audience, String algorithm, long expires)

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/main/java/org/apache/knox/gateway/trace/AccessHandler.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/knox/gateway/trace/AccessHandler.java b/gateway-server/src/main/java/org/apache/knox/gateway/trace/AccessHandler.java
index 6ee7c83..dfb7213 100644
--- a/gateway-server/src/main/java/org/apache/knox/gateway/trace/AccessHandler.java
+++ b/gateway-server/src/main/java/org/apache/knox/gateway/trace/AccessHandler.java
@@ -25,7 +25,7 @@ import org.eclipse.jetty.util.component.AbstractLifeCycle;
 
 public class AccessHandler extends AbstractLifeCycle implements RequestLog {
 
-  private static Logger log = Logger.getLogger( "org.apache.hadoop.gateway.access" );
+  private static Logger log = Logger.getLogger( "org.apache.knox.gateway.access" );
 
   @Override
   public void log( Request request, Response response ) {

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/main/java/org/apache/knox/gateway/trace/TraceHandler.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/knox/gateway/trace/TraceHandler.java b/gateway-server/src/main/java/org/apache/knox/gateway/trace/TraceHandler.java
index af2bc22..34bee67 100644
--- a/gateway-server/src/main/java/org/apache/knox/gateway/trace/TraceHandler.java
+++ b/gateway-server/src/main/java/org/apache/knox/gateway/trace/TraceHandler.java
@@ -28,7 +28,7 @@ import java.util.Set;
 
 public class TraceHandler extends HandlerWrapper {
 
-  static final String HTTP_LOGGER = "org.apache.hadoop.gateway.http";
+  static final String HTTP_LOGGER = "org.apache.knox.gateway.http";
   static final String HTTP_REQUEST_LOGGER = HTTP_LOGGER + ".request";
   static final String HTTP_REQUEST_HEADER_LOGGER = HTTP_REQUEST_LOGGER + ".headers";
   static final String HTTP_REQUEST_BODY_LOGGER = HTTP_REQUEST_LOGGER + ".body";

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/main/java/org/apache/knox/gateway/util/KnoxCLI.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/knox/gateway/util/KnoxCLI.java b/gateway-server/src/main/java/org/apache/knox/gateway/util/KnoxCLI.java
index 531b494..1cd1e11 100644
--- a/gateway-server/src/main/java/org/apache/knox/gateway/util/KnoxCLI.java
+++ b/gateway-server/src/main/java/org/apache/knox/gateway/util/KnoxCLI.java
@@ -1261,8 +1261,8 @@ public class KnoxCLI extends Configured implements Tool {
 //        Build the Ini with minimum requirements
         Ini ini = new Ini();
         ini.addSection("main");
-        ini.setSectionProperty("main", "ldapRealm", "org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm");
-        ini.setSectionProperty("main", "ldapContextFactory", "org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory");
+        ini.setSectionProperty("main", "ldapRealm", "org.apache.knox.gateway.shirorealm.KnoxLdapRealm");
+        ini.setSectionProperty("main", "ldapContextFactory", "org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory");
         ini.setSectionProperty("main", "ldapRealm.contextFactory.url", url);
 
         username = getSystemUsername(t);

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/main/java/org/apache/knox/gateway/websockets/WebsocketLogMessages.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/java/org/apache/knox/gateway/websockets/WebsocketLogMessages.java b/gateway-server/src/main/java/org/apache/knox/gateway/websockets/WebsocketLogMessages.java
index 25a4b9e..b3abd10 100644
--- a/gateway-server/src/main/java/org/apache/knox/gateway/websockets/WebsocketLogMessages.java
+++ b/gateway-server/src/main/java/org/apache/knox/gateway/websockets/WebsocketLogMessages.java
@@ -28,7 +28,7 @@ import org.apache.knox.gateway.i18n.messages.StackTrace;
  * @since 0.10
  */
 
-@Messages(logger = "org.apache.hadoop.gateway.websockets")
+@Messages(logger = "org.apache.knox.gateway.websockets")
 public interface WebsocketLogMessages {
 
   @Message(level = MessageLevel.ERROR,

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/main/resources/conf/log4j.properties
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/resources/conf/log4j.properties b/gateway-server/src/main/resources/conf/log4j.properties
index 90edf58..ffb5d20 100644
--- a/gateway-server/src/main/resources/conf/log4j.properties
+++ b/gateway-server/src/main/resources/conf/log4j.properties
@@ -21,4 +21,4 @@ log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
 #log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %-5p [%t] %c{2} (%F:%M(%L)) - %m%n
 log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %-5p [%t] %m%n
 
-log4j.logger.org.apache.hadoop.gateway=INFO
\ No newline at end of file
+log4j.logger.org.apache.knox.gateway=INFO
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/main/resources/org/apache/knox/gateway/GatewayServer.xml
----------------------------------------------------------------------
diff --git a/gateway-server/src/main/resources/org/apache/knox/gateway/GatewayServer.xml b/gateway-server/src/main/resources/org/apache/knox/gateway/GatewayServer.xml
index 99330a1..994bb78 100644
--- a/gateway-server/src/main/resources/org/apache/knox/gateway/GatewayServer.xml
+++ b/gateway-server/src/main/resources/org/apache/knox/gateway/GatewayServer.xml
@@ -46,7 +46,7 @@
         </filter>
         <filter>
             <name>dispatch</name>
-            <class>org.apache.org.apache.hadoop.gateway.dispatch.HdfsDispatch</class>
+            <class>org.apache.org.apache.knox.gateway.dispatch.HdfsDispatch</class>
         </filter>
     </service>
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/test/java/org/apache/knox/gateway/GatewayFuncTest.xml
----------------------------------------------------------------------
diff --git a/gateway-server/src/test/java/org/apache/knox/gateway/GatewayFuncTest.xml b/gateway-server/src/test/java/org/apache/knox/gateway/GatewayFuncTest.xml
index d3c185a..8c0080c 100644
--- a/gateway-server/src/test/java/org/apache/knox/gateway/GatewayFuncTest.xml
+++ b/gateway-server/src/test/java/org/apache/knox/gateway/GatewayFuncTest.xml
@@ -43,11 +43,11 @@
             <name>rewrite</name>
             <class>org.apache.org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletFilter</class>
             <rewrite>webhdfs://*:*/{path=**}
-                http://{org.apache.org.apache.hadoop.gateway.address}/org.apache.hadoopache.hadoop.gateway/gateway/webhdfs/v1/{path=**}</rewrite>
+                http://{org.apache.org.apache.knox.gateway.address}/org.apache.hadoopache.hadoop.gateway/gateway/webhdfs/v1/{path=**}</rewrite>
         </filter>
         <filter>
             <name>dispatch</name>
-            <class>org.apache.org.apache.hadoop.gateway.dispatch.HdfsDispatch</class>
+            <class>org.apache.org.apache.knox.gateway.dispatch.HdfsDispatch</class>
         </filter>
     </service>
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/test/java/org/apache/knox/gateway/util/KnoxCLITest.java
----------------------------------------------------------------------
diff --git a/gateway-server/src/test/java/org/apache/knox/gateway/util/KnoxCLITest.java b/gateway-server/src/test/java/org/apache/knox/gateway/util/KnoxCLITest.java
index e84bbbd..4c4d419 100644
--- a/gateway-server/src/test/java/org/apache/knox/gateway/util/KnoxCLITest.java
+++ b/gateway-server/src/test/java/org/apache/knox/gateway/util/KnoxCLITest.java
@@ -496,7 +496,7 @@ public class KnoxCLITest {
         .addTag( "enabled" ).addText( "123" )
         .addTag( "param" )
         .addTag( "name" ).addText( "" )
-        .addTag( "value" ).addText( "org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm" ).gotoParent()
+        .addTag( "value" ).addText( "org.apache.knox.gateway.shirorealm.KnoxLdapRealm" ).gotoParent()
         .addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.userDnTemplate" )
         .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" ).gotoParent()
@@ -532,7 +532,7 @@ public class KnoxCLITest {
         .addTag( "enabled" ).addText( "true" )
         .addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm" )
-        .addTag( "value" ).addText( "org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm" ).gotoParent()
+        .addTag( "value" ).addText( "org.apache.knox.gateway.shirorealm.KnoxLdapRealm" ).gotoParent()
         .addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.userDnTemplate" )
         .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" ).gotoParent()

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/test/resources/conf-demo/conf/shiro.ini
----------------------------------------------------------------------
diff --git a/gateway-server/src/test/resources/conf-demo/conf/shiro.ini b/gateway-server/src/test/resources/conf-demo/conf/shiro.ini
index b3472a2..8bb3303 100644
--- a/gateway-server/src/test/resources/conf-demo/conf/shiro.ini
+++ b/gateway-server/src/test/resources/conf-demo/conf/shiro.ini
@@ -17,7 +17,7 @@
 ##########################################################################
 
 [main]
-ldapRealm = org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm
+ldapRealm = org.apache.knox.gateway.shirorealm.KnoxLdapRealm
 ldapRealm.userDnTemplate = uid={0},ou=people,dc=hadoop,dc=apache,dc=org
 ldapRealm.contextFactory.url = ldap://localhost:33389
 ldapRealm.contextFactory.authenticationMechanism = simple

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/test/resources/conf-demo/conf/topologies/admin.xml
----------------------------------------------------------------------
diff --git a/gateway-server/src/test/resources/conf-demo/conf/topologies/admin.xml b/gateway-server/src/test/resources/conf-demo/conf/topologies/admin.xml
index 2f3d9a9..efcd3c8 100644
--- a/gateway-server/src/test/resources/conf-demo/conf/topologies/admin.xml
+++ b/gateway-server/src/test/resources/conf-demo/conf/topologies/admin.xml
@@ -34,11 +34,11 @@
             </param>
             <param>
                 <name>main.ldapRealm</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
                 <name>main.ldapContextFactory</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
                 <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/test/resources/conf-demo/conf/topologies/sandbox.xml
----------------------------------------------------------------------
diff --git a/gateway-server/src/test/resources/conf-demo/conf/topologies/sandbox.xml b/gateway-server/src/test/resources/conf-demo/conf/topologies/sandbox.xml
index 2aaaf10..c7ae79a 100644
--- a/gateway-server/src/test/resources/conf-demo/conf/topologies/sandbox.xml
+++ b/gateway-server/src/test/resources/conf-demo/conf/topologies/sandbox.xml
@@ -34,11 +34,11 @@
             </param>
             <param>
                 <name>main.ldapRealm</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
             </param>
             <param>
                 <name>main.ldapContextFactory</name>
-                <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapContextFactory</value>
+                <value>org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory</value>
             </param>
             <param>
                 <name>main.ldapRealm.contextFactory</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/gateway-server/src/test/resources/log4j.properties b/gateway-server/src/test/resources/log4j.properties
index 7474633..b212231 100644
--- a/gateway-server/src/test/resources/log4j.properties
+++ b/gateway-server/src/test/resources/log4j.properties
@@ -26,7 +26,7 @@ log4j.appender.stdout.layout.ConversionPattern=%5p [%c] %m%n
 log4j.logger.audit = INFO, collectappender
 log4j.appender.collectappender = org.apache.hadoop.test.log.CollectAppender
 
-#log4j.logger.org.apache.hadoop.gateway=DEBUG
+#log4j.logger.org.apache.knox.gateway=DEBUG
 #log4j.logger.org.eclipse.jetty=DEBUG
 #log4j.logger.org.apache.shiro=DEBUG
 #log4j.logger.org.apache.http=DEBUG

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/test/resources/org/apache/knox/gateway/GatewayFuncTest.xml
----------------------------------------------------------------------
diff --git a/gateway-server/src/test/resources/org/apache/knox/gateway/GatewayFuncTest.xml b/gateway-server/src/test/resources/org/apache/knox/gateway/GatewayFuncTest.xml
index 82e443d..5581ee0 100644
--- a/gateway-server/src/test/resources/org/apache/knox/gateway/GatewayFuncTest.xml
+++ b/gateway-server/src/test/resources/org/apache/knox/gateway/GatewayFuncTest.xml
@@ -48,7 +48,7 @@
         </filter>
         <filter>
             <role>dispatch</role>
-            <class>org.apache.hadoop.gateway.dispatch.HdfsDispatch</class>
+            <class>org.apache.knox.gateway.dispatch.HdfsDispatch</class>
         </filter>
     </resource>
 

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/test/resources/org/apache/knox/gateway/topology/xml/simple-topology-ambari-format.conf
----------------------------------------------------------------------
diff --git a/gateway-server/src/test/resources/org/apache/knox/gateway/topology/xml/simple-topology-ambari-format.conf b/gateway-server/src/test/resources/org/apache/knox/gateway/topology/xml/simple-topology-ambari-format.conf
index 849e1b6..eacb631 100644
--- a/gateway-server/src/test/resources/org/apache/knox/gateway/topology/xml/simple-topology-ambari-format.conf
+++ b/gateway-server/src/test/resources/org/apache/knox/gateway/topology/xml/simple-topology-ambari-format.conf
@@ -26,7 +26,7 @@
     </property>
     <property>
         <name>topology.gateway.provider.authentication.ShiroProvider.param.main.ldapRealm</name>
-        <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+        <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
     </property>
     <property>
         <name>topology.gateway.provider.authentication.ShiroProvider.param.main.ldapRealm.userDnTemplate</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/test/resources/org/apache/knox/gateway/topology/xml/simple-topology-knox-format.xml
----------------------------------------------------------------------
diff --git a/gateway-server/src/test/resources/org/apache/knox/gateway/topology/xml/simple-topology-knox-format.xml b/gateway-server/src/test/resources/org/apache/knox/gateway/topology/xml/simple-topology-knox-format.xml
index 0a208fc..c0b9b13 100644
--- a/gateway-server/src/test/resources/org/apache/knox/gateway/topology/xml/simple-topology-knox-format.xml
+++ b/gateway-server/src/test/resources/org/apache/knox/gateway/topology/xml/simple-topology-knox-format.xml
@@ -27,7 +27,7 @@
            <name>ShiroSecurity</name>
            <param>
                <name>main.ldapRealm</name>
-               <value>org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm</value>
+               <value>org.apache.knox.gateway.shirorealm.KnoxLdapRealm</value>
            </param>
            <param>
                <name>main.ldapRealm.userDnTemplate</name>

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-server/src/test/resources/shiro.ini
----------------------------------------------------------------------
diff --git a/gateway-server/src/test/resources/shiro.ini b/gateway-server/src/test/resources/shiro.ini
index b3472a2..8bb3303 100644
--- a/gateway-server/src/test/resources/shiro.ini
+++ b/gateway-server/src/test/resources/shiro.ini
@@ -17,7 +17,7 @@
 ##########################################################################
 
 [main]
-ldapRealm = org.apache.hadoop.gateway.shirorealm.KnoxLdapRealm
+ldapRealm = org.apache.knox.gateway.shirorealm.KnoxLdapRealm
 ldapRealm.userDnTemplate = uid={0},ou=people,dc=hadoop,dc=apache,dc=org
 ldapRealm.contextFactory.url = ldap://localhost:33389
 ldapRealm.contextFactory.authenticationMechanism = simple

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-admin/src/main/java/org/apache/knox/gateway/service/admin/deploy/AdminServiceDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-service-admin/src/main/java/org/apache/knox/gateway/service/admin/deploy/AdminServiceDeploymentContributor.java b/gateway-service-admin/src/main/java/org/apache/knox/gateway/service/admin/deploy/AdminServiceDeploymentContributor.java
index 86089e3..3a69f6a 100644
--- a/gateway-service-admin/src/main/java/org/apache/knox/gateway/service/admin/deploy/AdminServiceDeploymentContributor.java
+++ b/gateway-service-admin/src/main/java/org/apache/knox/gateway/service/admin/deploy/AdminServiceDeploymentContributor.java
@@ -45,7 +45,7 @@ public class AdminServiceDeploymentContributor extends JerseyServiceDeploymentCo
    */
   @Override
   protected String[] getPackages() {
-    return new String[]{ "org.apache.hadoop.gateway.service.admin" };
+    return new String[]{ "org.apache.knox.gateway.service.admin" };
   }
 
   /* (non-Javadoc)

http://git-wip-us.apache.org/repos/asf/knox/blob/2e6713b6/gateway-service-definitions/src/main/resources/services/ambari/2.2.0/service.xml
----------------------------------------------------------------------
diff --git a/gateway-service-definitions/src/main/resources/services/ambari/2.2.0/service.xml b/gateway-service-definitions/src/main/resources/services/ambari/2.2.0/service.xml
index cb6f35e..a7ce77c 100644
--- a/gateway-service-definitions/src/main/resources/services/ambari/2.2.0/service.xml
+++ b/gateway-service-definitions/src/main/resources/services/ambari/2.2.0/service.xml
@@ -30,5 +30,5 @@
             <rewrite apply="AMBARI/ambari/api/inbound" to="request.body"/>
         </route>
     </routes>
-    <dispatch classname="org.apache.hadoop.gateway.dispatch.PassAllHeadersNoEncodingDispatch"/>
+    <dispatch classname="org.apache.knox.gateway.dispatch.PassAllHeadersNoEncodingDispatch"/>
 </service>


[34/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessorTest.java
new file mode 100644
index 0000000..51d14ca
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessorTest.java
@@ -0,0 +1,153 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.ha.provider.HaProvider;
+import org.apache.knox.gateway.ha.provider.HaServletContextListener;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.hostmap.HostMapper;
+import org.apache.knox.gateway.services.hostmap.HostMapperService;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+import org.apache.knox.gateway.svcregfunc.api.ServiceMappedAddressFunctionDescriptor;
+import org.easymock.EasyMock;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
+import static org.junit.Assert.fail;
+
+public class ServiceMappedAddressFunctionProcessorTest {
+
+  HostMapperService hms;
+  HostMapper hm;
+  ServiceRegistry reg;
+  GatewayServices svc;
+  UrlRewriteEnvironment env;
+  UrlRewriteContext ctx;
+  ServiceMappedAddressFunctionDescriptor desc;
+
+  @Before
+  public void setUp() {
+    hm = EasyMock.createNiceMock( HostMapper.class );
+    EasyMock.expect( hm.resolveInboundHostName( "test-host" ) ).andReturn( "test-internal-host" ).anyTimes();
+
+    hms = EasyMock.createNiceMock( HostMapperService.class );
+    EasyMock.expect( hms.getHostMapper( "test-cluster" ) ).andReturn( hm ).anyTimes();
+
+    reg = EasyMock.createNiceMock( ServiceRegistry.class );
+    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
+
+    svc = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
+    EasyMock.expect( svc.getService( GatewayServices.HOST_MAPPING_SERVICE ) ).andReturn( hms ).anyTimes();
+
+    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
+
+    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
+    EasyMock.expect( ctx.getDirection() ).andReturn( UrlRewriter.Direction.IN ).anyTimes();
+
+    desc = EasyMock.createNiceMock( ServiceMappedAddressFunctionDescriptor.class );
+
+     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
+
+     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
+
+     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
+
+     EasyMock.replay( hm, hms, reg, svc, env, desc, ctx, haProvider );
+  }
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ServiceMappedAddressFunctionProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ServiceMappedAddressFunctionProcessor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    ServiceMappedAddressFunctionProcessor func = new ServiceMappedAddressFunctionProcessor();
+    assertThat( func.name(), is( "serviceMappedAddr" ) );
+  }
+
+  @Test
+  public void testInitialize() throws Exception {
+    ServiceMappedAddressFunctionProcessor func = new ServiceMappedAddressFunctionProcessor();
+    try {
+      func.initialize( null, desc );
+      fail( "Should have thrown an IllegalArgumentException" );
+    } catch( IllegalArgumentException e ) {
+      assertThat( e.getMessage(), containsString( "environment" ) );
+    }
+
+    func = new ServiceMappedAddressFunctionProcessor();
+    try {
+      func.initialize( env, null );
+    } catch( Exception e ) {
+      e.printStackTrace();
+      fail( "Should not have thrown an exception" );
+    }
+
+    func.initialize( env, desc );
+
+    assertThat( func.cluster(), is( "test-cluster" ) );
+    assertThat( func.registry(), sameInstance( reg ) );
+  }
+
+  @Test
+  public void testDestroy() throws Exception {
+    ServiceMappedAddressFunctionProcessor func = new ServiceMappedAddressFunctionProcessor();
+    func.initialize( env, desc );
+    func.destroy();
+
+    assertThat( func.cluster(), nullValue() );
+    assertThat( func.registry(), nullValue() );
+  }
+
+  @Test
+  public void testResolve() throws Exception {
+    ServiceMappedAddressFunctionProcessor func = new ServiceMappedAddressFunctionProcessor();
+    func.initialize( env, desc );
+
+    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-internal-host:777" ) );
+    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, null ), nullValue() );
+
+    func.destroy();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessorTest.java
new file mode 100644
index 0000000..7a7f072
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessorTest.java
@@ -0,0 +1,153 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.ha.provider.HaProvider;
+import org.apache.knox.gateway.ha.provider.HaServletContextListener;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.hostmap.HostMapper;
+import org.apache.knox.gateway.services.hostmap.HostMapperService;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+import org.apache.knox.gateway.svcregfunc.api.ServiceMappedHostFunctionDescriptor;
+import org.easymock.EasyMock;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
+import static org.junit.Assert.fail;
+
+public class ServiceMappedHostFunctionProcessorTest {
+
+  HostMapperService hms;
+  HostMapper hm;
+  ServiceRegistry reg;
+  GatewayServices svc;
+  UrlRewriteEnvironment env;
+  UrlRewriteContext ctx;
+  ServiceMappedHostFunctionDescriptor desc;
+
+  @Before
+  public void setUp() {
+    hm = EasyMock.createNiceMock( HostMapper.class );
+    EasyMock.expect( hm.resolveInboundHostName( "test-host" ) ).andReturn( "test-internal-host" ).anyTimes();
+
+    hms = EasyMock.createNiceMock( HostMapperService.class );
+    EasyMock.expect( hms.getHostMapper( "test-cluster" ) ).andReturn( hm ).anyTimes();
+
+    reg = EasyMock.createNiceMock( ServiceRegistry.class );
+    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
+
+    svc = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
+    EasyMock.expect( svc.getService( GatewayServices.HOST_MAPPING_SERVICE ) ).andReturn( hms ).anyTimes();
+
+    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
+
+    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
+    EasyMock.expect( ctx.getDirection() ).andReturn( UrlRewriter.Direction.IN ).anyTimes();
+
+    desc = EasyMock.createNiceMock( ServiceMappedHostFunctionDescriptor.class );
+
+     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
+
+     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
+
+     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
+
+     EasyMock.replay( hm, hms, reg, svc, env, desc, ctx, haProvider );
+  }
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ServiceMappedHostFunctionProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ServiceMappedHostFunctionProcessor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    ServiceMappedHostFunctionProcessor func = new ServiceMappedHostFunctionProcessor();
+    assertThat( func.name(), is( "serviceMappedHost" ) );
+  }
+
+  @Test
+  public void testInitialize() throws Exception {
+    ServiceMappedHostFunctionProcessor func = new ServiceMappedHostFunctionProcessor();
+    try {
+      func.initialize( null, desc );
+      fail( "Should have thrown an IllegalArgumentException" );
+    } catch( IllegalArgumentException e ) {
+      assertThat( e.getMessage(), containsString( "environment" ) );
+    }
+
+    func = new ServiceMappedHostFunctionProcessor();
+    try {
+      func.initialize( env, null );
+    } catch( Exception e ) {
+      e.printStackTrace();
+      fail( "Should not have thrown an exception" );
+    }
+
+    func.initialize( env, desc );
+
+    assertThat( func.cluster(), is( "test-cluster" ) );
+    assertThat( func.registry(), sameInstance( reg ) );
+  }
+
+  @Test
+  public void testDestroy() throws Exception {
+    ServiceMappedHostFunctionProcessor func = new ServiceMappedHostFunctionProcessor();
+    func.initialize( env, desc );
+    func.destroy();
+
+    assertThat( func.cluster(), nullValue() );
+    assertThat( func.registry(), nullValue() );
+  }
+
+  @Test
+  public void testResolve() throws Exception {
+    ServiceMappedHostFunctionProcessor func = new ServiceMappedHostFunctionProcessor();
+    func.initialize( env, desc );
+
+    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-internal-host" ) );
+    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, null ), nullValue() );
+
+    func.destroy();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessorTest.java
new file mode 100644
index 0000000..78d5429
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessorTest.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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.ha.provider.HaProvider;
+import org.apache.knox.gateway.ha.provider.HaServletContextListener;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.hostmap.HostMapper;
+import org.apache.knox.gateway.services.hostmap.HostMapperService;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+import org.apache.knox.gateway.svcregfunc.api.ServiceMappedUrlFunctionDescriptor;
+import org.easymock.EasyMock;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
+import static org.junit.Assert.fail;
+
+public class ServiceMappedUrlFunctionProcessorTest {
+
+  HostMapperService hms;
+  HostMapper hm;
+  ServiceRegistry reg;
+  GatewayServices svc;
+  UrlRewriteEnvironment env;
+  UrlRewriteContext ctx;
+  ServiceMappedUrlFunctionDescriptor desc;
+
+  @Before
+  public void setUp() {
+    hm = EasyMock.createNiceMock( HostMapper.class );
+    EasyMock.expect( hm.resolveInboundHostName( "test-host" ) ).andReturn( "test-internal-host" ).anyTimes();
+
+    hms = EasyMock.createNiceMock( HostMapperService.class );
+    EasyMock.expect( hms.getHostMapper( "test-cluster" ) ).andReturn( hm ).anyTimes();
+
+    reg = EasyMock.createNiceMock( ServiceRegistry.class );
+    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
+
+    svc = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
+    EasyMock.expect( svc.getService( GatewayServices.HOST_MAPPING_SERVICE ) ).andReturn( hms ).anyTimes();
+
+    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
+
+    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
+    EasyMock.expect( ctx.getDirection() ).andReturn( UrlRewriter.Direction.IN ).anyTimes();
+
+    desc = EasyMock.createNiceMock( ServiceMappedUrlFunctionDescriptor.class );
+
+
+     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
+
+     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
+
+     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
+
+     EasyMock.replay( hm, hms, reg, svc, env, desc, ctx, haProvider );
+  }
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ServiceMappedUrlFunctionProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ServiceMappedUrlFunctionProcessor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    ServiceMappedUrlFunctionProcessor func = new ServiceMappedUrlFunctionProcessor();
+    assertThat( func.name(), is( "serviceMappedUrl" ) );
+  }
+
+  @Test
+  public void testInitialize() throws Exception {
+    ServiceMappedUrlFunctionProcessor func = new ServiceMappedUrlFunctionProcessor();
+    try {
+      func.initialize( null, desc );
+      fail( "Should have thrown an IllegalArgumentException" );
+    } catch( IllegalArgumentException e ) {
+      assertThat( e.getMessage(), containsString( "environment" ) );
+    }
+
+    func = new ServiceMappedUrlFunctionProcessor();
+    try {
+      func.initialize( env, null );
+    } catch( Exception e ) {
+      e.printStackTrace(); //NOTE: OK to use e.printStackTrace for a test failure.
+      fail( "Should not have thrown an exception" );
+    }
+
+    func.initialize( env, desc );
+
+    assertThat( func.cluster(), is( "test-cluster" ) );
+    assertThat( func.registry(), sameInstance( reg ) );
+  }
+
+  @Test
+  public void testDestroy() throws Exception {
+    ServiceMappedUrlFunctionProcessor func = new ServiceMappedUrlFunctionProcessor();
+    func.initialize( env, desc );
+    func.destroy();
+
+    assertThat( func.cluster(), nullValue() );
+    assertThat( func.registry(), nullValue() );
+  }
+
+  @Test
+  public void testResolve() throws Exception {
+    ServiceMappedUrlFunctionProcessor func = new ServiceMappedUrlFunctionProcessor();
+    func.initialize( env, desc );
+
+    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-scheme://test-internal-host:777/test-path" ) );
+    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, null ), nullValue() );
+
+    func.destroy();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServicePathFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServicePathFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServicePathFunctionProcessorTest.java
new file mode 100644
index 0000000..87ddfb1
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServicePathFunctionProcessorTest.java
@@ -0,0 +1,140 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.ha.provider.HaProvider;
+import org.apache.knox.gateway.ha.provider.HaServletContextListener;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+import org.apache.knox.gateway.svcregfunc.api.ServicePathFunctionDescriptor;
+import org.easymock.EasyMock;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
+import static org.junit.Assert.fail;
+
+public class ServicePathFunctionProcessorTest {
+
+  ServiceRegistry reg;
+  GatewayServices svc;
+  UrlRewriteEnvironment env;
+  UrlRewriteContext ctx;
+  ServicePathFunctionDescriptor desc;
+
+  @Before
+  public void setUp() {
+    reg = EasyMock.createNiceMock( ServiceRegistry.class );
+    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
+
+    svc = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
+
+    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
+
+    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
+
+    desc = EasyMock.createNiceMock( ServicePathFunctionDescriptor.class );
+
+     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
+
+     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
+
+     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
+
+     EasyMock.replay( reg, svc, env, desc, ctx, haProvider );
+  }
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ServicePathFunctionProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ServicePathFunctionProcessor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    ServicePathFunctionProcessor func = new ServicePathFunctionProcessor();
+    assertThat( func.name(), is( "servicePath" ) );
+  }
+
+  @Test
+  public void testInitialize() throws Exception {
+    ServicePathFunctionProcessor func = new ServicePathFunctionProcessor();
+    try {
+      func.initialize( null, desc );
+      fail( "Should have thrown an IllegalArgumentException" );
+    } catch( IllegalArgumentException e ) {
+      assertThat( e.getMessage(), containsString( "environment" ) );
+    }
+
+    func = new ServicePathFunctionProcessor();
+    try {
+      func.initialize( env, null );
+    } catch( Exception e ) {
+      e.printStackTrace();
+      fail( "Should not have thrown an exception" );
+    }
+
+    func.initialize( env, desc );
+
+    assertThat( func.cluster(), is( "test-cluster" ) );
+    assertThat( func.registry(), sameInstance( reg ) );
+  }
+
+  @Test
+  public void testDestroy() throws Exception {
+    ServicePathFunctionProcessor func = new ServicePathFunctionProcessor();
+    func.initialize( env, desc );
+    func.destroy();
+
+    assertThat( func.cluster(), nullValue() );
+    assertThat( func.registry(), nullValue() );
+  }
+
+  @Test
+  public void testResolve() throws Exception {
+    ServicePathFunctionProcessor func = new ServicePathFunctionProcessor();
+    func.initialize( env, desc );
+
+//    assertThat( func.resolve( ctx, "test-service" ), is( "/test-path" ) );
+    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+//    assertThat( func.resolve( ctx, null ), nullValue() );
+
+    func.destroy();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServicePortFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServicePortFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServicePortFunctionProcessorTest.java
new file mode 100644
index 0000000..76a0381
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServicePortFunctionProcessorTest.java
@@ -0,0 +1,140 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.ha.provider.HaProvider;
+import org.apache.knox.gateway.ha.provider.HaServletContextListener;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+import org.apache.knox.gateway.svcregfunc.api.ServicePortFunctionDescriptor;
+import org.easymock.EasyMock;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
+import static org.junit.Assert.fail;
+
+public class ServicePortFunctionProcessorTest {
+
+  ServiceRegistry reg;
+  GatewayServices svc;
+  UrlRewriteEnvironment env;
+  UrlRewriteContext ctx;
+  ServicePortFunctionDescriptor desc;
+
+  @Before
+  public void setUp() {
+    reg = EasyMock.createNiceMock( ServiceRegistry.class );
+    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
+
+    svc = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
+
+    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
+
+    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
+
+    desc = EasyMock.createNiceMock( ServicePortFunctionDescriptor.class );
+
+     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
+
+     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
+
+     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
+
+     EasyMock.replay( reg, svc, env, desc, ctx, haProvider );
+  }
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ServicePortFunctionProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ServicePortFunctionProcessor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    ServicePortFunctionProcessor func = new ServicePortFunctionProcessor();
+    assertThat( func.name(), is( "servicePort" ) );
+  }
+
+  @Test
+  public void testInitialize() throws Exception {
+    ServicePortFunctionProcessor func = new ServicePortFunctionProcessor();
+    try {
+      func.initialize( null, desc );
+      fail( "Should have thrown an IllegalArgumentException" );
+    } catch( IllegalArgumentException e ) {
+      assertThat( e.getMessage(), containsString( "environment" ) );
+    }
+
+    func = new ServicePortFunctionProcessor();
+    try {
+      func.initialize( env, null );
+    } catch( Exception e ) {
+      e.printStackTrace();
+      fail( "Should not have thrown an exception" );
+    }
+
+    func.initialize( env, desc );
+
+    assertThat( func.cluster(), is( "test-cluster" ) );
+    assertThat( func.registry(), sameInstance( reg ) );
+  }
+
+  @Test
+  public void testDestroy() throws Exception {
+    ServicePortFunctionProcessor func = new ServicePortFunctionProcessor();
+    func.initialize( env, desc );
+    func.destroy();
+
+    assertThat( func.cluster(), nullValue() );
+    assertThat( func.registry(), nullValue() );
+  }
+
+  @Test
+  public void testResolve() throws Exception {
+    ServicePortFunctionProcessor func = new ServicePortFunctionProcessor();
+    func.initialize( env, desc );
+
+    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "777" ) );
+    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, null ), nullValue() );
+
+    func.destroy();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest.java
new file mode 100644
index 0000000..9f19a4f
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest.java
@@ -0,0 +1,225 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.AbstractGatewayFilter;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletContextListener;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletFilter;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.hadoop.test.TestUtils;
+import org.apache.hadoop.test.log.NoOpLogger;
+import org.apache.hadoop.test.mock.MockInteraction;
+import org.apache.hadoop.test.mock.MockServlet;
+import org.apache.http.auth.BasicUserPrincipal;
+import org.easymock.EasyMock;
+import org.eclipse.jetty.servlet.FilterHolder;
+import org.eclipse.jetty.servlet.ServletHolder;
+import org.eclipse.jetty.http.HttpTester;
+import org.eclipse.jetty.servlet.ServletTester;
+import org.eclipse.jetty.util.ArrayQueue;
+import org.eclipse.jetty.util.log.Log;
+import org.hamcrest.core.Is;
+import org.junit.Test;
+
+import javax.security.auth.Subject;
+import javax.servlet.*;
+import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.nio.charset.Charset;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+
+
+public class ServiceRegistryFunctionsTest {
+
+  private ServletTester server;
+  private HttpTester.Request request;
+  private HttpTester.Response response;
+  private ArrayQueue<MockInteraction> interactions;
+  private MockInteraction interaction;
+
+  private static URL getTestResource( String name ) {
+    name = ServiceRegistryFunctionsTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
+    URL url = ClassLoader.getSystemResource( name );
+    return url;
+  }
+
+  public void setUp( String username, Map<String,String> initParams ) throws Exception {
+    ServiceRegistry mockServiceRegistry = EasyMock.createNiceMock( ServiceRegistry.class );
+    EasyMock.expect( mockServiceRegistry.lookupServiceURL( "test-cluster", "NAMENODE" ) ).andReturn( "test-nn-scheme://test-nn-host:411" ).anyTimes();
+    EasyMock.expect( mockServiceRegistry.lookupServiceURL( "test-cluster", "JOBTRACKER" ) ).andReturn( "test-jt-scheme://test-jt-host:511" ).anyTimes();
+
+    GatewayServices mockGatewayServices = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( mockGatewayServices.getService(GatewayServices.SERVICE_REGISTRY_SERVICE) ).andReturn( mockServiceRegistry ).anyTimes();
+
+    EasyMock.replay( mockServiceRegistry, mockGatewayServices );
+
+    String descriptorUrl = getTestResource( "rewrite.xml" ).toExternalForm();
+
+    Log.setLog( new NoOpLogger() );
+
+    server = new ServletTester();
+    server.setContextPath( "/" );
+    server.getContext().addEventListener( new UrlRewriteServletContextListener() );
+    server.getContext().setInitParameter(
+        UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );
+    server.getContext().setAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE, "test-cluster" );
+    server.getContext().setAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE, mockGatewayServices );
+
+    FilterHolder setupFilter = server.addFilter( SetupFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
+    setupFilter.setFilter( new SetupFilter( username ) );
+    FilterHolder rewriteFilter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
+    if( initParams != null ) {
+      for( Map.Entry<String,String> entry : initParams.entrySet() ) {
+        rewriteFilter.setInitParameter( entry.getKey(), entry.getValue() );
+      }
+    }
+    rewriteFilter.setFilter( new UrlRewriteServletFilter() );
+
+    interactions = new ArrayQueue<MockInteraction>();
+
+    ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
+    servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );
+
+    server.start();
+
+    interaction = new MockInteraction();
+    request = HttpTester.newRequest();
+    response = null;
+  }
+
+  @Test
+  public void testServiceRegistryFunctionsOnXmlRequestBody() throws Exception {
+    Map<String,String> initParams = new HashMap<>();
+    initParams.put( "request.body", "oozie-conf" );
+    setUp( "test-user", initParams );
+
+    String input = TestUtils.getResourceString( ServiceRegistryFunctionsTest.class, "test-input-body.xml", "UTF-8" );
+    String expect = TestUtils.getResourceString( ServiceRegistryFunctionsTest.class, "test-expect-body.xml", "UTF-8" );
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "PUT" )
+        .requestUrl( "http://test-host:42/test-path" )
+        .contentType( "text/xml" )
+        .characterEncoding( "UTF-8" )
+        .content( expect, Charset.forName( "UTF-8" ) );
+    interaction.respond()
+        .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "PUT" );
+    request.setURI( "/test-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "test-host:42" );
+    request.setHeader( "Content-Type", "text/xml; charset=UTF-8" );
+    request.setContent( input );
+
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), Is.is( 200 ) );
+  }
+
+  @Test
+  public void testServiceRegistryFunctionsOnJsonRequestBody() throws Exception {
+    Map<String,String> initParams = new HashMap<>();
+    initParams.put( "request.body", "oozie-conf" );
+    setUp( "test-user", initParams );
+
+    String input = TestUtils.getResourceString( ServiceRegistryFunctionsTest.class, "test-input-body.json", "UTF-8" );
+    String expect = TestUtils.getResourceString( ServiceRegistryFunctionsTest.class, "test-expect-body.json", "UTF-8" );
+
+    // Setup the server side request/response interaction.
+    interaction.expect()
+        .method( "PUT" )
+        .requestUrl( "http://test-host:42/test-path" )
+        .contentType( "application/json" )
+        .characterEncoding( "UTF-8" )
+        .content( expect, Charset.forName( "UTF-8" ) );
+    interaction.respond()
+        .status( 200 );
+    interactions.add( interaction );
+    request.setMethod( "PUT" );
+    request.setURI( "/test-path" );
+    //request.setVersion( "HTTP/1.1" );
+    request.setHeader( "Host", "test-host:42" );
+    request.setHeader( "Content-Type", "application/json; charset=UTF-8" );
+    request.setContent( input );
+
+    response = TestUtils.execute( server, request );
+
+    // Test the results.
+    assertThat( response.getStatus(), Is.is( 200 ) );
+  }
+
+  private static class SetupFilter implements Filter {
+    private Subject subject;
+
+    public SetupFilter( String userName ) {
+      subject = new Subject();
+      subject.getPrincipals().add( new BasicUserPrincipal( userName ) );
+    }
+
+    @Override
+    public void init( FilterConfig filterConfig ) throws ServletException {
+    }
+
+    @Override
+    public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException {
+      HttpServletRequest httpRequest = ((HttpServletRequest)request);
+      StringBuffer sourceUrl = httpRequest.getRequestURL();
+      String queryString = httpRequest.getQueryString();
+      if( queryString != null ) {
+        sourceUrl.append( "?" );
+        sourceUrl.append( queryString );
+      }
+      try {
+        request.setAttribute(
+            AbstractGatewayFilter.SOURCE_REQUEST_URL_ATTRIBUTE_NAME,
+            Parser.parseLiteral( sourceUrl.toString() ) );
+      } catch( URISyntaxException e ) {
+        throw new ServletException( e );
+      }
+      try {
+        Subject.doAs( subject, new PrivilegedExceptionAction<Void>() {
+          @Override
+          public Void run() throws Exception {
+            chain.doFilter( request, response );
+            return null;
+          }
+        } );
+      } catch( PrivilegedActionException e ) {
+        throw new ServletException( e );
+      }
+    }
+
+    @Override
+    public void destroy() {
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessorTest.java
new file mode 100644
index 0000000..9c9affd
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessorTest.java
@@ -0,0 +1,140 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.ha.provider.HaProvider;
+import org.apache.knox.gateway.ha.provider.HaServletContextListener;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+import org.apache.knox.gateway.svcregfunc.api.ServiceSchemeFunctionDescriptor;
+import org.easymock.EasyMock;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
+import static org.junit.Assert.fail;
+
+public class ServiceSchemeFunctionProcessorTest {
+
+  ServiceRegistry reg;
+  GatewayServices svc;
+  UrlRewriteEnvironment env;
+  UrlRewriteContext ctx;
+  ServiceSchemeFunctionDescriptor desc;
+
+  @Before
+  public void setUp() {
+    reg = EasyMock.createNiceMock( ServiceRegistry.class );
+    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
+
+    svc = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
+
+    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
+
+    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
+
+    desc = EasyMock.createNiceMock( ServiceSchemeFunctionDescriptor.class );
+
+     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
+
+     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
+
+     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
+
+     EasyMock.replay( reg, svc, env, desc, ctx, haProvider );
+  }
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ServiceSchemeFunctionProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ServiceSchemeFunctionProcessor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    ServiceSchemeFunctionProcessor func = new ServiceSchemeFunctionProcessor();
+    assertThat( func.name(), is( "serviceScheme" ) );
+  }
+
+  @Test
+  public void testInitialize() throws Exception {
+    ServiceSchemeFunctionProcessor func = new ServiceSchemeFunctionProcessor();
+    try {
+      func.initialize( null, desc );
+      fail( "Should have thrown an IllegalArgumentException" );
+    } catch( IllegalArgumentException e ) {
+      assertThat( e.getMessage(), containsString( "environment" ) );
+    }
+
+    func = new ServiceSchemeFunctionProcessor();
+    try {
+      func.initialize( env, null );
+    } catch( Exception e ) {
+      e.printStackTrace(); //NOTE: This is an OK use of e.printStackTrace in a test.
+      fail( "Should not have thrown an exception" );
+    }
+
+    func.initialize( env, desc );
+
+    assertThat( func.cluster(), is( "test-cluster" ) );
+    assertThat( func.registry(), sameInstance( reg ) );
+  }
+
+  @Test
+  public void testDestroy() throws Exception {
+    ServiceSchemeFunctionProcessor func = new ServiceSchemeFunctionProcessor();
+    func.initialize( env, desc );
+    func.destroy();
+
+    assertThat( func.cluster(), nullValue() );
+    assertThat( func.registry(), nullValue() );
+  }
+
+  @Test
+  public void testResolve() throws Exception {
+    ServiceSchemeFunctionProcessor func = new ServiceSchemeFunctionProcessor();
+    func.initialize( env, desc );
+
+    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-scheme" ) );
+    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, null ), nullValue() );
+
+    func.destroy();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceUrlFunctionProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceUrlFunctionProcessorTest.java b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceUrlFunctionProcessorTest.java
new file mode 100644
index 0000000..fde6ef8
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceUrlFunctionProcessorTest.java
@@ -0,0 +1,153 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.svcregfunc.impl;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
+import org.apache.knox.gateway.ha.provider.HaProvider;
+import org.apache.knox.gateway.ha.provider.HaServletContextListener;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.hostmap.HostMapper;
+import org.apache.knox.gateway.services.hostmap.HostMapperService;
+import org.apache.knox.gateway.services.registry.ServiceRegistry;
+import org.apache.knox.gateway.svcregfunc.api.ServiceUrlFunctionDescriptor;
+import org.easymock.EasyMock;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
+import static org.junit.Assert.fail;
+
+public class ServiceUrlFunctionProcessorTest {
+
+  HostMapperService hms;
+  HostMapper hm;
+  ServiceRegistry reg;
+  GatewayServices svc;
+  UrlRewriteEnvironment env;
+  UrlRewriteContext ctx;
+  ServiceUrlFunctionDescriptor desc;
+
+  @Before
+  public void setUp() {
+    hm = EasyMock.createNiceMock( HostMapper.class );
+    EasyMock.expect( hm.resolveInboundHostName( "test-host" ) ).andReturn( "test-internal-host" ).anyTimes();
+
+    hms = EasyMock.createNiceMock( HostMapperService.class );
+    EasyMock.expect( hms.getHostMapper( "test-cluster" ) ).andReturn( hm ).anyTimes();
+
+    reg = EasyMock.createNiceMock( ServiceRegistry.class );
+    EasyMock.expect( reg.lookupServiceURL( "test-cluster", "test-service" ) ).andReturn( "test-scheme://test-host:777/test-path" ).anyTimes();
+
+    svc = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( svc.getService( GatewayServices.SERVICE_REGISTRY_SERVICE ) ).andReturn( reg ).anyTimes();
+    EasyMock.expect( svc.getService( GatewayServices.HOST_MAPPING_SERVICE ) ).andReturn( hms ).anyTimes();
+
+    env = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( svc ).anyTimes();
+    EasyMock.expect( env.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster" ).anyTimes();
+
+    ctx = EasyMock.createNiceMock( UrlRewriteContext.class );
+    EasyMock.expect( ctx.getDirection() ).andReturn( UrlRewriter.Direction.IN ).anyTimes();
+
+    desc = EasyMock.createNiceMock( ServiceUrlFunctionDescriptor.class );
+
+     HaProvider haProvider = EasyMock.createNiceMock( HaProvider.class );
+
+     EasyMock.expect(env.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(haProvider).anyTimes();
+
+     EasyMock.expect(haProvider.isHaEnabled(EasyMock.anyObject(String.class))).andReturn(Boolean.FALSE).anyTimes();
+
+    EasyMock.replay( hm, hms, reg, svc, env, desc, ctx, haProvider);
+  }
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ServiceUrlFunctionProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ServiceUrlFunctionProcessor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testName() throws Exception {
+    ServiceUrlFunctionProcessor func = new ServiceUrlFunctionProcessor();
+    assertThat( func.name(), is( "serviceUrl" ) );
+  }
+
+  @Test
+  public void testInitialize() throws Exception {
+    ServiceUrlFunctionProcessor func = new ServiceUrlFunctionProcessor();
+    try {
+      func.initialize( null, desc );
+      fail( "Should have thrown an IllegalArgumentException" );
+    } catch( IllegalArgumentException e ) {
+      assertThat( e.getMessage(), containsString( "environment" ) );
+    }
+
+    func = new ServiceUrlFunctionProcessor();
+    try {
+      func.initialize( env, null );
+    } catch( Exception e ) {
+      e.printStackTrace(); //NOTE: OK to use e.printStackTrace for a test failure.
+      fail( "Should not have thrown an exception" );
+    }
+
+    func.initialize( env, desc );
+
+    assertThat( func.cluster(), is( "test-cluster" ) );
+    assertThat( func.registry(), sameInstance( reg ) );
+  }
+
+  @Test
+  public void testDestroy() throws Exception {
+    ServiceUrlFunctionProcessor func = new ServiceUrlFunctionProcessor();
+    func.initialize( env, desc );
+    func.destroy();
+
+    assertThat( func.cluster(), nullValue() );
+    assertThat( func.registry(), nullValue() );
+  }
+
+  @Test
+  public void testResolve() throws Exception {
+    ServiceUrlFunctionProcessor func = new ServiceUrlFunctionProcessor();
+    func.initialize( env, desc );
+
+    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-scheme://test-host:777/test-path" ) );
+    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, null ), nullValue() );
+
+    func.destroy();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/rewrite.xml b/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/rewrite.xml
deleted file mode 100644
index 47ba6e7..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/rewrite.xml
+++ /dev/null
@@ -1,101 +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.
--->
-<rules>
-
-    <rule name="nn-url">
-        <rewrite template="{$serviceUrl[NAMENODE]}"/>
-    </rule>
-
-    <rule name="nn-addr">
-        <rewrite template="{$serviceAddr[NAMENODE]}"/>
-    </rule>
-
-    <rule name="nn-scheme">
-        <rewrite template="{$serviceScheme[NAMENODE]}"/>
-    </rule>
-
-    <rule name="nn-host">
-        <rewrite template="{$serviceHost[NAMENODE]}"/>
-    </rule>
-
-    <rule name="nn-port">
-        <rewrite template="{$servicePort[NAMENODE]}"/>
-    </rule>
-
-    <rule name="nn-path">
-        <rewrite template="{$servicePath[NAMENODE]}"/>
-    </rule>
-
-    <rule name="hdfs-addr">
-        <rewrite template="hdfs://{$serviceAddr[NAMENODE]}"/>
-    </rule>
-
-    <rule name="hdfs-path">
-        <match pattern="{path=**}"/>
-        <rewrite template="hdfs://{$serviceHost[NAMENODE]}:{$servicePort[NAMENODE]}/{path=**}"/>
-    </rule>
-
-    <rule name="jt-addr">
-        <rewrite template="{$serviceAddr[JOBTRACKER]}"/>
-    </rule>
-
-    <filter name="oozie-conf">
-        <content type="*/xml">
-            <buffer path="/configuration/property">
-                <detect path="name" value="nameNode">
-                    <apply path="value" rule="hdfs-addr"/>
-                </detect>
-                <detect path="name" value="jobTracker">
-                    <apply path="value" rule="jt-addr"/>
-                </detect>
-                <detect path="name" value="oozie.wf.application.path">
-                    <apply path="value" rule="hdfs-path"/>
-                </detect>
-                <detect path="name" value="serviceUrl">
-                    <apply path="value" rule="nn-url"/>
-                </detect>
-                <detect path="name" value="serviceAddr">
-                    <apply path="value" rule="nn-addr"/>
-                </detect>
-                <detect path="name" value="serviceScheme">
-                    <apply path="value" rule="nn-scheme"/>
-                </detect>
-                <detect path="name" value="serviceHost">
-                    <apply path="value" rule="nn-host"/>
-                </detect>
-                <detect path="name" value="servicePort">
-                    <apply path="value" rule="nn-port"/>
-                </detect>
-                <detect path="name" value="servicePath">
-                    <apply path="value" rule="nn-path"/>
-                </detect>
-            </buffer>
-        </content>
-        <content type="*/json">
-            <apply path="$.nameNode" rule="hdfs-addr"/>
-            <apply path="$.jobTracker" rule="jt-addr"/>
-            <apply path="$['oozie.wf.application.path']" rule="hdfs-path"/>
-            <apply path="$.serviceUrl" rule="nn-url"/>
-            <apply path="$.serviceAddr" rule="nn-addr"/>
-            <apply path="$.serviceScheme" rule="nn-scheme"/>
-            <apply path="$.serviceHost" rule="nn-host"/>
-            <apply path="$.servicePort" rule="nn-port"/>
-            <apply path="$.servicePath" rule="nn-path"/>
-        </content>
-    </filter>
-
-</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.json b/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.json
deleted file mode 100644
index dcafe6a..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
-  "nameNode":"hdfs://test-nn-host:411",
-  "jobTracker":"test-jt-host:511",
-  "oozie.wf.application.path":"hdfs://test-nn-host:411/tmp/test",
-  "serviceUrl":"test-nn-scheme://test-nn-host:411",
-  "serviceAddr":"test-nn-host:411",
-  "serviceScheme":"test-nn-scheme",
-  "serviceHost":"test-nn-host",
-  "servicePort":"411",
-  "servicePath":"/"
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.xml b/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.xml
deleted file mode 100644
index 189cb54..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<configuration>
-    <property>
-        <name>nameNode</name>
-        <value>hdfs://test-nn-host:411</value>
-    </property>
-    <property>
-        <name>jobTracker</name>
-        <value>test-jt-host:511</value>
-    </property>
-    <property>
-        <name>oozie.wf.application.path</name>
-        <value>hdfs://test-nn-host:411/tmp/test</value>
-    </property>
-
-    <property>
-        <name>serviceUrl</name>
-        <value>test-nn-scheme://test-nn-host:411</value>
-    </property>
-    <property>
-        <name>serviceAddr</name>
-        <value>test-nn-host:411</value>
-    </property>
-    <property>
-        <name>serviceScheme</name>
-        <value>test-nn-scheme</value>
-    </property>
-    <property>
-        <name>serviceHost</name>
-        <value>test-nn-host</value>
-    </property>
-    <property>
-        <name>servicePort</name>
-        <value>411</value>
-    </property>
-    <property>
-        <name>servicePath</name>
-        <value>/</value>
-    </property>
-
-</configuration>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.json b/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.json
deleted file mode 100644
index 28700e0..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
-  "nameNode":"default",
-  "jobTracker":"default",
-  "oozie.wf.application.path":"/tmp/test",
-  "serviceUrl":"",
-  "serviceAddr":"",
-  "serviceScheme":"",
-  "serviceHost":"",
-  "servicePort":"",
-  "servicePath":""
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.xml b/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.xml
deleted file mode 100644
index 2c0d824..0000000
--- a/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/hadoop/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<configuration>
-    <property>
-        <name>nameNode</name>
-        <value>default</value>
-    </property>
-    <property>
-        <name>jobTracker</name>
-        <value>default</value>
-    </property>
-    <property>
-        <name>oozie.wf.application.path</name>
-        <value>/tmp/test</value>
-    </property>
-
-    <property>
-        <name>serviceUrl</name>
-        <value></value>
-    </property>
-    <property>
-        <name>serviceAddr</name>
-        <value></value>
-    </property>
-    <property>
-        <name>serviceScheme</name>
-        <value></value>
-    </property>
-    <property>
-        <name>serviceHost</name>
-        <value></value>
-    </property>
-    <property>
-        <name>servicePort</name>
-        <value></value>
-    </property>
-    <property>
-        <name>servicePath</name>
-        <value></value>
-    </property>
-
-</configuration>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/rewrite.xml b/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/rewrite.xml
new file mode 100644
index 0000000..47ba6e7
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/rewrite.xml
@@ -0,0 +1,101 @@
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one or more
+  contributor license agreements.  See the NOTICE file distributed with
+  this work for additional information regarding copyright ownership.
+  The ASF licenses this file to You under the Apache License, Version 2.0
+  (the "License"); you may not use this file except in compliance with
+  the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+-->
+<rules>
+
+    <rule name="nn-url">
+        <rewrite template="{$serviceUrl[NAMENODE]}"/>
+    </rule>
+
+    <rule name="nn-addr">
+        <rewrite template="{$serviceAddr[NAMENODE]}"/>
+    </rule>
+
+    <rule name="nn-scheme">
+        <rewrite template="{$serviceScheme[NAMENODE]}"/>
+    </rule>
+
+    <rule name="nn-host">
+        <rewrite template="{$serviceHost[NAMENODE]}"/>
+    </rule>
+
+    <rule name="nn-port">
+        <rewrite template="{$servicePort[NAMENODE]}"/>
+    </rule>
+
+    <rule name="nn-path">
+        <rewrite template="{$servicePath[NAMENODE]}"/>
+    </rule>
+
+    <rule name="hdfs-addr">
+        <rewrite template="hdfs://{$serviceAddr[NAMENODE]}"/>
+    </rule>
+
+    <rule name="hdfs-path">
+        <match pattern="{path=**}"/>
+        <rewrite template="hdfs://{$serviceHost[NAMENODE]}:{$servicePort[NAMENODE]}/{path=**}"/>
+    </rule>
+
+    <rule name="jt-addr">
+        <rewrite template="{$serviceAddr[JOBTRACKER]}"/>
+    </rule>
+
+    <filter name="oozie-conf">
+        <content type="*/xml">
+            <buffer path="/configuration/property">
+                <detect path="name" value="nameNode">
+                    <apply path="value" rule="hdfs-addr"/>
+                </detect>
+                <detect path="name" value="jobTracker">
+                    <apply path="value" rule="jt-addr"/>
+                </detect>
+                <detect path="name" value="oozie.wf.application.path">
+                    <apply path="value" rule="hdfs-path"/>
+                </detect>
+                <detect path="name" value="serviceUrl">
+                    <apply path="value" rule="nn-url"/>
+                </detect>
+                <detect path="name" value="serviceAddr">
+                    <apply path="value" rule="nn-addr"/>
+                </detect>
+                <detect path="name" value="serviceScheme">
+                    <apply path="value" rule="nn-scheme"/>
+                </detect>
+                <detect path="name" value="serviceHost">
+                    <apply path="value" rule="nn-host"/>
+                </detect>
+                <detect path="name" value="servicePort">
+                    <apply path="value" rule="nn-port"/>
+                </detect>
+                <detect path="name" value="servicePath">
+                    <apply path="value" rule="nn-path"/>
+                </detect>
+            </buffer>
+        </content>
+        <content type="*/json">
+            <apply path="$.nameNode" rule="hdfs-addr"/>
+            <apply path="$.jobTracker" rule="jt-addr"/>
+            <apply path="$['oozie.wf.application.path']" rule="hdfs-path"/>
+            <apply path="$.serviceUrl" rule="nn-url"/>
+            <apply path="$.serviceAddr" rule="nn-addr"/>
+            <apply path="$.serviceScheme" rule="nn-scheme"/>
+            <apply path="$.serviceHost" rule="nn-host"/>
+            <apply path="$.servicePort" rule="nn-port"/>
+            <apply path="$.servicePath" rule="nn-path"/>
+        </content>
+    </filter>
+
+</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.json b/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.json
new file mode 100644
index 0000000..dcafe6a
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.json
@@ -0,0 +1,11 @@
+{
+  "nameNode":"hdfs://test-nn-host:411",
+  "jobTracker":"test-jt-host:511",
+  "oozie.wf.application.path":"hdfs://test-nn-host:411/tmp/test",
+  "serviceUrl":"test-nn-scheme://test-nn-host:411",
+  "serviceAddr":"test-nn-host:411",
+  "serviceScheme":"test-nn-scheme",
+  "serviceHost":"test-nn-host",
+  "servicePort":"411",
+  "servicePath":"/"
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.xml b/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.xml
new file mode 100644
index 0000000..189cb54
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-expect-body.xml
@@ -0,0 +1,40 @@
+<configuration>
+    <property>
+        <name>nameNode</name>
+        <value>hdfs://test-nn-host:411</value>
+    </property>
+    <property>
+        <name>jobTracker</name>
+        <value>test-jt-host:511</value>
+    </property>
+    <property>
+        <name>oozie.wf.application.path</name>
+        <value>hdfs://test-nn-host:411/tmp/test</value>
+    </property>
+
+    <property>
+        <name>serviceUrl</name>
+        <value>test-nn-scheme://test-nn-host:411</value>
+    </property>
+    <property>
+        <name>serviceAddr</name>
+        <value>test-nn-host:411</value>
+    </property>
+    <property>
+        <name>serviceScheme</name>
+        <value>test-nn-scheme</value>
+    </property>
+    <property>
+        <name>serviceHost</name>
+        <value>test-nn-host</value>
+    </property>
+    <property>
+        <name>servicePort</name>
+        <value>411</value>
+    </property>
+    <property>
+        <name>servicePath</name>
+        <value>/</value>
+    </property>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.json
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.json b/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.json
new file mode 100644
index 0000000..28700e0
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.json
@@ -0,0 +1,11 @@
+{
+  "nameNode":"default",
+  "jobTracker":"default",
+  "oozie.wf.application.path":"/tmp/test",
+  "serviceUrl":"",
+  "serviceAddr":"",
+  "serviceScheme":"",
+  "serviceHost":"",
+  "servicePort":"",
+  "servicePath":""
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.xml b/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.xml
new file mode 100644
index 0000000..2c0d824
--- /dev/null
+++ b/gateway-provider-rewrite-func-service-registry/src/test/resources/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest/test-input-body.xml
@@ -0,0 +1,40 @@
+<configuration>
+    <property>
+        <name>nameNode</name>
+        <value>default</value>
+    </property>
+    <property>
+        <name>jobTracker</name>
+        <value>default</value>
+    </property>
+    <property>
+        <name>oozie.wf.application.path</name>
+        <value>/tmp/test</value>
+    </property>
+
+    <property>
+        <name>serviceUrl</name>
+        <value></value>
+    </property>
+    <property>
+        <name>serviceAddr</name>
+        <value></value>
+    </property>
+    <property>
+        <name>serviceScheme</name>
+        <value></value>
+    </property>
+    <property>
+        <name>serviceHost</name>
+        <value></value>
+    </property>
+    <property>
+        <name>servicePort</name>
+        <value></value>
+    </property>
+    <property>
+        <name>servicePath</name>
+        <value></value>
+    </property>
+
+</configuration>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/EncryptStepContextParams.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/EncryptStepContextParams.java b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/EncryptStepContextParams.java
deleted file mode 100644
index 6df13eb..0000000
--- a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/EncryptStepContextParams.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.hadoop.gateway.encrypturi;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.hadoop.gateway.util.urltemplate.Params;
-
-public class EncryptStepContextParams implements Params {
-  Map<String, List<String>> params = new HashMap<>();
-
-  public EncryptStepContextParams() {
-  }
-
-  @Override
-  public List<String> resolve( String name ) {
-    return params.get( name );
-  }
-
-  @Override
-  public Set<String> getNames() {
-    return params.keySet();
-  }
-
-  public void addParam( String name, List<String> values ) {
-    params.put( name, values );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/EncryptUriMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/EncryptUriMessages.java b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/EncryptUriMessages.java
deleted file mode 100644
index d7550e4..0000000
--- a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/EncryptUriMessages.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.encrypturi;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-import org.apache.hadoop.gateway.i18n.messages.StackTrace;
-
-@Messages(logger="org.apache.hadoop.gateway.encrypturi")
-public interface EncryptUriMessages {
-
-  @Message( level = MessageLevel.ERROR, text = "Failed to create or verify the presence of a password for URL encryption: {0}" )
-  void unableCreatePasswordForEncryption(@StackTrace( level = MessageLevel.DEBUG ) Exception e);
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/api/DecryptUriDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/api/DecryptUriDescriptor.java b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/api/DecryptUriDescriptor.java
deleted file mode 100644
index 01dd38f..0000000
--- a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/api/DecryptUriDescriptor.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.hadoop.gateway.encrypturi.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
-
-public class DecryptUriDescriptor extends UrlRewriteActionDescriptorBase
-    implements UrlRewriteActionDescriptor {
-  public static final String STEP_NAME = "decrypt";
-  private String param;
-
-  public DecryptUriDescriptor() {
-    super( STEP_NAME );
-  }
-
-  public String getParam() {
-    return param;
-  }
-
-  public void setParam( String param ) {
-    this.param = param;
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/api/EncryptUriDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/api/EncryptUriDescriptor.java b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/api/EncryptUriDescriptor.java
deleted file mode 100644
index 4584d24..0000000
--- a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/api/EncryptUriDescriptor.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.hadoop.gateway.encrypturi.api;
-
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
-
-public class EncryptUriDescriptor extends UrlRewriteActionDescriptorBase
-    implements UrlRewriteActionDescriptor {
-  public static final String STEP_NAME = "encrypt";
-  public static final String PASSWORD_ALIAS = "encryptQueryString";
-  private String template;
-  private String param;
-
-  public EncryptUriDescriptor() {
-    super( STEP_NAME );
-  }
-
-  public String getTemplate() {
-    return template;
-  }
-
-  public void setTemplate( String template ) {
-    this.template = template;
-  }
-
-  public String getParam() {
-    return param;
-  }
-
-  public void setParam( String param ) {
-    this.param = param;
-  }
-}


[05/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxLdapRealm.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxLdapRealm.java b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxLdapRealm.java
new file mode 100644
index 0000000..8c99358
--- /dev/null
+++ b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxLdapRealm.java
@@ -0,0 +1,768 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT 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.knox.gateway.shirorealm;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.naming.AuthenticationException;
+import javax.naming.Context;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.PartialResultException;
+import javax.naming.SizeLimitExceededException;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+import javax.naming.ldap.Control;
+import javax.naming.ldap.LdapContext;
+import javax.naming.ldap.LdapName;
+import javax.naming.ldap.PagedResultsControl;
+import javax.naming.ldap.PagedResultsResponseControl;
+
+import org.apache.knox.gateway.GatewayMessages;
+import org.apache.knox.gateway.audit.api.Action;
+import org.apache.knox.gateway.audit.api.ActionOutcome;
+import org.apache.knox.gateway.audit.api.AuditService;
+import org.apache.knox.gateway.audit.api.AuditServiceFactory;
+import org.apache.knox.gateway.audit.api.Auditor;
+import org.apache.knox.gateway.audit.api.ResourceType;
+import org.apache.knox.gateway.audit.log4j.audit.AuditConstants;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.shirorealm.impl.i18n.KnoxShiroMessages;
+import org.apache.shiro.SecurityUtils;
+import org.apache.shiro.authc.AuthenticationInfo;
+import org.apache.shiro.authc.AuthenticationToken;
+import org.apache.shiro.authc.SimpleAuthenticationInfo;
+import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
+import org.apache.shiro.authz.AuthorizationInfo;
+import org.apache.shiro.authz.SimpleAuthorizationInfo;
+import org.apache.shiro.crypto.hash.DefaultHashService;
+import org.apache.shiro.crypto.hash.Hash;
+import org.apache.shiro.crypto.hash.HashRequest;
+import org.apache.shiro.crypto.hash.HashService;
+import org.apache.shiro.realm.ldap.JndiLdapRealm;
+import org.apache.shiro.realm.ldap.LdapContextFactory;
+import org.apache.shiro.realm.ldap.LdapUtils;
+import org.apache.shiro.subject.MutablePrincipalCollection;
+import org.apache.shiro.subject.PrincipalCollection;
+import org.apache.shiro.util.StringUtils;
+
+/**
+ * Implementation of {@link org.apache.shiro.realm.ldap.JndiLdapRealm} that also
+ * returns each user's groups.
+ * This implementation is heavily based on org.apache.isis.security.shiro.IsisLdapRealm.
+ * 
+ * This implementation saves looked up ldap groups in Shiro Session to make them
+ * easy to be looked up outside of this object
+ * 
+ * <p>
+ * Sample config for <tt>shiro.ini</tt>:
+ * 
+ * [main]
+ * ldapRealm=KnoxLdapRealm
+ * ldapGroupContextFactory=KnoxLdapContextFactory
+ * ldapRealm.contextFactory=$ldapGroupContextFactory
+ * ldapRealm.contextFactory.authenticationMechanism=simple
+ * ldapRealm.contextFactory.url=ldap://localhost:33389
+ * ldapRealm.userDnTemplate=uid={0},ou=people,dc=hadoop,dc=apache,dc=org
+ * ldapRealm.authorizationEnabled=true
+ * ldapRealm.contextFactory.systemAuthenticationMechanism=simple
+ * ldapRealm.searchBase=ou=groups,dc=hadoop,dc=apache,dc=org
+ * ldapRealm.groupObjectClass=groupofnames
+ * ldapRealm.memberAttribute=member
+ * ldapRealm.memberAttributeValueTemplate=cn={0},ou=people,dc=hadoop,dc=apache,dc=org
+ * ldapRealm.contextFactory.systemUsername=uid=guest,ou=people,dc=hadoop,dc=apache,dc=org
+ * ldapRealm.contextFactory.clusterName=sandbox
+ * ldapRealm.contextFactory.systemPassword=S{ALIAS=ldcSystemPassword}
+ * [urls]
+ * **=authcBasic
+ *
+ * # optional mapping from physical groups to logical application roles
+ * ldapRealm.rolesByGroup = \
+ *    LDN_USERS: user_role,\
+ *    NYK_USERS: user_role,\
+ *    HKG_USERS: user_role,\
+ *    GLOBAL_ADMIN: admin_role,\
+ *    DEMOS: self-install_role
+ * 
+ * ldapRealm.permissionsByRole=\
+ *    user_role = *:ToDoItemsJdo:*:*,\
+ *                *:ToDoItem:*:*; \
+ *    self-install_role = *:ToDoItemsFixturesService:install:* ; \
+ *    admin_role = *
+ * 
+ * securityManager.realms = $ldapRealm
+ * 
+ * </pre>
+ */
+public class KnoxLdapRealm extends JndiLdapRealm {
+
+    private static GatewayMessages LOG = MessagesFactory.get( GatewayMessages.class );
+    KnoxShiroMessages ShiroLog = MessagesFactory.get( KnoxShiroMessages.class );
+    private static AuditService auditService = AuditServiceFactory.getAuditService();
+    private static Auditor auditor = auditService.getAuditor(
+        AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
+        AuditConstants.KNOX_COMPONENT_NAME );
+
+    private static Pattern TEMPLATE_PATTERN = Pattern.compile( "\\{(\\d+?)\\}" );
+    private static String DEFAULT_PRINCIPAL_REGEX = "(.*)";
+    private static final String MEMBER_SUBSTITUTION_TOKEN = "{0}";
+
+    private static final SearchControls SUBTREE_SCOPE = new SearchControls();
+    private static final SearchControls ONELEVEL_SCOPE = new SearchControls();
+    private static final SearchControls OBJECT_SCOPE = new SearchControls();
+
+    private static final String  SUBJECT_USER_ROLES = "subject.userRoles";
+    private static final String  SUBJECT_USER_GROUPS = "subject.userGroups";
+
+    private static final String  MEMBER_URL = "memberUrl";
+
+    private static final String POSIX_GROUP = "posixGroup";
+
+    private static final String HASHING_ALGORITHM = "SHA-256";
+
+    static {
+          SUBTREE_SCOPE.setSearchScope(SearchControls.SUBTREE_SCOPE);
+          ONELEVEL_SCOPE.setSearchScope(SearchControls.ONELEVEL_SCOPE);
+          OBJECT_SCOPE.setSearchScope( SearchControls.OBJECT_SCOPE );
+      }
+
+ 
+    private String searchBase;
+    private String userSearchBase;
+    private String principalRegex = DEFAULT_PRINCIPAL_REGEX;
+    private Pattern principalPattern = Pattern.compile( DEFAULT_PRINCIPAL_REGEX );
+    private String userDnTemplate = "{0}";
+    private String userSearchFilter = null;
+    private String userSearchAttributeTemplate = "{0}";
+    private String userSearchScope = "subtree";
+
+    private String groupSearchBase;
+
+    private String groupObjectClass = "groupOfNames";
+    
+    //  typical value: member, uniqueMember, meberUrl
+    private String memberAttribute = "member";
+
+    private String groupIdAttribute = "cn";
+    
+    private String memberAttributeValuePrefix = "uid={0}";
+    private String memberAttributeValueSuffix = "";
+    
+    private final Map<String,String> rolesByGroup = new LinkedHashMap<String, String>();
+    private final Map<String,List<String>> permissionsByRole = new LinkedHashMap<String, List<String>>();
+    
+    private boolean authorizationEnabled;
+
+    private String userSearchAttributeName;
+    private String userObjectClass = "person";
+
+    private HashService hashService = new DefaultHashService();
+
+    public KnoxLdapRealm() {
+      HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher(HASHING_ALGORITHM);
+      setCredentialsMatcher(credentialsMatcher);
+    }
+
+  @Override
+  //KNOX-534 overriding this method to be able to audit authentication exceptions
+  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws org.apache.shiro.authc.AuthenticationException {
+    try {
+      return super.doGetAuthenticationInfo(token);
+    } catch ( org.apache.shiro.authc.AuthenticationException e ) {
+      auditor.audit( Action.AUTHENTICATION , token.getPrincipal().toString(), ResourceType.PRINCIPAL, ActionOutcome.FAILURE, e.getMessage() );
+      ShiroLog.failedLoginInfo(token);
+      ShiroLog.failedLoginStackTrace(e);
+      ShiroLog.failedLoginAttempt(e.getCause());
+
+      throw e;
+    }
+  }
+
+  /**
+     * Get groups from LDAP.
+     * 
+     * @param principals
+     *            the principals of the Subject whose AuthenticationInfo should
+     *            be queried from the LDAP server.
+     * @param ldapContextFactory
+     *            factory used to retrieve LDAP connections.
+     * @return an {@link AuthorizationInfo} instance containing information
+     *         retrieved from the LDAP server.
+     * @throws NamingException
+     *             if any LDAP errors occur during the search.
+     */
+    @Override
+    protected AuthorizationInfo queryForAuthorizationInfo(final PrincipalCollection principals, 
+        final LdapContextFactory ldapContextFactory) throws NamingException {
+      if (!isAuthorizationEnabled()) {
+        return null;
+      }
+      final Set<String> roleNames = getRoles(principals, ldapContextFactory);
+        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(roleNames);
+        Set<String> stringPermissions = permsFor(roleNames);
+        simpleAuthorizationInfo.setStringPermissions(stringPermissions);
+        return simpleAuthorizationInfo;
+    }
+
+    private Set<String> getRoles(PrincipalCollection principals,
+        final LdapContextFactory ldapContextFactory) throws NamingException {
+        final String username = (String) getAvailablePrincipal(principals);
+
+        LdapContext systemLdapCtx = null;
+        try {
+            systemLdapCtx = ldapContextFactory.getSystemLdapContext();
+            return rolesFor(principals, username, systemLdapCtx, ldapContextFactory);
+        } catch (AuthenticationException e) {
+          LOG.failedToGetSystemLdapConnection(e);
+          return Collections.emptySet();
+        } finally {
+            LdapUtils.closeContext(systemLdapCtx);
+        }
+    }
+
+    private Set<String> rolesFor(PrincipalCollection principals, final String userName, final LdapContext ldapCtx,
+        final LdapContextFactory ldapContextFactory) throws NamingException {
+      final Set<String> roleNames = new HashSet<>();
+      final Set<String> groupNames = new HashSet<>();
+
+      String userDn;
+      if (userSearchAttributeName == null || userSearchAttributeName.isEmpty()) {
+        // memberAttributeValuePrefix and memberAttributeValueSuffix were computed from memberAttributeValueTemplate
+        userDn = memberAttributeValuePrefix + userName + memberAttributeValueSuffix;
+      } else {
+        userDn = getUserDn(userName);
+      }
+
+      // Activate paged results
+      int pageSize = 100;
+      int numResults = 0;
+      byte[] cookie = null;
+      try {
+        ldapCtx.addToEnvironment(Context.REFERRAL, "ignore");
+
+        ldapCtx.setRequestControls(new Control[]{new PagedResultsControl(pageSize, Control.NONCRITICAL)});
+
+        do {
+          // ldapsearch -h localhost -p 33389 -D uid=guest,ou=people,dc=hadoop,dc=apache,dc=org -w  guest-password
+          //       -b dc=hadoop,dc=apache,dc=org -s sub '(objectclass=*)'
+
+          NamingEnumeration<SearchResult> searchResultEnum = null;
+          try {
+            searchResultEnum = ldapCtx.search(
+                getGroupSearchBase(),
+                "objectClass=" + groupObjectClass,
+                SUBTREE_SCOPE);
+
+            while (searchResultEnum != null && searchResultEnum.hasMore()) { // searchResults contains all the groups in search scope
+              numResults++;
+              final SearchResult group = searchResultEnum.next();
+              addRoleIfMember(userDn, group, roleNames, groupNames, ldapContextFactory);
+            }
+          } catch (PartialResultException e) {
+            LOG.ignoringPartialResultException();
+          } finally {
+            if (searchResultEnum != null) {
+              searchResultEnum.close();
+            }
+          }
+
+          // Examine the paged results control response
+          Control[] controls = ldapCtx.getResponseControls();
+          if (controls != null) {
+            for (Control control : controls) {
+              if (control instanceof PagedResultsResponseControl) {
+                PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
+                cookie = prrc.getCookie();
+              }
+            }
+          }
+
+          // Re-activate paged results
+          ldapCtx.setRequestControls(new Control[]{new PagedResultsControl(pageSize, cookie, Control.CRITICAL)});
+        } while (cookie != null);
+      } catch (SizeLimitExceededException e) {
+        LOG.sizeLimitExceededOnlyRetrieved(numResults);
+//        System.out.println("Only retrieved first " + numResults + " groups due to SizeLimitExceededException.");
+      } catch(IOException e) {
+        LOG.unableToSetupPagedResults();
+//        System.out.println("Unabled to setup paged results");
+      }
+
+      // save role names and group names in session so that they can be easily looked up outside of this object
+      SecurityUtils.getSubject().getSession().setAttribute(SUBJECT_USER_ROLES, roleNames);
+      SecurityUtils.getSubject().getSession().setAttribute(SUBJECT_USER_GROUPS, groupNames);
+      if (!groupNames.isEmpty() && (principals instanceof MutablePrincipalCollection)) {
+        ((MutablePrincipalCollection)principals).addAll(groupNames, getName());
+      }
+      LOG.lookedUpUserRoles(roleNames, userName);
+
+      return roleNames;
+    }
+
+  private void addRoleIfMember(final String userDn, final SearchResult group,
+      final Set<String> roleNames, final Set<String> groupNames,
+      final LdapContextFactory ldapContextFactory) throws NamingException {
+
+    NamingEnumeration<? extends Attribute> attributeEnum = null;
+    NamingEnumeration<?> e = null;
+    try {
+      LdapName userLdapDn = new LdapName(userDn);
+      Attribute attribute = group.getAttributes().get(getGroupIdAttribute());
+      String groupName = attribute.get().toString();
+      
+      attributeEnum = group
+          .getAttributes().getAll();
+      while (attributeEnum.hasMore()) {
+        final Attribute attr = attributeEnum.next();
+        if (!memberAttribute.equalsIgnoreCase(attr.getID())) {
+          continue;
+        }
+        e = attr.getAll();
+        while (e.hasMore()) {
+          String attrValue = e.next().toString();
+          if (memberAttribute.equalsIgnoreCase(MEMBER_URL)) {
+            boolean dynamicGroupMember = isUserMemberOfDynamicGroup(userLdapDn,
+                attrValue, // memberUrl value
+                ldapContextFactory);
+            if (dynamicGroupMember) {
+              groupNames.add(groupName);
+              String roleName = roleNameFor(groupName);
+              if (roleName != null) {
+                roleNames.add(roleName);
+              } else {
+                roleNames.add(groupName);
+              }
+            }
+          } else {
+            if (groupObjectClass.equalsIgnoreCase(POSIX_GROUP)){
+              attrValue = memberAttributeValuePrefix + attrValue + memberAttributeValueSuffix;
+            }
+            if (userLdapDn.equals(new LdapName(attrValue))) {
+              groupNames.add(groupName);
+              String roleName = roleNameFor(groupName);
+              if (roleName != null) {
+                roleNames.add(roleName);
+              } else {
+                roleNames.add(groupName);
+              }
+              break;
+            }
+          }
+        }
+      }
+    }
+    finally {
+      try {
+        if (attributeEnum != null) {
+          attributeEnum.close();
+        }
+      }
+      finally {
+        if (e != null) {
+          e.close();
+        }
+      }
+    }
+  }
+
+    private String roleNameFor(String groupName) {
+        return !rolesByGroup.isEmpty() ? rolesByGroup.get(groupName) : groupName;
+    }
+
+
+    private Set<String> permsFor(Set<String> roleNames) {
+        Set<String> perms = new LinkedHashSet<String>(); // preserve order
+        for(String role: roleNames) {
+            List<String> permsForRole = permissionsByRole.get(role);
+            if(permsForRole != null) {
+                perms.addAll(permsForRole);
+            }
+        }
+        return perms;
+    }
+
+    public String getSearchBase() {
+        return searchBase;
+    }
+
+    public void setSearchBase(String searchBase) {
+      this.searchBase = searchBase;
+    }
+
+    public String getUserSearchBase() {
+      return  (userSearchBase != null && !userSearchBase.isEmpty()) ? 
+          userSearchBase : searchBase;
+    }
+
+    public void setUserSearchBase(String userSearchBase) {
+      this.userSearchBase = userSearchBase;
+    }
+
+    public String getGroupSearchBase() {
+      return (groupSearchBase != null && !groupSearchBase.isEmpty()) ? 
+          groupSearchBase : searchBase;
+    }
+
+    public void setGroupSearchBase(String groupSearchBase) {
+      this.groupSearchBase = groupSearchBase;
+    }
+
+    public String getGroupObjectClass() {
+      return groupObjectClass;
+    }
+    
+    public void setGroupObjectClass(String groupObjectClassAttribute) {
+        this.groupObjectClass = groupObjectClassAttribute;
+    }
+
+    public String getMemberAttribute() {
+      return memberAttribute;
+    }
+    
+    public void setMemberAttribute(String memberAttribute) {
+        this.memberAttribute = memberAttribute;
+    }
+    
+    public String getGroupIdAttribute() {
+      return groupIdAttribute;
+    }
+    
+    public void setGroupIdAttribute(String groupIdAttribute) {
+        this.groupIdAttribute = groupIdAttribute;
+    }
+    
+    public void setMemberAttributeValueTemplate(String template) {
+        if (!StringUtils.hasText(template)) {
+            String msg = "User DN template cannot be null or empty.";
+            throw new IllegalArgumentException(msg);
+        }
+        int index = template.indexOf(MEMBER_SUBSTITUTION_TOKEN);
+        if (index < 0) {
+            String msg = "Member attribute value template must contain the '" +
+                    MEMBER_SUBSTITUTION_TOKEN + "' replacement token to understand how to " +
+                    "parse the group members.";
+            throw new IllegalArgumentException(msg);
+        }
+        String prefix = template.substring(0, index);
+        String suffix = template.substring(prefix.length() + MEMBER_SUBSTITUTION_TOKEN.length());
+        this.memberAttributeValuePrefix = prefix;
+        this.memberAttributeValueSuffix = suffix;
+    }
+
+    public void setRolesByGroup(Map<String, String> rolesByGroup) {
+        this.rolesByGroup.putAll(rolesByGroup);
+    }
+
+    public void setPermissionsByRole(String permissionsByRoleStr) {
+        permissionsByRole.putAll(parsePermissionByRoleString(permissionsByRoleStr));
+    }
+    
+    public boolean isAuthorizationEnabled() {
+      return authorizationEnabled;
+    }
+
+    public void setAuthorizationEnabled(boolean authorizationEnabled) {
+      this.authorizationEnabled = authorizationEnabled;
+    }
+
+    public String getUserSearchAttributeName() {
+        return userSearchAttributeName;
+    }
+
+    public void setUserSearchAttributeName(String userSearchAttributeName) {
+      if (userSearchAttributeName != null) {
+        userSearchAttributeName = userSearchAttributeName.trim();
+      }
+      this.userSearchAttributeName = userSearchAttributeName;
+    }
+
+    public String getUserObjectClass() {
+      return userObjectClass;
+    }
+    
+    public void setUserObjectClass(String userObjectClass) {
+        this.userObjectClass = userObjectClass;
+    }
+
+    private Map<String, List<String>> parsePermissionByRoleString(String permissionsByRoleStr) {
+      Map<String,List<String>> perms = new HashMap<>();
+   
+      // split by semicolon ; then by eq = then by  comma ,
+      StringTokenizer stSem = new StringTokenizer(permissionsByRoleStr, ";");
+      while (stSem.hasMoreTokens()) {
+        String roleAndPerm = stSem.nextToken();
+        StringTokenizer stEq = new StringTokenizer(roleAndPerm, "=");
+        if (stEq.countTokens() != 2) {
+          continue;
+        }
+        String role = stEq.nextToken().trim();
+        String perm = stEq.nextToken().trim();
+        StringTokenizer stCom = new StringTokenizer(perm, ",");
+        List<String> permList = new ArrayList<String>();
+        while (stCom.hasMoreTokens()) {
+          permList.add(stCom.nextToken().trim());
+        }
+        perms.put(role,  permList);
+      }
+      return perms;
+  }
+
+  boolean isUserMemberOfDynamicGroup(LdapName userLdapDn, String memberUrl,
+      final LdapContextFactory ldapContextFactory) throws NamingException {
+
+    // ldap://host:port/dn?attributes?scope?filter?extensions
+
+    boolean member = false;
+
+    if (memberUrl == null) {
+      return false;
+    }
+    String[] tokens = memberUrl.split("\\?");
+    if (tokens.length < 4) {
+      return false;
+    }
+
+    String searchBaseString = tokens[0]
+        .substring(tokens[0].lastIndexOf("/") + 1);
+    String searchScope = tokens[2];
+    String searchFilter = tokens[3];
+
+    LdapName searchBaseDn = new LdapName(searchBaseString);
+
+    // do scope test
+    if (searchScope.equalsIgnoreCase("base")) {
+      return false;
+    }
+    if (!userLdapDn.toString().endsWith(searchBaseDn.toString())) {
+      return false;
+    }
+    if (searchScope.equalsIgnoreCase("one")
+        && (userLdapDn.size() != searchBaseDn.size() - 1)) {
+      return false;
+    }
+    // search for the filter, substituting base with userDn
+    // search for base_dn=userDn, scope=base, filter=filter
+    LdapContext systemLdapCtx = null;
+    systemLdapCtx = ldapContextFactory.getSystemLdapContext();
+    NamingEnumeration<SearchResult> searchResultEnum = null;
+    try {
+      searchResultEnum = systemLdapCtx
+        .search(userLdapDn, searchFilter,
+            searchScope.equalsIgnoreCase("sub") ? SUBTREE_SCOPE
+                : ONELEVEL_SCOPE);
+      if (searchResultEnum.hasMore()) {
+        return true;
+      }
+    }
+    finally {
+        try {
+          if (searchResultEnum != null) {
+            searchResultEnum.close();
+          }
+        }
+        finally {
+          LdapUtils.closeContext(systemLdapCtx);
+        }
+    }
+    return member;
+  }
+
+  public String getPrincipalRegex() {
+    return principalRegex;
+  }
+
+  public void setPrincipalRegex( String regex ) {
+    if( regex == null || regex.trim().isEmpty() ) {
+      principalPattern = Pattern.compile( DEFAULT_PRINCIPAL_REGEX );
+      principalRegex = DEFAULT_PRINCIPAL_REGEX;
+    } else {
+      regex = regex.trim();
+      Pattern pattern = Pattern.compile( regex );
+      principalPattern = pattern;
+      principalRegex = regex;
+    }
+  }
+
+  public String getUserSearchAttributeTemplate() {
+    return userSearchAttributeTemplate;
+  }
+
+  public void setUserSearchAttributeTemplate( final String template ) {
+    this.userSearchAttributeTemplate = ( template == null ? null : template.trim() );
+  }
+
+  public String getUserSearchFilter() {
+    return userSearchFilter;
+  }
+
+  public void setUserSearchFilter( final String filter ) {
+    this.userSearchFilter = ( filter == null ? null : filter.trim() );
+  }
+
+  public String getUserSearchScope() {
+    return userSearchScope;
+  }
+
+  public void setUserSearchScope( final String scope ) {
+    this.userSearchScope = ( scope == null ? null : scope.trim().toLowerCase() );
+  }
+
+  private SearchControls getUserSearchControls() {
+    SearchControls searchControls = SUBTREE_SCOPE;
+    if ( "onelevel".equalsIgnoreCase( userSearchScope ) ) {
+      searchControls = ONELEVEL_SCOPE;
+    } else if ( "object".equalsIgnoreCase( userSearchScope ) ) {
+      searchControls = OBJECT_SCOPE;
+    }
+    return searchControls;
+  }
+
+  @Override
+  public void setUserDnTemplate( final String template ) throws IllegalArgumentException {
+    userDnTemplate = template;
+  }
+
+  private Matcher matchPrincipal( final String principal ) {
+    Matcher matchedPrincipal = principalPattern.matcher( principal );
+    if( !matchedPrincipal.matches() ) {
+      throw new IllegalArgumentException( "Principal " + principal + " does not match " + principalRegex );
+    }
+    return matchedPrincipal;
+  }
+
+  /**
+     * Returns the LDAP User Distinguished Name (DN) to use when acquiring an
+     * {@link javax.naming.ldap.LdapContext LdapContext} from the {@link LdapContextFactory}.
+     * <p/>
+     * If the the {@link #getUserDnTemplate() userDnTemplate} property has been set, this implementation will construct
+     * the User DN by substituting the specified {@code principal} into the configured template.  If the
+     * {@link #getUserDnTemplate() userDnTemplate} has not been set, the method argument will be returned directly
+     * (indicating that the submitted authentication token principal <em>is</em> the User DN).
+     *
+     * @param principal the principal to substitute into the configured {@link #getUserDnTemplate() userDnTemplate}.
+     * @return the constructed User DN to use at runtime when acquiring an {@link javax.naming.ldap.LdapContext}.
+     * @throws IllegalArgumentException if the method argument is null or empty
+     * @throws IllegalStateException    if the {@link #getUserDnTemplate userDnTemplate} has not been set.
+     * @see LdapContextFactory#getLdapContext(Object, Object)
+     */
+    @Override
+    protected String getUserDn( final String principal ) throws IllegalArgumentException, IllegalStateException {
+      String userDn;
+      Matcher matchedPrincipal = matchPrincipal( principal );
+      String userSearchBase = getUserSearchBase();
+      String userSearchAttributeName = getUserSearchAttributeName();
+
+      // If not searching use the userDnTemplate and return.
+      if ( ( userSearchBase == null || userSearchBase.isEmpty() ) ||
+          ( userSearchAttributeName == null &&
+              userSearchFilter == null &&
+              !"object".equalsIgnoreCase( userSearchScope ) ) ) {
+        userDn = expandTemplate( userDnTemplate, matchedPrincipal );
+        LOG.computedUserDn( userDn, principal );
+        return userDn;
+      }
+
+      // Create the searchBase and searchFilter from config.
+      String searchBase = expandTemplate( getUserSearchBase(), matchedPrincipal );
+      String searchFilter = null;
+      if ( userSearchFilter == null ) {
+        if ( userSearchAttributeName == null ) {
+          searchFilter = String.format( "(objectclass=%1$s)", getUserObjectClass() );
+        } else {
+          searchFilter = String.format(
+              "(&(objectclass=%1$s)(%2$s=%3$s))",
+              getUserObjectClass(),
+              userSearchAttributeName,
+              expandTemplate( getUserSearchAttributeTemplate(), matchedPrincipal ) );
+        }
+      } else {
+        searchFilter = expandTemplate( userSearchFilter, matchedPrincipal );
+      }
+      SearchControls searchControls = getUserSearchControls();
+
+      // Search for userDn and return.
+      LdapContext systemLdapCtx = null;
+      NamingEnumeration<SearchResult> searchResultEnum = null;
+      try {
+        systemLdapCtx = getContextFactory().getSystemLdapContext();
+        LOG.searchBaseFilterScope(searchBase, searchFilter, userSearchScope);
+        searchResultEnum = systemLdapCtx.search( searchBase, searchFilter, searchControls );
+        // SearchResults contains all the entries in search scope
+        if (searchResultEnum.hasMore()) {
+          SearchResult searchResult = searchResultEnum.next();
+          userDn = searchResult.getNameInNamespace();
+          LOG.searchedAndFoundUserDn(userDn, principal);
+          return userDn;
+        } else {
+          throw new IllegalArgumentException("Illegal principal name: " + principal);
+        }
+      } catch (AuthenticationException e) {
+        LOG.failedToGetSystemLdapConnection(e);
+        throw new IllegalArgumentException("Illegal principal name: " + principal);
+      } catch (NamingException e) {
+        throw new IllegalArgumentException("Hit NamingException: " + e.getMessage());
+      } finally {
+        try {
+          if (searchResultEnum != null) {
+            searchResultEnum.close();
+          }
+        } catch (NamingException e) {
+          // Ignore exception on close.
+        }
+        finally {
+          LdapUtils.closeContext(systemLdapCtx);
+        }
+      }
+    }
+
+    @Override
+    protected AuthenticationInfo createAuthenticationInfo(AuthenticationToken token, Object ldapPrincipal, Object ldapCredentials, LdapContext ldapContext) throws NamingException {
+      HashRequest.Builder builder = new HashRequest.Builder();
+      Hash credentialsHash = hashService.computeHash(builder.setSource(token.getCredentials()).setAlgorithmName(HASHING_ALGORITHM).build());
+      return new SimpleAuthenticationInfo(token.getPrincipal(), credentialsHash.toHex(), credentialsHash.getSalt(), getName());
+    }
+
+  private static final String expandTemplate( final String template, final Matcher input ) {
+    String output = template;
+    Matcher matcher = TEMPLATE_PATTERN.matcher( output );
+    while( matcher.find() ) {
+      String lookupStr = matcher.group( 1 );
+      int lookupIndex = Integer.parseInt( lookupStr );
+      String lookupValue = input.group( lookupIndex );
+      output = matcher.replaceFirst( lookupValue == null ? "" : lookupValue );
+      matcher = TEMPLATE_PATTERN.matcher( output );
+    }
+    return output;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxPamRealm.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxPamRealm.java b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxPamRealm.java
new file mode 100644
index 0000000..4e1deb3
--- /dev/null
+++ b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxPamRealm.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.knox.gateway.shirorealm;
+
+import java.util.LinkedHashSet;
+import java.util.Set;
+import org.apache.knox.gateway.GatewayMessages;
+import org.apache.knox.gateway.audit.api.Action;
+import org.apache.knox.gateway.audit.api.ActionOutcome;
+import org.apache.knox.gateway.audit.api.ResourceType;
+import org.apache.knox.gateway.audit.api.AuditService;
+import org.apache.knox.gateway.audit.api.AuditServiceFactory;
+import org.apache.knox.gateway.audit.api.Auditor;
+import org.apache.knox.gateway.audit.log4j.audit.AuditConstants;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.shirorealm.impl.i18n.KnoxShiroMessages;
+import org.apache.shiro.SecurityUtils;
+import org.apache.shiro.authc.AuthenticationException;
+
+import org.apache.shiro.authc.AuthenticationInfo;
+import org.apache.shiro.authc.AuthenticationToken;
+import org.apache.shiro.authc.SimpleAuthenticationInfo;
+import org.apache.shiro.authc.UsernamePasswordToken;
+import org.apache.shiro.authz.AuthorizationInfo;
+import org.apache.shiro.authz.SimpleAuthorizationInfo;
+import org.apache.shiro.realm.AuthorizingRealm;
+import org.apache.shiro.subject.PrincipalCollection;
+import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
+import org.apache.shiro.crypto.hash.*;
+import org.jvnet.libpam.PAM;
+import org.jvnet.libpam.PAMException;
+import org.jvnet.libpam.UnixUser;
+
+/**
+ * A Unix-style
+ * <a href="http://www.kernel.org/pub/linux/libs/pam/index.html">PAM</a>
+ * {@link org.apache.shiro.realm.Realm Realm} that uses
+ * <a href="https://github.com/kohsuke/libpam4j">libpam4j</a> to interface with
+ * the PAM system libraries.
+ * <p>
+ * This is a single Shiro {@code Realm} that interfaces with the OS's
+ * {@code PAM} subsystem which itself can be connected to several authentication
+ * methods (unix-crypt,Samba, LDAP, etc.)
+ * <p>
+ * This {@code Realm} can also take part in Shiro's Pluggable Realms concept.
+ * <p>
+ * Using a {@code KnoxPamRealm} requires a PAM {@code service} name. This is the
+ * name of the file under {@code /etc/pam.d} that is used to initialise and
+ * configure the PAM subsytem. Normally, this file reflects the application
+ * using it. For example {@code gdm}, {@code su}, etc. There is no default value
+ * for this propery.
+ * <p>
+ * For example, defining this realm in Shiro .ini:
+ *
+ * <pre>
+ * [main]
+ * pamRealm = org.apache.shiro.realm.libpam4j.KnoxPamRealm
+ * pamRealm.service = [ knox-pam-ldap-service | knox-pam-os-service | knox-pam-winbind-service ]
+ * [urls]
+ * **=authcBasic
+ * </pre>
+ *
+ */
+
+public class KnoxPamRealm extends AuthorizingRealm {
+  private static final String HASHING_ALGORITHM = "SHA-256";
+  private static final String SUBJECT_USER_ROLES = "subject.userRoles";
+  private static final String SUBJECT_USER_GROUPS = "subject.userGroups";
+  private HashService hashService = new DefaultHashService();
+  KnoxShiroMessages ShiroLog = MessagesFactory.get(KnoxShiroMessages.class);
+  GatewayMessages GatewayLog = MessagesFactory.get(GatewayMessages.class);
+  private static AuditService auditService = AuditServiceFactory.getAuditService();
+  private static Auditor auditor = auditService.getAuditor(AuditConstants.DEFAULT_AUDITOR_NAME,
+      AuditConstants.KNOX_SERVICE_NAME, AuditConstants.KNOX_COMPONENT_NAME);
+
+  private String service;
+
+  public KnoxPamRealm() {
+    HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher(HASHING_ALGORITHM);
+    setCredentialsMatcher(credentialsMatcher);
+  }
+
+  public void setService(String service) {
+    this.service = service;
+  }
+
+  public String getService() {
+    return this.service;
+  }
+
+  @Override
+  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
+    Set<String> roles = new LinkedHashSet<String>();
+
+    UnixUserPrincipal user = principals.oneByType(UnixUserPrincipal.class);
+    if (user != null) {
+      roles.addAll(user.getUnixUser().getGroups());
+    }
+    SecurityUtils.getSubject().getSession().setAttribute(SUBJECT_USER_ROLES, roles);
+    SecurityUtils.getSubject().getSession().setAttribute(SUBJECT_USER_GROUPS, roles);
+
+    /* Coverity Scan CID 1361682 */
+    String userName = null;
+
+    if (user != null) {
+      userName = user.getName();
+    }
+
+    GatewayLog.lookedUpUserRoles(roles, userName);
+    return new SimpleAuthorizationInfo(roles);
+  }
+
+  @Override
+  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
+    UsernamePasswordToken upToken = (UsernamePasswordToken) token;
+    UnixUser user = null;
+    try {
+      user = (new PAM(this.getService())).authenticate(upToken.getUsername(), new String(upToken.getPassword()));
+    } catch (PAMException e) {
+      handleAuthFailure(token, e.getMessage(), e);
+    }
+    HashRequest.Builder builder = new HashRequest.Builder();
+    Hash credentialsHash = hashService
+        .computeHash(builder.setSource(token.getCredentials()).setAlgorithmName(HASHING_ALGORITHM).build());
+    /* Coverity Scan CID 1361684 */
+    if (credentialsHash == null) {
+      handleAuthFailure(token, "Failed to compute hash", null);
+    }
+    return new SimpleAuthenticationInfo(new UnixUserPrincipal(user), credentialsHash.toHex(), credentialsHash.getSalt(),
+        getName());
+  }
+
+  private void handleAuthFailure(AuthenticationToken token, String errorMessage, Exception e) {
+    auditor.audit(Action.AUTHENTICATION, token.getPrincipal().toString(), ResourceType.PRINCIPAL, ActionOutcome.FAILURE,
+        errorMessage);
+    ShiroLog.failedLoginInfo(token);
+
+    if (e != null) {
+      ShiroLog.failedLoginAttempt(e.getCause());
+      throw new AuthenticationException(e);
+    }
+
+    throw new AuthenticationException(errorMessage);
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/UnixUserPrincipal.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/UnixUserPrincipal.java b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/UnixUserPrincipal.java
new file mode 100644
index 0000000..247cae6
--- /dev/null
+++ b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/UnixUserPrincipal.java
@@ -0,0 +1,46 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT 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.knox.gateway.shirorealm;
+
+import java.security.Principal;
+import org.jvnet.libpam.UnixUser;
+
+public class UnixUserPrincipal implements Principal {
+	private final UnixUser userName;
+
+	public UnixUserPrincipal(UnixUser userName) {
+		this.userName = userName;
+	}
+
+	@Override
+	public String getName() {
+		return userName.getUserName();
+	}
+
+	public UnixUser getUnixUser() {
+		return userName;
+	}
+
+	@Override
+	public String toString() {
+		return String.valueOf(userName.getUserName());
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/impl/i18n/KnoxShiroMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/impl/i18n/KnoxShiroMessages.java b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/impl/i18n/KnoxShiroMessages.java
new file mode 100644
index 0000000..736a544
--- /dev/null
+++ b/gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/impl/i18n/KnoxShiroMessages.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.knox.gateway.shirorealm.impl.i18n;
+
+import org.apache.knox.gateway.i18n.messages.Message;
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.Messages;
+
+import org.apache.knox.gateway.i18n.messages.StackTrace;
+import org.apache.shiro.authc.AuthenticationToken;
+import org.apache.shiro.subject.Subject;
+
+@Messages(logger = "org.apache.hadoop.gateway")
+public interface KnoxShiroMessages {
+
+  @Message(level = MessageLevel.ERROR, text = "Shiro unable to login: {0}")
+  void failedLoginAttempt(Throwable e);
+
+  @Message(level = MessageLevel.INFO, text = "Could not login: {0}")
+  void failedLoginInfo(AuthenticationToken token);
+
+  @Message( level = MessageLevel.DEBUG, text = "Failed to Authenticate with LDAP server: {1}" )
+  void failedLoginStackTrace( @StackTrace( level = MessageLevel.DEBUG ) Exception e );
+
+  @Message(level = MessageLevel.INFO, text = "Successfully logged in: {0}, {1}")
+  void successfulLoginAttempt(Subject subject, AuthenticationToken authToken);
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-shiro/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index 3ee0582..0000000
--- a/gateway-provider-security-shiro/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.deploy.impl.ShiroDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-shiro/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..8ded76f
--- /dev/null
+++ b/gateway-provider-security-shiro/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.deploy.impl.ShiroDeploymentContributor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/test/java/org/apache/hadoop/gateway/deploy/impl/ShiroDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/test/java/org/apache/hadoop/gateway/deploy/impl/ShiroDeploymentContributorTest.java b/gateway-provider-security-shiro/src/test/java/org/apache/hadoop/gateway/deploy/impl/ShiroDeploymentContributorTest.java
deleted file mode 100644
index 63f8e9f..0000000
--- a/gateway-provider-security-shiro/src/test/java/org/apache/hadoop/gateway/deploy/impl/ShiroDeploymentContributorTest.java
+++ /dev/null
@@ -1,108 +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.hadoop.gateway.deploy.impl;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.security.AliasService;
-import org.apache.hadoop.gateway.services.security.CryptoService;
-import org.apache.hadoop.gateway.services.security.impl.DefaultCryptoService;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Topology;
-import org.easymock.EasyMock;
-import org.jboss.shrinkwrap.api.ShrinkWrap;
-import org.jboss.shrinkwrap.api.asset.StringAsset;
-import org.jboss.shrinkwrap.api.spec.WebArchive;
-import org.jboss.shrinkwrap.descriptor.api.Descriptors;
-import org.jboss.shrinkwrap.descriptor.api.webapp30.WebAppDescriptor;
-import org.junit.Test;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class ShiroDeploymentContributorTest {
-
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( ProviderDeploymentContributor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof ShiroDeploymentContributor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + ShiroDeploymentContributor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testDeployment() throws IOException {
-    WebArchive webArchive = ShrinkWrap.create( WebArchive.class, "test-archive" );
-
-    Map<String,String> providerParams = new HashMap<>();
-    Provider provider = new Provider();
-    provider.setEnabled( true );
-    provider.setName( "shiro" );
-    provider.setParams(  providerParams );
-
-    Topology topology = new Topology();
-    topology.setName( "Sample" );
-
-    DeploymentContext context = EasyMock.createNiceMock( DeploymentContext.class );
-    EasyMock.expect( context.getWebArchive() ).andReturn( webArchive ).anyTimes();
-    EasyMock.expect( context.getWebAppDescriptor() ).andReturn( Descriptors.create( WebAppDescriptor.class ) ).anyTimes();
-    EasyMock.expect( context.getTopology() ).andReturn( topology ).anyTimes();
-    EasyMock.replay( context );
-
-    AliasService as = EasyMock.createNiceMock( AliasService.class );
-    CryptoService cryptoService = new DefaultCryptoService();
-    ((DefaultCryptoService)cryptoService).setAliasService( as );
-
-    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService ).anyTimes();
-
-    ShiroDeploymentContributor contributor = new ShiroDeploymentContributor();
-
-    assertThat( contributor.getRole(), is( "authentication" ) );
-    assertThat( contributor.getName(), is( "ShiroProvider" ) );
-
-    // Just make sure it doesn't blow up.
-    contributor.initializeContribution( context );
-
-    contributor.contributeProvider( context, provider );
-
-    // Just make sure it doesn't blow up.
-    contributor.finalizeContribution( context );
-
-    assertThat( context.getWebAppDescriptor().getOrCreateSessionConfig().getOrCreateCookieConfig().isHttpOnly(), is( true ) );
-    assertThat( context.getWebAppDescriptor().getOrCreateSessionConfig().getOrCreateCookieConfig().isSecure(), is( true ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/test/java/org/apache/hadoop/gateway/shirorealm/KnoxLdapRealmTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/test/java/org/apache/hadoop/gateway/shirorealm/KnoxLdapRealmTest.java b/gateway-provider-security-shiro/src/test/java/org/apache/hadoop/gateway/shirorealm/KnoxLdapRealmTest.java
deleted file mode 100644
index cea8cca..0000000
--- a/gateway-provider-security-shiro/src/test/java/org/apache/hadoop/gateway/shirorealm/KnoxLdapRealmTest.java
+++ /dev/null
@@ -1,104 +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.hadoop.gateway.shirorealm;
-
-import org.junit.Test;
-import static org.junit.Assert.*;
-
-public class KnoxLdapRealmTest {
-  
-  @Test
-  public void setGetSearchBase() {
-    KnoxLdapRealm realm = new KnoxLdapRealm();
-    realm.setSearchBase("dc=hadoop,dc=apache,dc=org");
-    assertEquals(realm.getSearchBase(), "dc=hadoop,dc=apache,dc=org");
-  }
-  
-  @Test
-  public void setGetGroupObjectClass() {
-    KnoxLdapRealm realm = new KnoxLdapRealm();
-    realm.setGroupObjectClass("groupOfMembers");
-    assertEquals(realm.getGroupObjectClass(), "groupOfMembers");
-  }  
-  
-  @Test
-  public void setGetUniqueMemberAttribute() {
-    KnoxLdapRealm realm = new KnoxLdapRealm();
-    realm.setMemberAttribute("member");
-    assertEquals(realm.getMemberAttribute(), "member");
-  }
-  
-  @Test
-  public void setGetUserSearchAttributeName() {
-    KnoxLdapRealm realm = new KnoxLdapRealm();
-    realm.setUserSearchAttributeName("uid");
-    assertEquals(realm.getUserSearchAttributeName(), "uid");
-  }
-  
-  @Test
-  public void setGetUserObjectClass() {
-    KnoxLdapRealm realm = new KnoxLdapRealm();
-    realm.setUserObjectClass("inetuser");
-    assertEquals(realm.getUserObjectClass(), "inetuser");
-  }
-  
-  @Test
-  public void setGetUserSearchBase() {
-    KnoxLdapRealm realm = new KnoxLdapRealm();
-    realm.setSearchBase("dc=example,dc=com");
-    realm.setUserSearchBase("dc=knox,dc=example,dc=com");
-    assertEquals(realm.getUserSearchBase(), "dc=knox,dc=example,dc=com");
-  }
-  
-  @Test
-  public void setGetGroupSearchBase() {
-    KnoxLdapRealm realm = new KnoxLdapRealm();
-    realm.setSearchBase("dc=example,dc=com");
-    realm.setGroupSearchBase("dc=knox,dc=example,dc=com");
-    assertEquals(realm.getGroupSearchBase(), "dc=knox,dc=example,dc=com");
-  }
-  
-  @Test
-  public void verifyDefaultUserSearchAttributeName() {
-    KnoxLdapRealm realm = new KnoxLdapRealm();
-    assertNull(realm.getUserSearchAttributeName());
-  }
-  
-  @Test
-  public void verifyDefaultGetUserObjectClass() {
-    KnoxLdapRealm realm = new KnoxLdapRealm();
-    assertEquals(realm.getUserObjectClass(), "person");
-  }
-  
-  @Test
-  public void verifyDefaultUserSearchBase() {
-    KnoxLdapRealm realm = new KnoxLdapRealm();
-    realm.setSearchBase("dc=knox,dc=example,dc=com");
-    assertEquals(realm.getUserSearchBase(), "dc=knox,dc=example,dc=com");
-  }
-  
-  @Test
-  public void verifyDefaultGroupSearchBase() {
-    KnoxLdapRealm realm = new KnoxLdapRealm();
-    realm.setSearchBase("dc=knox,dc=example,dc=com");
-    assertEquals(realm.getGroupSearchBase(), "dc=knox,dc=example,dc=com");
-  }
-  
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/test/java/org/apache/hadoop/gateway/shirorealm/KnoxPamRealmTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/test/java/org/apache/hadoop/gateway/shirorealm/KnoxPamRealmTest.java b/gateway-provider-security-shiro/src/test/java/org/apache/hadoop/gateway/shirorealm/KnoxPamRealmTest.java
deleted file mode 100644
index 1ada3c6..0000000
--- a/gateway-provider-security-shiro/src/test/java/org/apache/hadoop/gateway/shirorealm/KnoxPamRealmTest.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.hadoop.gateway.shirorealm;
-
-import java.util.Scanner;
-
-import org.junit.Test;
-
-import org.apache.shiro.authc.AuthenticationInfo;
-import org.apache.shiro.authc.UsernamePasswordToken;
-
-import static org.junit.Assert.*;
-import static org.junit.Assume.assumeTrue;
-import static org.easymock.EasyMock.*;
-
-public class KnoxPamRealmTest {
-  @Test
-  public void setService() {
-    KnoxPamRealm realm = new KnoxPamRealm();
-    realm.setService("knox-pam-os-service");
-    //assertEquals(realm.getService(), "knox-pam-os-service");
-  }
-
-  @Test
-  public void testDoGetAuthenticationInfo() {
-    KnoxPamRealm realm = new KnoxPamRealm();
-    realm.setService("sshd");  // pam settings being used: /etc/pam.d/sshd
-
-    // use environment variables and skip the test if not set.
-    String pamuser = System.getenv("PAMUSER");
-    String pampass = System.getenv("PAMPASS");
-    assumeTrue(pamuser != null);
-    assumeTrue(pampass != null);
-
-    // mock shiro auth token
-    UsernamePasswordToken authToken = createMock(UsernamePasswordToken.class);
-    expect(authToken.getUsername()).andReturn(pamuser);
-    expect(authToken.getPassword()).andReturn(pampass.toCharArray());
-    expect(authToken.getCredentials()).andReturn(pampass);
-    replay(authToken);
-
-    // login
-    AuthenticationInfo authInfo = realm.doGetAuthenticationInfo(authToken);
-
-    // verify success
-    assertTrue(authInfo.getCredentials() != null);
-  }
-
-  public static void main(String[] args) throws Exception {
-    KnoxPamRealmTest pamTest = new KnoxPamRealmTest();
-    pamTest.testDoGetAuthenticationInfo();
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/test/java/org/apache/knox/gateway/deploy/impl/ShiroDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/test/java/org/apache/knox/gateway/deploy/impl/ShiroDeploymentContributorTest.java b/gateway-provider-security-shiro/src/test/java/org/apache/knox/gateway/deploy/impl/ShiroDeploymentContributorTest.java
new file mode 100644
index 0000000..307d97e
--- /dev/null
+++ b/gateway-provider-security-shiro/src/test/java/org/apache/knox/gateway/deploy/impl/ShiroDeploymentContributorTest.java
@@ -0,0 +1,104 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.deploy.impl;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributor;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.AliasService;
+import org.apache.knox.gateway.services.security.CryptoService;
+import org.apache.knox.gateway.services.security.impl.DefaultCryptoService;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Topology;
+import org.easymock.EasyMock;
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.spec.WebArchive;
+import org.jboss.shrinkwrap.descriptor.api.Descriptors;
+import org.jboss.shrinkwrap.descriptor.api.webapp30.WebAppDescriptor;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class ShiroDeploymentContributorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( ProviderDeploymentContributor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof ShiroDeploymentContributor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + ShiroDeploymentContributor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testDeployment() throws IOException {
+    WebArchive webArchive = ShrinkWrap.create( WebArchive.class, "test-archive" );
+
+    Map<String,String> providerParams = new HashMap<>();
+    Provider provider = new Provider();
+    provider.setEnabled( true );
+    provider.setName( "shiro" );
+    provider.setParams(  providerParams );
+
+    Topology topology = new Topology();
+    topology.setName( "Sample" );
+
+    DeploymentContext context = EasyMock.createNiceMock( DeploymentContext.class );
+    EasyMock.expect( context.getWebArchive() ).andReturn( webArchive ).anyTimes();
+    EasyMock.expect( context.getWebAppDescriptor() ).andReturn( Descriptors.create( WebAppDescriptor.class ) ).anyTimes();
+    EasyMock.expect( context.getTopology() ).andReturn( topology ).anyTimes();
+    EasyMock.replay( context );
+
+    AliasService as = EasyMock.createNiceMock( AliasService.class );
+    CryptoService cryptoService = new DefaultCryptoService();
+    ((DefaultCryptoService)cryptoService).setAliasService( as );
+
+    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService ).anyTimes();
+
+    ShiroDeploymentContributor contributor = new ShiroDeploymentContributor();
+
+    assertThat( contributor.getRole(), is( "authentication" ) );
+    assertThat( contributor.getName(), is( "ShiroProvider" ) );
+
+    // Just make sure it doesn't blow up.
+    contributor.initializeContribution( context );
+
+    contributor.contributeProvider( context, provider );
+
+    // Just make sure it doesn't blow up.
+    contributor.finalizeContribution( context );
+
+    assertThat( context.getWebAppDescriptor().getOrCreateSessionConfig().getOrCreateCookieConfig().isHttpOnly(), is( true ) );
+    assertThat( context.getWebAppDescriptor().getOrCreateSessionConfig().getOrCreateCookieConfig().isSecure(), is( true ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/test/java/org/apache/knox/gateway/shirorealm/KnoxLdapRealmTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/test/java/org/apache/knox/gateway/shirorealm/KnoxLdapRealmTest.java b/gateway-provider-security-shiro/src/test/java/org/apache/knox/gateway/shirorealm/KnoxLdapRealmTest.java
new file mode 100644
index 0000000..591dd7e
--- /dev/null
+++ b/gateway-provider-security-shiro/src/test/java/org/apache/knox/gateway/shirorealm/KnoxLdapRealmTest.java
@@ -0,0 +1,104 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT 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.knox.gateway.shirorealm;
+
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class KnoxLdapRealmTest {
+  
+  @Test
+  public void setGetSearchBase() {
+    KnoxLdapRealm realm = new KnoxLdapRealm();
+    realm.setSearchBase("dc=hadoop,dc=apache,dc=org");
+    assertEquals(realm.getSearchBase(), "dc=hadoop,dc=apache,dc=org");
+  }
+  
+  @Test
+  public void setGetGroupObjectClass() {
+    KnoxLdapRealm realm = new KnoxLdapRealm();
+    realm.setGroupObjectClass("groupOfMembers");
+    assertEquals(realm.getGroupObjectClass(), "groupOfMembers");
+  }  
+  
+  @Test
+  public void setGetUniqueMemberAttribute() {
+    KnoxLdapRealm realm = new KnoxLdapRealm();
+    realm.setMemberAttribute("member");
+    assertEquals(realm.getMemberAttribute(), "member");
+  }
+  
+  @Test
+  public void setGetUserSearchAttributeName() {
+    KnoxLdapRealm realm = new KnoxLdapRealm();
+    realm.setUserSearchAttributeName("uid");
+    assertEquals(realm.getUserSearchAttributeName(), "uid");
+  }
+  
+  @Test
+  public void setGetUserObjectClass() {
+    KnoxLdapRealm realm = new KnoxLdapRealm();
+    realm.setUserObjectClass("inetuser");
+    assertEquals(realm.getUserObjectClass(), "inetuser");
+  }
+  
+  @Test
+  public void setGetUserSearchBase() {
+    KnoxLdapRealm realm = new KnoxLdapRealm();
+    realm.setSearchBase("dc=example,dc=com");
+    realm.setUserSearchBase("dc=knox,dc=example,dc=com");
+    assertEquals(realm.getUserSearchBase(), "dc=knox,dc=example,dc=com");
+  }
+  
+  @Test
+  public void setGetGroupSearchBase() {
+    KnoxLdapRealm realm = new KnoxLdapRealm();
+    realm.setSearchBase("dc=example,dc=com");
+    realm.setGroupSearchBase("dc=knox,dc=example,dc=com");
+    assertEquals(realm.getGroupSearchBase(), "dc=knox,dc=example,dc=com");
+  }
+  
+  @Test
+  public void verifyDefaultUserSearchAttributeName() {
+    KnoxLdapRealm realm = new KnoxLdapRealm();
+    assertNull(realm.getUserSearchAttributeName());
+  }
+  
+  @Test
+  public void verifyDefaultGetUserObjectClass() {
+    KnoxLdapRealm realm = new KnoxLdapRealm();
+    assertEquals(realm.getUserObjectClass(), "person");
+  }
+  
+  @Test
+  public void verifyDefaultUserSearchBase() {
+    KnoxLdapRealm realm = new KnoxLdapRealm();
+    realm.setSearchBase("dc=knox,dc=example,dc=com");
+    assertEquals(realm.getUserSearchBase(), "dc=knox,dc=example,dc=com");
+  }
+  
+  @Test
+  public void verifyDefaultGroupSearchBase() {
+    KnoxLdapRealm realm = new KnoxLdapRealm();
+    realm.setSearchBase("dc=knox,dc=example,dc=com");
+    assertEquals(realm.getGroupSearchBase(), "dc=knox,dc=example,dc=com");
+  }
+  
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-shiro/src/test/java/org/apache/knox/gateway/shirorealm/KnoxPamRealmTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-shiro/src/test/java/org/apache/knox/gateway/shirorealm/KnoxPamRealmTest.java b/gateway-provider-security-shiro/src/test/java/org/apache/knox/gateway/shirorealm/KnoxPamRealmTest.java
new file mode 100644
index 0000000..340bbc4
--- /dev/null
+++ b/gateway-provider-security-shiro/src/test/java/org/apache/knox/gateway/shirorealm/KnoxPamRealmTest.java
@@ -0,0 +1,68 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT 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.knox.gateway.shirorealm;
+
+import org.junit.Test;
+
+import org.apache.shiro.authc.AuthenticationInfo;
+import org.apache.shiro.authc.UsernamePasswordToken;
+
+import static org.junit.Assert.*;
+import static org.junit.Assume.assumeTrue;
+import static org.easymock.EasyMock.*;
+
+public class KnoxPamRealmTest {
+  @Test
+  public void setService() {
+    KnoxPamRealm realm = new KnoxPamRealm();
+    realm.setService("knox-pam-os-service");
+    //assertEquals(realm.getService(), "knox-pam-os-service");
+  }
+
+  @Test
+  public void testDoGetAuthenticationInfo() {
+    KnoxPamRealm realm = new KnoxPamRealm();
+    realm.setService("sshd");  // pam settings being used: /etc/pam.d/sshd
+
+    // use environment variables and skip the test if not set.
+    String pamuser = System.getenv("PAMUSER");
+    String pampass = System.getenv("PAMPASS");
+    assumeTrue(pamuser != null);
+    assumeTrue(pampass != null);
+
+    // mock shiro auth token
+    UsernamePasswordToken authToken = createMock(UsernamePasswordToken.class);
+    expect(authToken.getUsername()).andReturn(pamuser);
+    expect(authToken.getPassword()).andReturn(pampass.toCharArray());
+    expect(authToken.getCredentials()).andReturn(pampass);
+    replay(authToken);
+
+    // login
+    AuthenticationInfo authInfo = realm.doGetAuthenticationInfo(authToken);
+
+    // verify success
+    assertTrue(authInfo.getCredentials() != null);
+  }
+
+  public static void main(String[] args) throws Exception {
+    KnoxPamRealmTest pamTest = new KnoxPamRealmTest();
+    pamTest.testDoGetAuthenticationInfo();
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/WebAppSecMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/WebAppSecMessages.java b/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/WebAppSecMessages.java
deleted file mode 100644
index 7cf68f4..0000000
--- a/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/WebAppSecMessages.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.hadoop.gateway.webappsec;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-
-@Messages(logger="org.apache.hadoop.gateway.provider.global.csrf")
-public interface WebAppSecMessages {
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/deploy/WebAppSecContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/deploy/WebAppSecContributor.java b/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/deploy/WebAppSecContributor.java
deleted file mode 100644
index 50a6767..0000000
--- a/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/deploy/WebAppSecContributor.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.hadoop.gateway.webappsec.deploy;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-public class WebAppSecContributor extends
-    ProviderDeploymentContributorBase {
-  private static final String ROLE = "webappsec";
-  private static final String NAME = "WebAppSec";
-  private static final String CSRF_SUFFIX = "_CSRF";
-  private static final String CSRF_FILTER_CLASSNAME = "org.apache.hadoop.gateway.webappsec.filter.CSRFPreventionFilter";
-  private static final String CSRF_ENABLED = "csrf.enabled";
-  private static final String CORS_SUFFIX = "_CORS";
-  private static final String CORS_FILTER_CLASSNAME = "com.thetransactioncompany.cors.CORSFilter";
-  private static final String CORS_ENABLED = "cors.enabled";
-  private static final String XFRAME_OPTIONS_SUFFIX = "_XFRAMEOPTIONS";
-  private static final String XFRAME_OPTIONS_FILTER_CLASSNAME = "org.apache.hadoop.gateway.webappsec.filter.XFrameOptionsFilter";
-  private static final String XFRAME_OPTIONS_ENABLED = "xframe.options.enabled";
-
-  @Override
-  public String getRole() {
-    return ROLE;
-  }
-
-  @Override
-  public String getName() {
-    return NAME;
-  }
-
-  @Override
-  public void initializeContribution(DeploymentContext context) {
-    super.initializeContribution(context);
-  }
-
-  @Override
-  public void contributeFilter(DeploymentContext context, Provider provider, Service service, 
-      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
-    
-    Provider webappsec = context.getTopology().getProvider(ROLE, NAME);
-    if (webappsec != null && webappsec.isEnabled()) {
-      Map<String,String> map = provider.getParams();
-      if (params == null) {
-        params = new ArrayList<FilterParamDescriptor>();
-      }
-
-      Map<String, String> providerParams = provider.getParams();
-      // CORS support
-      String corsEnabled = map.get(CORS_ENABLED);
-      if ( corsEnabled != null && corsEnabled.equals("true")) {
-        provisionConfig(resource, providerParams, params, "cors.");
-        resource.addFilter().name( getName() + CORS_SUFFIX ).role( getRole() ).impl( CORS_FILTER_CLASSNAME ).params( params );
-      }
-
-      // CRSF
-      params = new ArrayList<FilterParamDescriptor>();
-      String csrfEnabled = map.get(CSRF_ENABLED);
-      if ( csrfEnabled != null && csrfEnabled.equals("true")) {
-        provisionConfig(resource, providerParams, params, "csrf.");
-        resource.addFilter().name( getName() + CSRF_SUFFIX ).role( getRole() ).impl( CSRF_FILTER_CLASSNAME ).params( params );
-      }
-
-      // X-Frame-Options - clickjacking protection
-      params = new ArrayList<FilterParamDescriptor>();
-      String xframeOptionsEnabled = map.get(XFRAME_OPTIONS_ENABLED);
-      if ( xframeOptionsEnabled != null && xframeOptionsEnabled.equals("true")) {
-        provisionConfig(resource, providerParams, params, "xframe.");
-        resource.addFilter().name( getName() + XFRAME_OPTIONS_SUFFIX ).role( getRole() ).impl( XFRAME_OPTIONS_FILTER_CLASSNAME ).params( params );
-      }
-    }
-  }
-
-  private void provisionConfig(ResourceDescriptor resource, Map<String,String> providerParams,
-      List<FilterParamDescriptor> params, String prefix) {
-    for(Entry<String, String> entry : providerParams.entrySet()) {
-      if (entry.getKey().startsWith(prefix)) {
-        params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
-      }
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/filter/CSRFPreventionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/filter/CSRFPreventionFilter.java b/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/filter/CSRFPreventionFilter.java
deleted file mode 100644
index 9b07662..0000000
--- a/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/filter/CSRFPreventionFilter.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.hadoop.gateway.webappsec.filter;
-
-import java.io.IOException;
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-public class CSRFPreventionFilter implements Filter {
-  private static final String CUSTOM_HEADER_PARAM = "csrf.customheader";
-  private static final String CUSTOM_METHODS_TO_IGNORE_PARAM = "csrf.methodstoignore";
-  private String  headerName = "X-XSRF-Header";
-  private String  mti = "GET,OPTIONS,HEAD";
-  private Set<String> methodsToIgnore = null;
-  
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-    String customHeader = filterConfig.getInitParameter(CUSTOM_HEADER_PARAM);
-    if (customHeader != null) {
-      headerName = customHeader;
-    }
-    String customMTI = filterConfig.getInitParameter(CUSTOM_METHODS_TO_IGNORE_PARAM);
-    if (customMTI != null) {
-      mti = customMTI;
-    }
-    String[] methods = mti.split(",");
-    methodsToIgnore = new HashSet<>();
-    for (int i = 0; i < methods.length; i++) {
-      methodsToIgnore.add(methods[i]);
-    }
-  }
-  
-  @Override
-  public void doFilter(ServletRequest request, ServletResponse response,
-      FilterChain chain) throws IOException, ServletException {
-    HttpServletRequest httpRequest = (HttpServletRequest)request;
-    if ( methodsToIgnore.contains( httpRequest.getMethod() ) || httpRequest.getHeader(headerName) != null ) {
-      chain.doFilter(request, response);
-    } else {
-      ((HttpServletResponse)response).sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing Required Header for Vulnerability Protection");
-    }
-  }
-
-  /* (non-Javadoc)
-   * @see javax.servlet.Filter#destroy()
-   */
-  @Override
-  public void destroy() {
-    // TODO Auto-generated method stub
-    
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/filter/XFrameOptionsFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/filter/XFrameOptionsFilter.java b/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/filter/XFrameOptionsFilter.java
deleted file mode 100644
index 9ec14a6..0000000
--- a/gateway-provider-security-webappsec/src/main/java/org/apache/hadoop/gateway/webappsec/filter/XFrameOptionsFilter.java
+++ /dev/null
@@ -1,137 +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.hadoop.gateway.webappsec.filter;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpServletResponseWrapper;
-
-/**
- * This filter protects proxied webapps from clickjacking attacks that
- * are possible through use of Frames to contain the proxied resources.
- */
-public class XFrameOptionsFilter implements Filter {
-  private static final String X_FRAME_OPTIONS = "X-Frame-Options";
-  private static final String CUSTOM_HEADER_PARAM = "xframe.options";
-
-  private String option = "DENY";
-
-  /* (non-Javadoc)
-   * @see javax.servlet.Filter#destroy()
-   */
-  @Override
-  public void destroy() {
-  }
-
-  /* (non-Javadoc)
-   * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
-   */
-  @Override
-  public void doFilter(ServletRequest req, ServletResponse res,
-      FilterChain chain) throws IOException, ServletException {
-    ((HttpServletResponse) res).setHeader(X_FRAME_OPTIONS, option);
-    chain.doFilter(req, new XFrameOptionsResponseWrapper((HttpServletResponse) res));
-  }
-
-  /* (non-Javadoc)
-   * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
-   */
-  @Override
-  public void init(FilterConfig config) throws ServletException {
-    String customOption = config.getInitParameter(CUSTOM_HEADER_PARAM);
-    if (customOption != null) {
-      option = customOption;
-    }
-  }
-
-  public class XFrameOptionsResponseWrapper extends HttpServletResponseWrapper {
-    @Override
-    public void addHeader(String name, String value) {
-      // don't allow additional values to be added to
-      // the configured options value in topology
-      if (!name.equals(X_FRAME_OPTIONS)) {
-        super.addHeader(name, value);
-      }
-    }
-
-    @Override
-    public void setHeader(String name, String value) {
-      // don't allow overwriting of configured value
-      if (!name.equals(X_FRAME_OPTIONS)) {
-        super.setHeader(name, value);
-      }
-    }
-
-    /**
-     * construct a wrapper for this request
-     * 
-     * @param request
-     */
-    public XFrameOptionsResponseWrapper(HttpServletResponse response) {
-        super(response);
-    }
-
-    @Override
-    public String getHeader(String name) {
-        String headerValue = null;
-        if (name.equals(X_FRAME_OPTIONS)) {
-            headerValue = option;
-        }
-        else {
-          headerValue = super.getHeader(name);
-        }
-        return headerValue;
-    }
-
-    /**
-     * get the Header names
-     */
-    @Override
-    public Collection<String> getHeaderNames() {
-        List<String> names = (List<String>) super.getHeaderNames();
-        if (names == null) {
-          names = new ArrayList<String>();
-        }
-        names.add(X_FRAME_OPTIONS);
-        return names;
-    }
-
-    @Override
-    public Collection<String> getHeaders(String name) {
-        List<String> values = (List<String>) super.getHeaders(name);
-        if (name.equals(X_FRAME_OPTIONS)) {
-          if (values == null) {
-            values = new ArrayList<String>();
-          }
-          values.add(option);
-        }
-        return values;
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/WebAppSecMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/WebAppSecMessages.java b/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/WebAppSecMessages.java
new file mode 100644
index 0000000..8ea2467
--- /dev/null
+++ b/gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/WebAppSecMessages.java
@@ -0,0 +1,24 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.webappsec;
+
+import org.apache.knox.gateway.i18n.messages.Messages;
+
+@Messages(logger="org.apache.hadoop.gateway.provider.global.csrf")
+public interface WebAppSecMessages {
+}


[33/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/impl/DecryptUriProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/impl/DecryptUriProcessor.java b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/impl/DecryptUriProcessor.java
deleted file mode 100644
index 9a9d0c7..0000000
--- a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/impl/DecryptUriProcessor.java
+++ /dev/null
@@ -1,89 +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.hadoop.gateway.encrypturi.impl;
-
-import java.io.UnsupportedEncodingException;
-import java.util.Arrays;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.hadoop.gateway.encrypturi.EncryptStepContextParams;
-import org.apache.hadoop.gateway.encrypturi.api.DecryptUriDescriptor;
-import org.apache.hadoop.gateway.encrypturi.api.EncryptUriDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.security.CryptoService;
-import org.apache.hadoop.gateway.services.security.EncryptionResult;
-import org.apache.hadoop.gateway.util.urltemplate.Expander;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-public class DecryptUriProcessor
-    implements UrlRewriteStepProcessor<DecryptUriDescriptor> {
-
-  private String clusterName;
-  private CryptoService cryptoService;
-  private String param;
-
-  @Override
-  public String getType() {
-    return DecryptUriDescriptor.STEP_NAME;
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, DecryptUriDescriptor descriptor ) throws Exception {
-    clusterName = environment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE );
-    GatewayServices services = environment.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
-    cryptoService = (CryptoService) services.getService(GatewayServices.CRYPTO_SERVICE);
-    param = descriptor.getParam();
-  }
-
-  @Override
-  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
-    if( param != null && !param.isEmpty() ) {
-      Template template = Parser.parseTemplate( "{" + param + "}" );
-      String resolvedTemplate = Expander.expandToString( template, context.getParameters(), context.getEvaluator() );
-      String url = decode( resolvedTemplate );
-      EncryptStepContextParams params = new EncryptStepContextParams();
-      params.addParam( param, Arrays.asList( url ) );
-      context.addParameters( params );
-      return UrlRewriteStepStatus.SUCCESS;
-    }
-    return UrlRewriteStepStatus.FAILURE;
-  }
-
-  @Override
-  public void destroy() {
-  }
-
-  private String decode( String string ) throws UnsupportedEncodingException {
-    byte[] bytes = Base64.decodeBase64( string );
-    EncryptionResult result = EncryptionResult.fromByteArray(bytes);
-    byte[] clear = cryptoService.decryptForCluster(clusterName,
-        EncryptUriDescriptor.PASSWORD_ALIAS,
-        result.cipher,
-        result.iv,
-        result.salt);
-    if (clear != null) {
-      return new String(clear);
-    }
-    return null;
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptUriDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptUriDeploymentContributor.java b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptUriDeploymentContributor.java
deleted file mode 100644
index 622fdff..0000000
--- a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptUriDeploymentContributor.java
+++ /dev/null
@@ -1,87 +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.hadoop.gateway.encrypturi.impl;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.encrypturi.EncryptUriMessages;
-import org.apache.hadoop.gateway.encrypturi.api.EncryptUriDescriptor;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.services.security.AliasService;
-import org.apache.hadoop.gateway.services.security.AliasServiceException;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-import java.util.List;
-
-public class EncryptUriDeploymentContributor
-    extends ProviderDeploymentContributorBase
-    implements ProviderDeploymentContributor {
-
-  private static EncryptUriMessages log = MessagesFactory.get( EncryptUriMessages.class );
-  public static final String PROVIDER_ROLE_NAME = "encrypt";
-  public static final String PROVIDER_IMPL_NAME = "default";
-  private AliasService as;
-
-  @Override
-  public String getRole() {
-    return PROVIDER_ROLE_NAME;
-  }
-
-  @Override
-  public String getName() {
-    return PROVIDER_IMPL_NAME;
-  }
-
-  public void setAliasService(AliasService as) {
-    this.as = as;
-  }
-
-  @Override
-  public void initializeContribution(DeploymentContext context) {
-    super.initializeContribution(context);
-
-    String clusterName = context.getTopology().getName();
-
-    // we don't want to overwrite an existing alias from a previous topology deployment
-    // so we can't just blindly generateAlias here.
-    // this version of getPassword will generate a value for it only if missing
-    try {
-      this.as.getPasswordFromAliasForCluster(clusterName, EncryptUriDescriptor.PASSWORD_ALIAS, true);
-    } catch (AliasServiceException e) {
-      log.unableCreatePasswordForEncryption(e);
-    }
-  }
-
-  @Override
-  public void contributeProvider( DeploymentContext context, Provider provider ) {
-  }
-
-  @Override
-  public void contributeFilter(
-      DeploymentContext context,
-      Provider provider,
-      Service service,
-      ResourceDescriptor resource,
-      List<FilterParamDescriptor> params ) {
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptUriProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptUriProcessor.java b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptUriProcessor.java
deleted file mode 100644
index 2b0554e..0000000
--- a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptUriProcessor.java
+++ /dev/null
@@ -1,85 +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.hadoop.gateway.encrypturi.impl;
-
-import java.io.UnsupportedEncodingException;
-import java.util.Arrays;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.hadoop.gateway.encrypturi.EncryptStepContextParams;
-import org.apache.hadoop.gateway.encrypturi.api.EncryptUriDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.security.CryptoService;
-import org.apache.hadoop.gateway.services.security.EncryptionResult;
-import org.apache.hadoop.gateway.util.urltemplate.Expander;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-public class EncryptUriProcessor
-    implements UrlRewriteStepProcessor<EncryptUriDescriptor> {
-
-  private String clusterName;
-  private CryptoService cryptoService;
-  private String template;
-  private String param;
-
-  @Override
-  public String getType() {
-    return EncryptUriDescriptor.STEP_NAME;
-  }
-
-  @Override
-  public void initialize( UrlRewriteEnvironment environment, EncryptUriDescriptor descriptor ) throws Exception {
-    clusterName = environment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE );
-    GatewayServices services = environment.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
-    cryptoService = (CryptoService) services.getService(GatewayServices.CRYPTO_SERVICE);
-    template = descriptor.getTemplate();
-    param = descriptor.getParam();
-  }
-
-  @Override
-  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
-    if( param != null && !param.isEmpty() && template != null && !template.isEmpty() ) {
-      Template uri = Parser.parseTemplate( template );
-      String resolvedTemplate = Expander.expandToString( uri, context.getParameters(), context.getEvaluator() );
-      if( resolvedTemplate != null && !resolvedTemplate.isEmpty() ) {
-        String endcoedUrl = encode( resolvedTemplate );
-        EncryptStepContextParams params = new EncryptStepContextParams();
-        params.addParam( param, Arrays.asList( endcoedUrl ) );
-        context.addParameters( params );
-        return UrlRewriteStepStatus.SUCCESS;
-      }
-    }
-    return UrlRewriteStepStatus.FAILURE;
-  }
-
-  @Override
-  public void destroy() {
-  }
-
-  private String encode( String string ) throws UnsupportedEncodingException {
-    EncryptionResult result = cryptoService.encryptForCluster(clusterName, EncryptUriDescriptor.PASSWORD_ALIAS, string.getBytes("UTF-8"));
-    string = Base64.encodeBase64URLSafeString(result.toByteAray());
-    return string;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/EncryptStepContextParams.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/EncryptStepContextParams.java b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/EncryptStepContextParams.java
new file mode 100644
index 0000000..919660a
--- /dev/null
+++ b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/EncryptStepContextParams.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.knox.gateway.encrypturi;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.knox.gateway.util.urltemplate.Params;
+
+public class EncryptStepContextParams implements Params {
+  Map<String, List<String>> params = new HashMap<>();
+
+  public EncryptStepContextParams() {
+  }
+
+  @Override
+  public List<String> resolve( String name ) {
+    return params.get( name );
+  }
+
+  @Override
+  public Set<String> getNames() {
+    return params.keySet();
+  }
+
+  public void addParam( String name, List<String> values ) {
+    params.put( name, values );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/EncryptUriMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/EncryptUriMessages.java b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/EncryptUriMessages.java
new file mode 100644
index 0000000..afcc384
--- /dev/null
+++ b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/EncryptUriMessages.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.encrypturi;
+
+import org.apache.knox.gateway.i18n.messages.Message;
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.Messages;
+import org.apache.knox.gateway.i18n.messages.StackTrace;
+
+@Messages(logger="org.apache.hadoop.gateway.encrypturi")
+public interface EncryptUriMessages {
+
+  @Message( level = MessageLevel.ERROR, text = "Failed to create or verify the presence of a password for URL encryption: {0}" )
+  void unableCreatePasswordForEncryption(@StackTrace( level = MessageLevel.DEBUG ) Exception e);
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/api/DecryptUriDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/api/DecryptUriDescriptor.java b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/api/DecryptUriDescriptor.java
new file mode 100644
index 0000000..886e181
--- /dev/null
+++ b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/api/DecryptUriDescriptor.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.knox.gateway.encrypturi.api;
+
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
+
+public class DecryptUriDescriptor extends UrlRewriteActionDescriptorBase
+    implements UrlRewriteActionDescriptor {
+  public static final String STEP_NAME = "decrypt";
+  private String param;
+
+  public DecryptUriDescriptor() {
+    super( STEP_NAME );
+  }
+
+  public String getParam() {
+    return param;
+  }
+
+  public void setParam( String param ) {
+    this.param = param;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/api/EncryptUriDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/api/EncryptUriDescriptor.java b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/api/EncryptUriDescriptor.java
new file mode 100644
index 0000000..7dbae0a
--- /dev/null
+++ b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/api/EncryptUriDescriptor.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.knox.gateway.encrypturi.api;
+
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
+
+public class EncryptUriDescriptor extends UrlRewriteActionDescriptorBase
+    implements UrlRewriteActionDescriptor {
+  public static final String STEP_NAME = "encrypt";
+  public static final String PASSWORD_ALIAS = "encryptQueryString";
+  private String template;
+  private String param;
+
+  public EncryptUriDescriptor() {
+    super( STEP_NAME );
+  }
+
+  public String getTemplate() {
+    return template;
+  }
+
+  public void setTemplate( String template ) {
+    this.template = template;
+  }
+
+  public String getParam() {
+    return param;
+  }
+
+  public void setParam( String param ) {
+    this.param = param;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/impl/DecryptUriProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/impl/DecryptUriProcessor.java b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/impl/DecryptUriProcessor.java
new file mode 100644
index 0000000..c1b2e8e
--- /dev/null
+++ b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/impl/DecryptUriProcessor.java
@@ -0,0 +1,90 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.encrypturi.impl;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Arrays;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.knox.gateway.encrypturi.EncryptStepContextParams;
+import org.apache.knox.gateway.encrypturi.api.DecryptUriDescriptor;
+import org.apache.knox.gateway.encrypturi.api.EncryptUriDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.CryptoService;
+import org.apache.knox.gateway.services.security.EncryptionResult;
+import org.apache.knox.gateway.util.urltemplate.Expander;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+public class DecryptUriProcessor
+    implements UrlRewriteStepProcessor<DecryptUriDescriptor> {
+
+  private String clusterName;
+  private CryptoService cryptoService;
+  private String param;
+
+  @Override
+  public String getType() {
+    return DecryptUriDescriptor.STEP_NAME;
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, DecryptUriDescriptor descriptor ) throws Exception {
+    clusterName = environment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE );
+    GatewayServices services = environment.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
+    cryptoService = (CryptoService) services.getService(GatewayServices.CRYPTO_SERVICE);
+    param = descriptor.getParam();
+  }
+
+  @Override
+  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
+    if( param != null && !param.isEmpty() ) {
+      Template template = Parser.parseTemplate( "{" + param + "}" );
+      String resolvedTemplate = Expander
+          .expandToString( template, context.getParameters(), context.getEvaluator() );
+      String url = decode( resolvedTemplate );
+      EncryptStepContextParams params = new EncryptStepContextParams();
+      params.addParam( param, Arrays.asList( url ) );
+      context.addParameters( params );
+      return UrlRewriteStepStatus.SUCCESS;
+    }
+    return UrlRewriteStepStatus.FAILURE;
+  }
+
+  @Override
+  public void destroy() {
+  }
+
+  private String decode( String string ) throws UnsupportedEncodingException {
+    byte[] bytes = Base64.decodeBase64( string );
+    EncryptionResult result = EncryptionResult.fromByteArray(bytes);
+    byte[] clear = cryptoService.decryptForCluster(clusterName,
+        EncryptUriDescriptor.PASSWORD_ALIAS,
+        result.cipher,
+        result.iv,
+        result.salt);
+    if (clear != null) {
+      return new String(clear);
+    }
+    return null;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/impl/EncryptUriDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/impl/EncryptUriDeploymentContributor.java b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/impl/EncryptUriDeploymentContributor.java
new file mode 100644
index 0000000..b3ac725
--- /dev/null
+++ b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/impl/EncryptUriDeploymentContributor.java
@@ -0,0 +1,87 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.encrypturi.impl;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributor;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.encrypturi.EncryptUriMessages;
+import org.apache.knox.gateway.encrypturi.api.EncryptUriDescriptor;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.services.security.AliasService;
+import org.apache.knox.gateway.services.security.AliasServiceException;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+import java.util.List;
+
+public class EncryptUriDeploymentContributor
+    extends ProviderDeploymentContributorBase
+    implements ProviderDeploymentContributor {
+
+  private static EncryptUriMessages log = MessagesFactory.get( EncryptUriMessages.class );
+  public static final String PROVIDER_ROLE_NAME = "encrypt";
+  public static final String PROVIDER_IMPL_NAME = "default";
+  private AliasService as;
+
+  @Override
+  public String getRole() {
+    return PROVIDER_ROLE_NAME;
+  }
+
+  @Override
+  public String getName() {
+    return PROVIDER_IMPL_NAME;
+  }
+
+  public void setAliasService(AliasService as) {
+    this.as = as;
+  }
+
+  @Override
+  public void initializeContribution(DeploymentContext context) {
+    super.initializeContribution(context);
+
+    String clusterName = context.getTopology().getName();
+
+    // we don't want to overwrite an existing alias from a previous topology deployment
+    // so we can't just blindly generateAlias here.
+    // this version of getPassword will generate a value for it only if missing
+    try {
+      this.as.getPasswordFromAliasForCluster(clusterName, EncryptUriDescriptor.PASSWORD_ALIAS, true);
+    } catch (AliasServiceException e) {
+      log.unableCreatePasswordForEncryption(e);
+    }
+  }
+
+  @Override
+  public void contributeProvider( DeploymentContext context, Provider provider ) {
+  }
+
+  @Override
+  public void contributeFilter(
+      DeploymentContext context,
+      Provider provider,
+      Service service,
+      ResourceDescriptor resource,
+      List<FilterParamDescriptor> params ) {
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/impl/EncryptUriProcessor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/impl/EncryptUriProcessor.java b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/impl/EncryptUriProcessor.java
new file mode 100644
index 0000000..413ddfc
--- /dev/null
+++ b/gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/impl/EncryptUriProcessor.java
@@ -0,0 +1,86 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.encrypturi.impl;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Arrays;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.knox.gateway.encrypturi.EncryptStepContextParams;
+import org.apache.knox.gateway.encrypturi.api.EncryptUriDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.CryptoService;
+import org.apache.knox.gateway.services.security.EncryptionResult;
+import org.apache.knox.gateway.util.urltemplate.Expander;
+import org.apache.knox.gateway.util.urltemplate.Parser;
+import org.apache.knox.gateway.util.urltemplate.Template;
+
+public class EncryptUriProcessor
+    implements UrlRewriteStepProcessor<EncryptUriDescriptor> {
+
+  private String clusterName;
+  private CryptoService cryptoService;
+  private String template;
+  private String param;
+
+  @Override
+  public String getType() {
+    return EncryptUriDescriptor.STEP_NAME;
+  }
+
+  @Override
+  public void initialize( UrlRewriteEnvironment environment, EncryptUriDescriptor descriptor ) throws Exception {
+    clusterName = environment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE );
+    GatewayServices services = environment.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
+    cryptoService = (CryptoService) services.getService(GatewayServices.CRYPTO_SERVICE);
+    template = descriptor.getTemplate();
+    param = descriptor.getParam();
+  }
+
+  @Override
+  public UrlRewriteStepStatus process( UrlRewriteContext context ) throws Exception {
+    if( param != null && !param.isEmpty() && template != null && !template.isEmpty() ) {
+      Template uri = Parser.parseTemplate( template );
+      String resolvedTemplate = Expander
+          .expandToString( uri, context.getParameters(), context.getEvaluator() );
+      if( resolvedTemplate != null && !resolvedTemplate.isEmpty() ) {
+        String endcoedUrl = encode( resolvedTemplate );
+        EncryptStepContextParams params = new EncryptStepContextParams();
+        params.addParam( param, Arrays.asList( endcoedUrl ) );
+        context.addParameters( params );
+        return UrlRewriteStepStatus.SUCCESS;
+      }
+    }
+    return UrlRewriteStepStatus.FAILURE;
+  }
+
+  @Override
+  public void destroy() {
+  }
+
+  private String encode( String string ) throws UnsupportedEncodingException {
+    EncryptionResult result = cryptoService.encryptForCluster(clusterName, EncryptUriDescriptor.PASSWORD_ALIAS, string.getBytes("UTF-8"));
+    string = Base64.encodeBase64URLSafeString(result.toByteAray());
+    return string;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index 328b0a0..0000000
--- a/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.encrypturi.impl.EncryptUriDeploymentContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor b/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
deleted file mode 100644
index 1404210..0000000
--- a/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
+++ /dev/null
@@ -1,20 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.encrypturi.api.EncryptUriDescriptor
-org.apache.hadoop.gateway.encrypturi.api.DecryptUriDescriptor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor b/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
deleted file mode 100644
index 14bd1d5..0000000
--- a/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
+++ /dev/null
@@ -1,20 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.encrypturi.impl.EncryptUriProcessor
-org.apache.hadoop.gateway.encrypturi.impl.DecryptUriProcessor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..2486c9b
--- /dev/null
+++ b/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.encrypturi.impl.EncryptUriDeploymentContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor b/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
new file mode 100644
index 0000000..c7f1465
--- /dev/null
+++ b/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor
@@ -0,0 +1,20 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.encrypturi.api.EncryptUriDescriptor
+org.apache.knox.gateway.encrypturi.api.DecryptUriDescriptor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor b/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
new file mode 100644
index 0000000..2678c6d
--- /dev/null
+++ b/gateway-provider-rewrite-step-encrypt-uri/src/main/resources/META-INF/services/org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor
@@ -0,0 +1,20 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.encrypturi.impl.EncryptUriProcessor
+org.apache.knox.gateway.encrypturi.impl.DecryptUriProcessor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/api/DecryptUriDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/api/DecryptUriDescriptorTest.java b/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/api/DecryptUriDescriptorTest.java
deleted file mode 100644
index c51bbd7..0000000
--- a/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/api/DecryptUriDescriptorTest.java
+++ /dev/null
@@ -1,55 +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.hadoop.gateway.encrypturi.api;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
-import org.junit.Test;
-
-public class DecryptUriDescriptorTest {
-
-  @Test
-  @SuppressWarnings("rawtypes")
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteStepDescriptor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof DecryptUriDescriptor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + DecryptUriDescriptor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testGetAndSet() {
-    DecryptUriDescriptor descriptor = new DecryptUriDescriptor();
-    assertThat( descriptor.type(), is( "decrypt" ) );
-    assertThat( descriptor.getParam(), nullValue() );
-
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/api/EncryptUriDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/api/EncryptUriDescriptorTest.java b/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/api/EncryptUriDescriptorTest.java
deleted file mode 100644
index ea0c61a..0000000
--- a/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/api/EncryptUriDescriptorTest.java
+++ /dev/null
@@ -1,55 +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.hadoop.gateway.encrypturi.api;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
-import org.junit.Test;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class EncryptUriDescriptorTest {
-
-  @Test
-  @SuppressWarnings("rawtypes")
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteStepDescriptor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof EncryptUriDescriptor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + EncryptUriDescriptor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testGetAndSet() {
-    EncryptUriDescriptor descriptor = new EncryptUriDescriptor();
-    assertThat( descriptor.type(), is( "encrypt" ) );
-    assertThat( descriptor.getParam(), nullValue() );
-
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptDecryptUriProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptDecryptUriProcessorTest.java b/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptDecryptUriProcessorTest.java
deleted file mode 100644
index 9e9f93c..0000000
--- a/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptDecryptUriProcessorTest.java
+++ /dev/null
@@ -1,157 +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.hadoop.gateway.encrypturi.impl;
-
-import org.apache.hadoop.gateway.encrypturi.EncryptStepContextParams;
-import org.apache.hadoop.gateway.encrypturi.api.DecryptUriDescriptor;
-import org.apache.hadoop.gateway.encrypturi.api.EncryptUriDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteContext;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.security.AliasService;
-import org.apache.hadoop.gateway.services.security.CryptoService;
-import org.apache.hadoop.gateway.services.security.impl.DefaultCryptoService;
-import org.easymock.Capture;
-import org.easymock.EasyMock;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.IsNot.not;
-import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString;
-import static org.junit.Assert.fail;
-
-
-public class EncryptDecryptUriProcessorTest {
-
-  @SuppressWarnings("rawtypes")
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( UrlRewriteStepProcessor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof EncryptUriProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + EncryptUriProcessor.class.getName() + " via service loader." );
-
-    loader = ServiceLoader.load( UrlRewriteStepProcessor.class );
-    iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof DecryptUriProcessor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + DecryptUriProcessor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testEncryptDecrypt() throws Exception {
-    String encryptedValueParamName = "address";
-    String clusterName = "test-cluster-name";
-    String passwordAlias = "encryptQueryString";
-
-    // Test encryption.  Result is in encryptedAdrress
-
-    AliasService as = EasyMock.createNiceMock( AliasService.class );
-    String secret = "asdf";
-    EasyMock.expect( as.getPasswordFromAliasForCluster( clusterName, passwordAlias ) ).andReturn( secret.toCharArray() ).anyTimes();
-    CryptoService cryptoService = new DefaultCryptoService();
-    ((DefaultCryptoService)cryptoService).setAliasService( as );
-    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService );
-
-    UrlRewriteEnvironment encEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();
-    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( clusterName ).anyTimes();
-    UrlRewriteContext encContext = EasyMock.createNiceMock( UrlRewriteContext.class );
-
-    EncryptStepContextParams hostPortParams = new EncryptStepContextParams();
-    hostPortParams.addParam( "host", Arrays.asList( "host.yarn.com" ) );
-    hostPortParams.addParam( "port", Arrays.asList( "8088" ) );
-    EasyMock.expect( encContext.getParameters() ).andReturn( hostPortParams );
-
-
-    Capture<EncryptStepContextParams> encodedValue = new Capture<EncryptStepContextParams>();
-    encContext.addParameters( EasyMock.capture( encodedValue ) );
-
-    EasyMock.replay( gatewayServices, as, encEnvironment, encContext );
-
-    EncryptUriDescriptor descriptor = new EncryptUriDescriptor();
-    descriptor.setTemplate( "{host}:{port}" );
-    descriptor.setParam( encryptedValueParamName );
-    EncryptUriProcessor processor = new EncryptUriProcessor();
-    processor.initialize( encEnvironment, descriptor );
-    UrlRewriteStepStatus encStatus = processor.process( encContext );
-
-    assertThat( encStatus, is ( UrlRewriteStepStatus.SUCCESS ) );
-    assertThat( encodedValue.getValue(), notNullValue() );
-    assertThat( encodedValue.getValue().resolve( encryptedValueParamName ).size(), is( 1 ) );
-    String encryptedAdrress = encodedValue.getValue().resolve( encryptedValueParamName ).get( 0 );
-    assertThat( encryptedAdrress, not( isEmptyOrNullString() ) );
-    assertThat( encryptedAdrress, not( "{host}:{port}" ) );
-    assertThat( encryptedAdrress, not( "hdp:8088" ) );
-
-    // Test decryption.  Result is in dectryptedAdrress.
-    String decParam = "foo";
-    gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService );
-    as = EasyMock.createNiceMock( AliasService.class );
-    EasyMock.expect( as.getPasswordFromAliasForCluster( clusterName, passwordAlias ) ).andReturn( secret.toCharArray() ).anyTimes();
-
-    UrlRewriteEnvironment decEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();
-    EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( clusterName ).anyTimes();
-    UrlRewriteContext decContext = EasyMock.createNiceMock( UrlRewriteContext.class );
-
-    EncryptStepContextParams encryptedParams = new EncryptStepContextParams();
-    encryptedParams.addParam( decParam, Arrays.asList( encryptedAdrress ) ); //Value was encrypted by EncryptUriProcessor
-    encryptedParams.addParam( "foo1", Arrays.asList( "test" ) );
-    EasyMock.expect( decContext.getParameters() ).andReturn( encryptedParams );
-
-    Capture<EncryptStepContextParams> decodedValue = new Capture<EncryptStepContextParams>();
-    decContext.addParameters( EasyMock.capture( decodedValue ) );
-
-    EasyMock.replay( gatewayServices, as, decEnvironment, decContext );
-
-    DecryptUriDescriptor decDescriptor = new DecryptUriDescriptor();
-    decDescriptor.setParam( decParam );
-
-    DecryptUriProcessor decProcessor = new DecryptUriProcessor();
-    decProcessor.initialize( decEnvironment, decDescriptor );
-    UrlRewriteStepStatus decStatus = decProcessor.process( decContext );
-    assertThat( decStatus, is ( UrlRewriteStepStatus.SUCCESS ) );
-    assertThat( decodedValue.getValue(), notNullValue() );
-    assertThat( decodedValue.getValue().resolve( decParam ).size(), is( 1 ) );
-    String dectryptedAdrress = decodedValue.getValue().resolve( decParam ).get( 0 );
-    assertThat( dectryptedAdrress, is ( "host.yarn.com:8088" ) );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptUriDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptUriDeploymentContributorTest.java b/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptUriDeploymentContributorTest.java
deleted file mode 100644
index 7f09224..0000000
--- a/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/hadoop/gateway/encrypturi/impl/EncryptUriDeploymentContributorTest.java
+++ /dev/null
@@ -1,105 +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.hadoop.gateway.encrypturi.impl;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteEnvironment;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.security.AliasService;
-import org.apache.hadoop.gateway.services.security.CryptoService;
-import org.apache.hadoop.gateway.services.security.impl.DefaultCryptoService;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Topology;
-import org.easymock.EasyMock;
-import org.jboss.shrinkwrap.api.ShrinkWrap;
-import org.jboss.shrinkwrap.api.spec.WebArchive;
-import org.junit.Test;
-
-import java.io.IOException;
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
-
-public class EncryptUriDeploymentContributorTest {
-
-  @SuppressWarnings("rawtypes")
-  @Test
-  public void testServiceLoader() throws Exception {
-    ServiceLoader loader = ServiceLoader.load( ProviderDeploymentContributor.class );
-    Iterator iterator = loader.iterator();
-    assertThat( "Service iterator empty.", iterator.hasNext() );
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof EncryptUriDeploymentContributor ) {
-        return;
-      }
-    }
-    fail( "Failed to find " + EncryptUriDeploymentContributor.class.getName() + " via service loader." );
-  }
-
-  @Test
-  public void testDeployment() throws IOException {
-    WebArchive webArchive = ShrinkWrap.create( WebArchive.class, "test-acrhive" );
-
-    Provider provider = new Provider();
-    provider.setEnabled( true );
-    provider.setName( EncryptUriDeploymentContributor.PROVIDER_ROLE_NAME );
-
-    Topology topology = new Topology();
-    topology.setName( "Sample" );
-
-    DeploymentContext context = EasyMock.createNiceMock( DeploymentContext.class );
-
-    EasyMock.expect( context.getWebArchive() ).andReturn( webArchive ).anyTimes();
-    EasyMock.expect( context.getTopology() ).andReturn( topology ).anyTimes();
-    EasyMock.replay( context );
-
-    AliasService as = EasyMock.createNiceMock( AliasService.class );
-    CryptoService cryptoService = new DefaultCryptoService();
-    ((DefaultCryptoService) cryptoService).setAliasService( as );
-
-    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
-    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService ).anyTimes();
-
-    UrlRewriteEnvironment encEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();
-
-    EncryptUriDeploymentContributor contributor = new EncryptUriDeploymentContributor();
-    contributor.setAliasService( as );
-
-    assertThat( contributor.getRole(), is( EncryptUriDeploymentContributor.PROVIDER_ROLE_NAME ) );
-    assertThat( contributor.getName(), is( EncryptUriDeploymentContributor.PROVIDER_IMPL_NAME ) );
-
-    // Just make sure it doesn't blow up.
-    contributor.contributeFilter( null, null, null, null, null );
-
-    // Just make sure it doesn't blow up.
-    contributor.initializeContribution( context );
-
-    contributor.contributeProvider( context, provider );
-
-    // Just make sure it doesn't blow up.
-    contributor.finalizeContribution( context );
-
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/api/DecryptUriDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/api/DecryptUriDescriptorTest.java b/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/api/DecryptUriDescriptorTest.java
new file mode 100644
index 0000000..af73679
--- /dev/null
+++ b/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/api/DecryptUriDescriptorTest.java
@@ -0,0 +1,55 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.encrypturi.api;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
+import org.junit.Test;
+
+public class DecryptUriDescriptorTest {
+
+  @Test
+  @SuppressWarnings("rawtypes")
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteStepDescriptor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof DecryptUriDescriptor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + DecryptUriDescriptor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testGetAndSet() {
+    DecryptUriDescriptor descriptor = new DecryptUriDescriptor();
+    assertThat( descriptor.type(), is( "decrypt" ) );
+    assertThat( descriptor.getParam(), nullValue() );
+
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/api/EncryptUriDescriptorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/api/EncryptUriDescriptorTest.java b/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/api/EncryptUriDescriptorTest.java
new file mode 100644
index 0000000..60d4206
--- /dev/null
+++ b/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/api/EncryptUriDescriptorTest.java
@@ -0,0 +1,55 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.encrypturi.api;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
+import org.junit.Test;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class EncryptUriDescriptorTest {
+
+  @Test
+  @SuppressWarnings("rawtypes")
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteStepDescriptor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof EncryptUriDescriptor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + EncryptUriDescriptor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testGetAndSet() {
+    EncryptUriDescriptor descriptor = new EncryptUriDescriptor();
+    assertThat( descriptor.type(), is( "encrypt" ) );
+    assertThat( descriptor.getParam(), nullValue() );
+
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/impl/EncryptDecryptUriProcessorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/impl/EncryptDecryptUriProcessorTest.java b/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/impl/EncryptDecryptUriProcessorTest.java
new file mode 100644
index 0000000..4758982
--- /dev/null
+++ b/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/impl/EncryptDecryptUriProcessorTest.java
@@ -0,0 +1,157 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.encrypturi.impl;
+
+import org.apache.knox.gateway.encrypturi.EncryptStepContextParams;
+import org.apache.knox.gateway.encrypturi.api.DecryptUriDescriptor;
+import org.apache.knox.gateway.encrypturi.api.EncryptUriDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepProcessor;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.AliasService;
+import org.apache.knox.gateway.services.security.CryptoService;
+import org.apache.knox.gateway.services.security.impl.DefaultCryptoService;
+import org.easymock.Capture;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.IsNot.not;
+import static org.hamcrest.text.IsEmptyString.isEmptyOrNullString;
+import static org.junit.Assert.fail;
+
+
+public class EncryptDecryptUriProcessorTest {
+
+  @SuppressWarnings("rawtypes")
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( UrlRewriteStepProcessor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof EncryptUriProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + EncryptUriProcessor.class.getName() + " via service loader." );
+
+    loader = ServiceLoader.load( UrlRewriteStepProcessor.class );
+    iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof DecryptUriProcessor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + DecryptUriProcessor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testEncryptDecrypt() throws Exception {
+    String encryptedValueParamName = "address";
+    String clusterName = "test-cluster-name";
+    String passwordAlias = "encryptQueryString";
+
+    // Test encryption.  Result is in encryptedAdrress
+
+    AliasService as = EasyMock.createNiceMock( AliasService.class );
+    String secret = "asdf";
+    EasyMock.expect( as.getPasswordFromAliasForCluster( clusterName, passwordAlias ) ).andReturn( secret.toCharArray() ).anyTimes();
+    CryptoService cryptoService = new DefaultCryptoService();
+    ((DefaultCryptoService)cryptoService).setAliasService( as );
+    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService );
+
+    UrlRewriteEnvironment encEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();
+    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( clusterName ).anyTimes();
+    UrlRewriteContext encContext = EasyMock.createNiceMock( UrlRewriteContext.class );
+
+    EncryptStepContextParams hostPortParams = new EncryptStepContextParams();
+    hostPortParams.addParam( "host", Arrays.asList( "host.yarn.com" ) );
+    hostPortParams.addParam( "port", Arrays.asList( "8088" ) );
+    EasyMock.expect( encContext.getParameters() ).andReturn( hostPortParams );
+
+
+    Capture<EncryptStepContextParams> encodedValue = new Capture<EncryptStepContextParams>();
+    encContext.addParameters( EasyMock.capture( encodedValue ) );
+
+    EasyMock.replay( gatewayServices, as, encEnvironment, encContext );
+
+    EncryptUriDescriptor descriptor = new EncryptUriDescriptor();
+    descriptor.setTemplate( "{host}:{port}" );
+    descriptor.setParam( encryptedValueParamName );
+    EncryptUriProcessor processor = new EncryptUriProcessor();
+    processor.initialize( encEnvironment, descriptor );
+    UrlRewriteStepStatus encStatus = processor.process( encContext );
+
+    assertThat( encStatus, is ( UrlRewriteStepStatus.SUCCESS ) );
+    assertThat( encodedValue.getValue(), notNullValue() );
+    assertThat( encodedValue.getValue().resolve( encryptedValueParamName ).size(), is( 1 ) );
+    String encryptedAdrress = encodedValue.getValue().resolve( encryptedValueParamName ).get( 0 );
+    assertThat( encryptedAdrress, not( isEmptyOrNullString() ) );
+    assertThat( encryptedAdrress, not( "{host}:{port}" ) );
+    assertThat( encryptedAdrress, not( "hdp:8088" ) );
+
+    // Test decryption.  Result is in dectryptedAdrress.
+    String decParam = "foo";
+    gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService );
+    as = EasyMock.createNiceMock( AliasService.class );
+    EasyMock.expect( as.getPasswordFromAliasForCluster( clusterName, passwordAlias ) ).andReturn( secret.toCharArray() ).anyTimes();
+
+    UrlRewriteEnvironment decEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();
+    EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( clusterName ).anyTimes();
+    UrlRewriteContext decContext = EasyMock.createNiceMock( UrlRewriteContext.class );
+
+    EncryptStepContextParams encryptedParams = new EncryptStepContextParams();
+    encryptedParams.addParam( decParam, Arrays.asList( encryptedAdrress ) ); //Value was encrypted by EncryptUriProcessor
+    encryptedParams.addParam( "foo1", Arrays.asList( "test" ) );
+    EasyMock.expect( decContext.getParameters() ).andReturn( encryptedParams );
+
+    Capture<EncryptStepContextParams> decodedValue = new Capture<EncryptStepContextParams>();
+    decContext.addParameters( EasyMock.capture( decodedValue ) );
+
+    EasyMock.replay( gatewayServices, as, decEnvironment, decContext );
+
+    DecryptUriDescriptor decDescriptor = new DecryptUriDescriptor();
+    decDescriptor.setParam( decParam );
+
+    DecryptUriProcessor decProcessor = new DecryptUriProcessor();
+    decProcessor.initialize( decEnvironment, decDescriptor );
+    UrlRewriteStepStatus decStatus = decProcessor.process( decContext );
+    assertThat( decStatus, is ( UrlRewriteStepStatus.SUCCESS ) );
+    assertThat( decodedValue.getValue(), notNullValue() );
+    assertThat( decodedValue.getValue().resolve( decParam ).size(), is( 1 ) );
+    String dectryptedAdrress = decodedValue.getValue().resolve( decParam ).get( 0 );
+    assertThat( dectryptedAdrress, is ( "host.yarn.com:8088" ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/impl/EncryptUriDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/impl/EncryptUriDeploymentContributorTest.java b/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/impl/EncryptUriDeploymentContributorTest.java
new file mode 100644
index 0000000..8741119
--- /dev/null
+++ b/gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/impl/EncryptUriDeploymentContributorTest.java
@@ -0,0 +1,105 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.encrypturi.impl;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteEnvironment;
+import org.apache.knox.gateway.services.GatewayServices;
+import org.apache.knox.gateway.services.security.AliasService;
+import org.apache.knox.gateway.services.security.CryptoService;
+import org.apache.knox.gateway.services.security.impl.DefaultCryptoService;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Topology;
+import org.easymock.EasyMock;
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.spec.WebArchive;
+import org.junit.Test;
+
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class EncryptUriDeploymentContributorTest {
+
+  @SuppressWarnings("rawtypes")
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( ProviderDeploymentContributor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof EncryptUriDeploymentContributor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + EncryptUriDeploymentContributor.class.getName() + " via service loader." );
+  }
+
+  @Test
+  public void testDeployment() throws IOException {
+    WebArchive webArchive = ShrinkWrap.create( WebArchive.class, "test-acrhive" );
+
+    Provider provider = new Provider();
+    provider.setEnabled( true );
+    provider.setName( EncryptUriDeploymentContributor.PROVIDER_ROLE_NAME );
+
+    Topology topology = new Topology();
+    topology.setName( "Sample" );
+
+    DeploymentContext context = EasyMock.createNiceMock( DeploymentContext.class );
+
+    EasyMock.expect( context.getWebArchive() ).andReturn( webArchive ).anyTimes();
+    EasyMock.expect( context.getTopology() ).andReturn( topology ).anyTimes();
+    EasyMock.replay( context );
+
+    AliasService as = EasyMock.createNiceMock( AliasService.class );
+    CryptoService cryptoService = new DefaultCryptoService();
+    ((DefaultCryptoService) cryptoService).setAliasService( as );
+
+    GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
+    EasyMock.expect( gatewayServices.getService( GatewayServices.CRYPTO_SERVICE ) ).andReturn( cryptoService ).anyTimes();
+
+    UrlRewriteEnvironment encEnvironment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
+    EasyMock.expect( encEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();
+
+    EncryptUriDeploymentContributor contributor = new EncryptUriDeploymentContributor();
+    contributor.setAliasService( as );
+
+    assertThat( contributor.getRole(), is( EncryptUriDeploymentContributor.PROVIDER_ROLE_NAME ) );
+    assertThat( contributor.getName(), is( EncryptUriDeploymentContributor.PROVIDER_IMPL_NAME ) );
+
+    // Just make sure it doesn't blow up.
+    contributor.contributeFilter( null, null, null, null, null );
+
+    // Just make sure it doesn't blow up.
+    contributor.initializeContribution( context );
+
+    contributor.contributeProvider( context, provider );
+
+    // Just make sure it doesn't blow up.
+    contributor.finalizeContribution( context );
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeDescriptor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeDescriptor.java b/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeDescriptor.java
deleted file mode 100644
index f026e38..0000000
--- a/gateway-provider-rewrite-step-secure-query/src/main/java/org/apache/hadoop/gateway/securequery/SecureQueryDecodeDescriptor.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.hadoop.gateway.securequery;
-
-import org.apache.hadoop.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
-
-public class SecureQueryDecodeDescriptor
-    extends UrlRewriteActionDescriptorBase
-    implements UrlRewriteActionDescriptor {
-
-  static final String STEP_NAME = "decode-query";
-
-  public SecureQueryDecodeDescriptor() {
-    super( STEP_NAME );
-  }
-
-  @Override
-  public String getParam() {
-    return null;
-  }
-
-}


[27/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteStreamFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteStreamFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteStreamFilter.java
deleted file mode 100644
index 41f141b..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/javascript/JavaScriptUrlRewriteStreamFilter.java
+++ /dev/null
@@ -1,64 +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.hadoop.gateway.filter.rewrite.impl.javascript;
-
-import org.apache.commons.io.input.ReaderInputStream;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStreamFilter;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-
-public class JavaScriptUrlRewriteStreamFilter implements UrlRewriteStreamFilter {
-
-  private static String[] TYPES = new String[]{ "application/javascript", "text/javascript", "*/javascript",
-      "application/x-javascript", "text/x-javascript", "*/x-javascript" };
-  private static String[] NAMES = new String[]{ null };
-
-  @Override
-  public String[] getTypes() {
-    return TYPES;
-  }
-
-  @Override
-  public String[] getNames() {
-    return NAMES;
-  }
-
-  @Override
-  public InputStream filter(
-      InputStream stream,
-      String encoding,
-      UrlRewriter rewriter,
-      Resolver resolver,
-      UrlRewriter.Direction direction,
-      UrlRewriteFilterContentDescriptor config )
-          throws IOException {
-
-    if ( config != null ) {
-      return new ReaderInputStream(
-          new JavaScriptUrlRewriteFilterReader(
-              new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
-    } else {
-      return stream;
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReader.java
deleted file mode 100644
index 10fc9b8..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonFilterReader.java
+++ /dev/null
@@ -1,644 +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.hadoop.gateway.filter.rewrite.impl.json;
-
-import com.fasterxml.jackson.core.JsonFactory;
-import com.fasterxml.jackson.core.JsonGenerator;
-import com.fasterxml.jackson.core.JsonParser;
-import com.fasterxml.jackson.core.JsonToken;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import com.fasterxml.jackson.databind.node.TextNode;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterBufferDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterDetectDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterGroupDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.util.JsonPath;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringWriter;
-import java.util.List;
-import java.util.Stack;
-import java.util.regex.Pattern;
-
-class JsonFilterReader extends Reader {
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-
-  private static final UrlRewriteFilterPathDescriptor.Compiler<JsonPath.Expression> JPATH_COMPILER = new JsonPathCompiler();
-  private static final UrlRewriteFilterPathDescriptor.Compiler<Pattern> REGEX_COMPILER = new RegexCompiler();
-
-  private JsonFactory factory;
-  private JsonParser parser;
-  private JsonGenerator generator;
-  private ObjectMapper mapper;
-
-  private Reader reader;
-  private int offset;
-  private StringWriter writer;
-  private StringBuffer buffer;
-  private Stack<Level> stack;
-  private Level bufferingLevel;
-  private UrlRewriteFilterBufferDescriptor bufferingConfig;
-  private UrlRewriteFilterGroupDescriptor config;
-
-
-  public JsonFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException {
-    this.reader = reader;
-    factory = new JsonFactory();
-    mapper = new ObjectMapper();
-    parser = factory.createParser( reader );
-    writer = new StringWriter();
-    buffer = writer.getBuffer();
-    offset = 0;
-    generator = factory.createGenerator( writer );
-    stack = new Stack<Level>();
-    bufferingLevel = null;
-    bufferingConfig = null;
-    this.config = config;
-  }
-
-  @Override
-  public int read( char[] destBuffer, int destOffset, int destCount ) throws IOException {
-    int count = 0;
-    int available = buffer.length() - offset;
-
-    if( available == 0 ) {
-      JsonToken token = parser.nextToken();
-      if( token == null ) {
-        count = -1;
-      } else {
-        processCurrentToken();
-        available = buffer.length() - offset;
-      }
-    }
-
-    if( available > 0 ) {
-      count = Math.min( destCount, available );
-      buffer.getChars( offset, offset+count, destBuffer, destOffset );
-      offset += count;
-      if( offset == buffer.length() ) {
-        offset = 0;
-        buffer.setLength( 0 );
-      }
-    }
-
-    return count;
-  }
-
-  private void processCurrentToken() throws IOException {
-    switch( parser.getCurrentToken() ) {
-      case START_OBJECT:
-        processStartObject();
-        break;
-      case END_OBJECT:
-        processEndObject();
-        break;
-      case START_ARRAY:
-        processStartArray();
-        break;
-      case END_ARRAY:
-        processEndArray();
-        break;
-      case FIELD_NAME:
-        processFieldName(); // Could be the name of an object, array or value.
-        break;
-      case VALUE_STRING:
-        processValueString();
-        break;
-      case VALUE_NUMBER_INT:
-      case VALUE_NUMBER_FLOAT:
-        processValueNumber();
-        break;
-      case VALUE_TRUE:
-      case VALUE_FALSE:
-        processValueBoolean();
-        break;
-      case VALUE_NULL:
-        processValueNull();
-        break;
-      case NOT_AVAILABLE:
-        // Ignore it.
-        break;
-    }
-    generator.flush();
-  }
-
-  private Level pushLevel( String field, JsonNode node, JsonNode scopeNode, UrlRewriteFilterGroupDescriptor scopeConfig ) {
-    if( !stack.isEmpty() ) {
-      Level top = stack.peek();
-      if( scopeNode == null ) {
-        scopeNode = top.scopeNode;
-        scopeConfig = top.scopeConfig;
-      }
-    }
-    Level level = new Level( field, node, scopeNode, scopeConfig );
-    stack.push( level );
-    return level;
-  }
-
-  private void processStartObject() throws IOException {
-    JsonNode node;
-    Level child;
-    Level parent;
-    if( stack.isEmpty() ) {
-      node = mapper.createObjectNode();
-      child = pushLevel( null, node, node, config );
-    } else {
-      child = stack.peek();
-      if( child.node == null ) {
-        child.node = mapper.createObjectNode();
-        parent = stack.get( stack.size()-2 );
-        switch( parent.node.asToken() ) {
-          case START_ARRAY:
-            ((ArrayNode)parent.node ).add( child.node );
-            break;
-          case START_OBJECT:
-            ((ObjectNode)parent.node ).put( child.field, child.node );
-            break;
-          default:
-            throw new IllegalStateException();
-        }
-      } else if( child.isArray() ) {
-        parent = child;
-        node = mapper.createObjectNode();
-        child = pushLevel( null, node, null, null );
-        ((ArrayNode)parent.node ).add( child.node );
-      } else {
-        throw new IllegalStateException();
-      }
-    }
-    if( bufferingLevel == null ) {
-      if( !startBuffering( child ) ) {
-        generator.writeStartObject();
-      }
-    }
-  }
-
-  private void processEndObject() throws IOException {
-    Level child;
-    Level parent;
-    child = stack.pop();
-    if( bufferingLevel == child ) {
-      filterBufferedNode( child );
-      mapper.writeTree( generator, child.node );
-      bufferingLevel = null;
-      bufferingConfig = null;
-    } else if( bufferingLevel == null ) {
-      generator.writeEndObject();
-      if( !stack.isEmpty() ) {
-        parent = stack.peek();
-        switch( parent.node.asToken() ) {
-          case START_ARRAY:
-            ((ArrayNode)parent.node ).removeAll();
-            break;
-          case START_OBJECT:
-            ((ObjectNode)parent.node ).removeAll();
-            break;
-          default:
-            throw new IllegalStateException();
-        }
-      }
-    }
-  }
-
-  private void processStartArray() throws IOException {
-    JsonNode node;
-    Level child;
-    Level parent;
-    if( stack.isEmpty() ) {
-      node = mapper.createArrayNode();
-      child = pushLevel( null, node, node, config );
-    } else {
-      child = stack.peek();
-      if( child.node == null ) {
-        child.node = mapper.createArrayNode();
-        parent = stack.get( stack.size() - 2 );
-        switch( parent.node.asToken() ) {
-          case START_ARRAY:
-            ((ArrayNode)parent.node ).add( child.node );
-            break;
-          case START_OBJECT:
-            ((ObjectNode)parent.node ).put( child.field, child.node );
-            break;
-          default:
-            throw new IllegalStateException();
-        }
-      } else if( child.isArray() ) {
-        parent = child;
-        child = pushLevel( null, mapper.createArrayNode(), null, null );
-        ((ArrayNode)parent.node ).add( child.node );
-      } else {
-        throw new IllegalStateException();
-      }
-    }
-    if( bufferingLevel == null ) {
-      if( !startBuffering( child ) ) {
-        generator.writeStartArray();
-      }
-    }
-  }
-
-  private void processEndArray() throws IOException {
-    Level child;
-    Level parent;
-    child = stack.pop();
-    if( bufferingLevel == child ) {
-      filterBufferedNode( child );
-      mapper.writeTree( generator, child.node );
-      bufferingLevel = null;
-      bufferingConfig = null;
-    } else if( bufferingLevel == null ) {
-      generator.writeEndArray();
-      if( !stack.isEmpty() ) {
-        parent = stack.peek();
-        switch( parent.node.asToken() ) {
-          case START_ARRAY:
-            ((ArrayNode)parent.node ).removeAll();
-            break;
-          case START_OBJECT:
-            ((ObjectNode)parent.node ).removeAll();
-            break;
-          default:
-            throw new IllegalStateException();
-        }
-      }
-    }
-  }
-
-  private void processFieldName() throws IOException {
-    Level child = pushLevel( parser.getCurrentName(), null, null, null );
-    try {
-      child.field = filterFieldName( child.field );
-    } catch( Exception e ) {
-      LOG.failedToFilterFieldName( child.field, e );
-      // Write original name.
-    }
-    if( bufferingLevel == null ) {
-      generator.writeFieldName( child.field );
-    }
-  }
-
-  private void processValueString() throws IOException {
-    Level child;
-    Level parent;
-    String value = null;
-    parent = stack.peek();
-    if( parent.isArray() ) {
-      ArrayNode array = (ArrayNode)parent.node;
-      array.add( parser.getText() );
-      if( bufferingLevel == null ) {
-        value = filterStreamValue( parent );
-        array.set( array.size()-1, new TextNode( value ) );
-      } else {
-        array.removeAll();
-      }
-    } else {
-      child = stack.pop();
-      parent = stack.peek();
-      ((ObjectNode)parent.node ).put( child.field, parser.getText() );
-      if( bufferingLevel == null ) {
-        child.node = parent.node; // Populate the JsonNode of the child for filtering.
-        value = filterStreamValue( child );
-      }
-    }
-    if( bufferingLevel == null ) {
-      if( parent.node.isArray() ) {
-        ((ArrayNode)parent.node).removeAll();
-      } else {
-        ((ObjectNode)parent.node).removeAll();
-      }
-      generator.writeString( value );
-    }
-  }
-
-  private void processValueNumber() throws IOException {
-    Level child;
-    Level parent;
-    parent = stack.peek();
-    if( parent.isArray() ) {
-      if( bufferingLevel != null ) {
-        ArrayNode array = (ArrayNode)parent.node;
-        processBufferedArrayValueNumber( array );
-      }
-    } else {
-      child = stack.pop();
-      if( bufferingLevel != null ) {
-        parent = stack.peek();
-        ObjectNode object = (ObjectNode)parent.node;
-        processBufferedFieldValueNumber( child, object );
-      }
-    }
-    if( bufferingLevel == null ) {
-      processedUnbufferedValueNumber();
-    }
-  }
-
-  private void processedUnbufferedValueNumber() throws IOException {
-    switch( parser.getNumberType() ) {
-      case INT:
-        generator.writeNumber( parser.getIntValue() );
-        break;
-      case LONG:
-        generator.writeNumber( parser.getLongValue() );
-        break;
-      case BIG_INTEGER:
-        generator.writeNumber( parser.getBigIntegerValue() );
-        break;
-      case FLOAT:
-        generator.writeNumber( parser.getFloatValue() );
-        break;
-      case DOUBLE:
-        generator.writeNumber( parser.getDoubleValue() );
-        break;
-      case BIG_DECIMAL:
-        generator.writeNumber( parser.getDecimalValue() );
-        break;
-    }
-  }
-
-  private void processBufferedFieldValueNumber( Level child, ObjectNode object ) throws IOException {
-    //object.put( child.field, parser.getDecimalValue() );
-    switch( parser.getNumberType() ) {
-      case INT:
-        object.put( child.field, parser.getIntValue() );
-        break;
-      case LONG:
-        object.put( child.field, parser.getLongValue() );
-        break;
-      case BIG_INTEGER:
-        object.put( child.field, parser.getDecimalValue() );
-        break;
-      case FLOAT:
-        object.put( child.field, parser.getFloatValue() );
-        break;
-      case DOUBLE:
-        object.put( child.field, parser.getDoubleValue() );
-        break;
-      case BIG_DECIMAL:
-        object.put( child.field, parser.getDecimalValue() );
-        break;
-    }
-  }
-
-  private void processBufferedArrayValueNumber( ArrayNode array ) throws IOException {
-    //array.add( parser.getDecimalValue() );
-    switch( parser.getNumberType() ) {
-      case INT:
-        array.add( parser.getIntValue() );
-        break;
-      case LONG:
-        array.add( parser.getLongValue() );
-        break;
-      case BIG_INTEGER:
-        array.add( parser.getDecimalValue() );
-        break;
-      case FLOAT:
-        array.add( parser.getFloatValue() );
-        break;
-      case DOUBLE:
-        array.add( parser.getDoubleValue() );
-        break;
-      case BIG_DECIMAL:
-        array.add( parser.getDecimalValue() );
-        break;
-    }
-  }
-
-  private void processValueBoolean() throws IOException {
-    Level child;
-    Level parent;
-    parent = stack.peek();
-    if( parent.isArray() ) {
-      ((ArrayNode)parent.node ).add( parser.getBooleanValue() );
-      //dump();
-      if( bufferingLevel == null ) {
-        ((ArrayNode)parent.node ).removeAll();
-      }
-    } else {
-      child = stack.pop();
-      parent = stack.peek();
-      ((ObjectNode)parent.node ).put( child.field, parser.getBooleanValue() );
-      //dump();
-      if( bufferingLevel == null ) {
-        ((ObjectNode)parent.node ).remove( child.field );
-      }
-    }
-    if( bufferingLevel == null ) {
-      generator.writeBoolean( parser.getBooleanValue() );
-    }
-  }
-
-  private void processValueNull() throws IOException {
-    Level child;
-    Level parent = stack.peek();
-    if( parent.isArray() ) {
-      ((ArrayNode)parent.node ).addNull();
-      //dump();
-      if( bufferingLevel == null ) {
-        ((ArrayNode)parent.node ).removeAll();
-      }
-    } else {
-      child = stack.pop();
-      parent = stack.peek();
-      ((ObjectNode)parent.node ).putNull( child.field );
-      //dump();
-      if( bufferingLevel == null ) {
-        ((ObjectNode)parent.node ).remove( child.field );
-      }
-    }
-    if( bufferingLevel == null ) {
-      generator.writeNull();
-    }
-  }
-
-  protected boolean startBuffering( Level node ) {
-    boolean buffered = false;
-    UrlRewriteFilterGroupDescriptor scope = node.scopeConfig;
-    if( scope != null ) {
-      for( UrlRewriteFilterPathDescriptor selector : scope.getSelectors() ) {
-        JsonPath.Expression path = (JsonPath.Expression)selector.compiledPath( JPATH_COMPILER );
-        List<JsonPath.Match> matches = path.evaluate( node.scopeNode );
-        if( matches != null && matches.size() > 0 ) {
-          if( selector instanceof UrlRewriteFilterBufferDescriptor ) {
-            bufferingLevel = node;
-            bufferingConfig = (UrlRewriteFilterBufferDescriptor)selector;
-            buffered = true;
-          }
-          break;
-        }
-      }
-    }
-    return buffered;
-  }
-
-  protected String filterStreamValue( Level node ) {
-    String value;
-    if( node.isArray() ) {
-      value = node.node.get( 0 ).asText();
-    } else {
-      value = node.node.get( node.field ).asText();
-    }
-    String rule = null;
-    UrlRewriteFilterGroupDescriptor scope = node.scopeConfig;
-    //TODO: Scan the top level apply rules for the first match.
-    if( scope != null ) {
-      for( UrlRewriteFilterPathDescriptor selector : scope.getSelectors() ) {
-        JsonPath.Expression path = (JsonPath.Expression)selector.compiledPath( JPATH_COMPILER );
-        List<JsonPath.Match> matches = path.evaluate( node.scopeNode );
-        if( matches != null && matches.size() > 0 ) {
-          JsonPath.Match match = matches.get( 0 );
-          if( match.getNode().isTextual() ) {
-            if( selector instanceof UrlRewriteFilterApplyDescriptor ) {
-              UrlRewriteFilterApplyDescriptor apply = (UrlRewriteFilterApplyDescriptor)selector;
-              rule = apply.rule();
-              break;
-            }
-          }
-        }
-      }
-    }
-    try {
-      value = filterValueString( node.field, value, rule );
-      if( node.isArray() ) {
-        ((ArrayNode)node.node).set( 0, new TextNode( value ) );
-      } else {
-        ((ObjectNode)node.node).put( node.field, value );
-      }
-    } catch( Exception e ) {
-      LOG.failedToFilterValue( value, rule, e );
-    }
-    return value;
-  }
-
-  private void filterBufferedNode( Level node ) {
-    for( UrlRewriteFilterPathDescriptor selector : bufferingConfig.getSelectors() ) {
-      JsonPath.Expression path = (JsonPath.Expression)selector.compiledPath( JPATH_COMPILER );
-      List<JsonPath.Match> matches = path.evaluate( node.node );
-      for( JsonPath.Match match : matches ) {
-        if( selector instanceof UrlRewriteFilterApplyDescriptor ) {
-          if( match.getNode().isTextual() ) {
-            filterBufferedValue( match, (UrlRewriteFilterApplyDescriptor)selector );
-          }
-        } else if( selector instanceof UrlRewriteFilterDetectDescriptor ) {
-          UrlRewriteFilterDetectDescriptor detectConfig = (UrlRewriteFilterDetectDescriptor)selector;
-          JsonPath.Expression detectPath = (JsonPath.Expression)detectConfig.compiledPath( JPATH_COMPILER );
-          List<JsonPath.Match> detectMatches = detectPath.evaluate( node.node );
-          for( JsonPath.Match detectMatch : detectMatches ) {
-            if( detectMatch.getNode().isTextual() ) {
-              String detectValue = detectMatch.getNode().asText();
-              Pattern detectPattern = detectConfig.compiledValue( REGEX_COMPILER );
-              if( detectPattern.matcher( detectValue ).matches() ) {
-                filterBufferedValues( node, detectConfig.getSelectors() );
-              }
-            }
-          }
-        }
-      }
-    }
-  }
-
-  private void filterBufferedValues( Level node, List<UrlRewriteFilterPathDescriptor> selectors ) {
-    for( UrlRewriteFilterPathDescriptor selector : selectors ) {
-      JsonPath.Expression path = (JsonPath.Expression)selector.compiledPath( JPATH_COMPILER );
-      List<JsonPath.Match> matches = path.evaluate( node.node );
-      for( JsonPath.Match match : matches ) {
-        if( match.getNode().isTextual() ) {
-          if( selector instanceof UrlRewriteFilterApplyDescriptor ) {
-            filterBufferedValue( match, (UrlRewriteFilterApplyDescriptor)selector );
-          }
-        }
-      }
-    }
-  }
-
-  private void filterBufferedValue( JsonPath.Match match, UrlRewriteFilterApplyDescriptor apply ) {
-    String field = match.getField();
-    String value = match.getNode().asText();
-    try {
-      value = filterValueString( field, value, apply.rule() );
-      ((ObjectNode)match.getParent().getNode()).put( field, value );
-    } catch( Exception e ) {
-      LOG.failedToFilterValue( value, apply.rule(), e );
-    }
-  }
-
-  protected String filterFieldName( String field ) {
-    return field;
-  }
-
-  protected String filterValueString( String name, String value, String rule ) {
-    return value;
-  }
-
-  @Override
-  public void close() throws IOException {
-    generator.close();
-    writer.close();
-    parser.close();
-    reader.close();
-  }
-
-  private static class Level {
-    String field;
-    JsonNode node;
-    JsonNode scopeNode;
-    UrlRewriteFilterGroupDescriptor scopeConfig;
-    private Level( String field, JsonNode node, JsonNode scopeNode, UrlRewriteFilterGroupDescriptor scopeConfig ) {
-      this.field = field;
-      this.node = node;
-      this.scopeNode = scopeNode;
-      this.scopeConfig = scopeConfig;
-    }
-    public boolean isArray() {
-      return node != null && node.isArray();
-    }
-  }
-
-  private static class JsonPathCompiler implements UrlRewriteFilterPathDescriptor.Compiler<JsonPath.Expression> {
-    @Override
-    public JsonPath.Expression compile( String expression, JsonPath.Expression compiled ) {
-      return JsonPath.compile( expression );
-    }
-  }
-
-  private static class RegexCompiler implements UrlRewriteFilterPathDescriptor.Compiler<Pattern> {
-    @Override
-    public Pattern compile( String expression, Pattern compiled ) {
-      if( compiled != null ) {
-        return compiled;
-      } else {
-        return Pattern.compile( expression );
-      }
-    }
-  }
-
-//  private void dump() throws IOException {
-//    mapper.writeTree( factory.createGenerator( System.out ), stack.get( 0 ).node );
-//    System.out.println();
-//  }
-
-}
-

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonUrlRewriteFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonUrlRewriteFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonUrlRewriteFilterReader.java
deleted file mode 100644
index a5bbc82..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonUrlRewriteFilterReader.java
+++ /dev/null
@@ -1,64 +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.hadoop.gateway.filter.rewrite.impl.json;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.net.URISyntaxException;
-
-public class JsonUrlRewriteFilterReader extends JsonFilterReader {
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-
-  private Resolver resolver;
-  private UrlRewriter rewriter;
-  private UrlRewriter.Direction direction;
-
-  public JsonUrlRewriteFilterReader(
-      Reader reader,
-      UrlRewriter rewriter,
-      Resolver resolver,
-      UrlRewriter.Direction direction,
-      UrlRewriteFilterContentDescriptor config )
-          throws IOException {
-    super( reader, config );
-    this.resolver = resolver;
-    this.rewriter = rewriter;
-    this.direction = direction;
-  }
-
-  protected String filterValueString( String name, String value, String rule ) {
-    try {
-      Template input = Parser.parseLiteral( value );
-      Template output = rewriter.rewrite( resolver, input, direction, rule );
-      value = output.getPattern();
-    } catch( URISyntaxException e ) {
-      LOG.failedToParseValueForUrlRewrite( value );
-    }
-    return value;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonUrlRewriteStreamFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonUrlRewriteStreamFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonUrlRewriteStreamFilter.java
deleted file mode 100644
index 9599f40..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/json/JsonUrlRewriteStreamFilter.java
+++ /dev/null
@@ -1,59 +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.hadoop.gateway.filter.rewrite.impl.json;
-
-import org.apache.commons.io.input.ReaderInputStream;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStreamFilter;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-
-public class JsonUrlRewriteStreamFilter implements UrlRewriteStreamFilter {
-
-  private static String[] TYPES = new String[]{ "application/json", "text/json", "*/json" };
-  private static String[] NAMES = new String[]{ null };
-
-  @Override
-  public String[] getTypes() {
-    return TYPES;
-  }
-
-  @Override
-  public String[] getNames() {
-    return NAMES;
-  }
-
-  @Override
-  public InputStream filter(
-      InputStream stream,
-      String encoding,
-      UrlRewriter rewriter,
-      Resolver resolver,
-      UrlRewriter.Direction direction,
-      UrlRewriteFilterContentDescriptor config )
-          throws IOException {
-    return new ReaderInputStream(
-        new JsonUrlRewriteFilterReader(
-            new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/noop/NoOpUrlRewriteStreamFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/noop/NoOpUrlRewriteStreamFilter.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/noop/NoOpUrlRewriteStreamFilter.java
deleted file mode 100644
index 00a9027..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/noop/NoOpUrlRewriteStreamFilter.java
+++ /dev/null
@@ -1,55 +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.hadoop.gateway.filter.rewrite.impl.noop;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteStreamFilter;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-public class NoOpUrlRewriteStreamFilter implements UrlRewriteStreamFilter {
-
-  private static String[] TYPES = new String[]{ null };
-  private static String[] NAMES = new String[]{ null };
-
-  @Override
-  public String[] getTypes() {
-    return TYPES;
-  }
-
-  @Override
-  public String[] getNames() {
-    return NAMES;
-  }
-
-  @Override
-  public InputStream filter(
-      InputStream stream,
-      String encoding,
-      UrlRewriter rewriter,
-      Resolver resolver,
-      UrlRewriter.Direction direction,
-      UrlRewriteFilterContentDescriptor config )
-          throws IOException {
-    return stream;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReader.java
deleted file mode 100644
index 2dd6519..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlFilterReader.java
+++ /dev/null
@@ -1,643 +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.hadoop.gateway.filter.rewrite.impl.xml;
-
-import org.apache.commons.lang3.StringEscapeUtils;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterBufferDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterDetectDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterGroupDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterScopeDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteResources;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.i18n.resources.ResourcesFactory;
-import org.apache.hadoop.gateway.util.XmlUtils;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.Text;
-
-import javax.xml.namespace.QName;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.stream.XMLEventReader;
-import javax.xml.stream.XMLInputFactory;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.events.Attribute;
-import javax.xml.stream.events.Characters;
-import javax.xml.stream.events.Comment;
-import javax.xml.stream.events.EndElement;
-import javax.xml.stream.events.Namespace;
-import javax.xml.stream.events.StartDocument;
-import javax.xml.stream.events.StartElement;
-import javax.xml.stream.events.XMLEvent;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-import javax.xml.xpath.XPath;
-import javax.xml.xpath.XPathConstants;
-import javax.xml.xpath.XPathExpression;
-import javax.xml.xpath.XPathExpressionException;
-import javax.xml.xpath.XPathFactory;
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.util.Iterator;
-import java.util.Stack;
-import java.util.regex.Pattern;
-
-public abstract class XmlFilterReader extends Reader {
-
-  private static final UrlRewriteResources RES = ResourcesFactory.get( UrlRewriteResources.class );
-
-  private static final String DEFAULT_XML_VERSION = "1.0";
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-  private static final UrlRewriteFilterPathDescriptor.Compiler<XPathExpression> XPATH_COMPILER = new XmlPathCompiler();
-  private static final UrlRewriteFilterPathDescriptor.Compiler<Pattern> REGEX_COMPILER = new RegexCompiler();
-
-  private Reader reader;
-  private UrlRewriteFilterContentDescriptor config;
-  private int offset;
-  private StringWriter writer;
-  private StringBuffer buffer;
-  private XMLInputFactory factory;
-  private XMLEventReader parser;
-  private Document document;
-  private Stack<Level> stack;
-  private boolean isEmptyElement;
-
-  protected XmlFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException, XMLStreamException {
-    this.reader = reader;
-    this.config = config;
-    writer = new StringWriter();
-    buffer = writer.getBuffer();
-    offset = 0;
-    document = null;
-    stack = new Stack<Level>();
-    isEmptyElement = false;
-    factory = XMLInputFactory.newFactory();
-    //KNOX-620 factory.setProperty( XMLConstants.ACCESS_EXTERNAL_DTD, "false" );
-    //KNOX-620 factory.setProperty( XMLConstants.ACCESS_EXTERNAL_SCHEMA, "false" );
-    factory.setProperty( "javax.xml.stream.isReplacingEntityReferences", Boolean.FALSE );
-    factory.setProperty("http://java.sun.com/xml/stream/"
-                + "properties/report-cdata-event", Boolean.TRUE);
-    parser = factory.createXMLEventReader( reader );
-  }
-
-  protected abstract String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName );
-
-  protected abstract String filterText( QName elementName, String text, String ruleName );
-
-  @Override
-  public int read( char[] destBuffer, int destOffset, int destCount ) throws IOException {
-    int count = 0;
-    int available = buffer.length() - offset;
-
-    if( available == 0 ) {
-      if( parser.hasNext() ) {
-        try {
-          XMLEvent event = parser.nextEvent();
-          processEvent( event );
-        } catch( IOException e ) {
-          throw e;
-        } catch( RuntimeException e ) {
-          throw e;
-        } catch ( Exception e ) {
-          throw new RuntimeException( e );
-        }
-        available = buffer.length() - offset;
-      } else {
-        count = -1;
-      }
-    }
-
-    if( available > 0 ) {
-      count = Math.min( destCount, available );
-      buffer.getChars( offset, offset + count, destBuffer, destOffset );
-      offset += count;
-      if( offset == buffer.length() ) {
-        offset = 0;
-        buffer.setLength( 0 );
-      }
-    }
-    return count;
-  }
-
-  private void processEvent( XMLEvent event ) throws ParserConfigurationException, XPathExpressionException, IOException, XMLStreamException {
-    int type = event.getEventType();
-    switch( type ) {
-      case XMLEvent.START_DOCUMENT:
-        processStartDocument( (StartDocument)event );
-        break;
-      case XMLEvent.END_DOCUMENT:
-        processEndDocument();
-        break;
-      case XMLEvent.START_ELEMENT:
-        if( parser.peek().getEventType() == XMLEvent.END_ELEMENT )
-          isEmptyElement = true;
-        processStartElement( event.asStartElement());
-        break;
-      case XMLEvent.END_ELEMENT:
-        processEndElement( event.asEndElement() );
-        isEmptyElement = false;
-        break;
-      case XMLEvent.CHARACTERS:
-      case XMLEvent.CDATA:
-      case XMLEvent.SPACE:
-        processCharacters( event.asCharacters() );
-        break;
-      case XMLEvent.COMMENT:
-        processComment( (Comment)event );
-        break;
-      case XMLEvent.DTD:
-      case XMLEvent.NAMESPACE:
-      case XMLEvent.ATTRIBUTE:
-      case XMLEvent.ENTITY_REFERENCE:
-      case XMLEvent.ENTITY_DECLARATION:
-      case XMLEvent.NOTATION_DECLARATION:
-      case XMLEvent.PROCESSING_INSTRUCTION:
-      default:
-        // Fail if we run into any of these for now.
-        throw new IllegalStateException( Integer.toString( type ) );
-    }
-  }
-
-  private void processStartDocument( StartDocument event ) throws ParserConfigurationException {
-    //System.out.println( "SD=" + event );
-    String s;
-
-    document = XmlUtils.createDocument( false );
-    pushLevel( null, event, document, document, config );
-
-    writer.write( "<?xml" );
-
-    s = event.getVersion();
-    if( s == null ) {
-      s = DEFAULT_XML_VERSION;
-    }
-    writer.write( " version=\"");
-    writer.write( s );
-    writer.write( "\"" );
-
-    s = event.getCharacterEncodingScheme();
-    if( s != null ) {
-      writer.write( " encoding=\"");
-      writer.write( s );
-      writer.write( "\"" );
-    }
-
-    writer.write( " standalone=\"");
-    writer.write( event.isStandalone() ? "yes" : "no" );
-    writer.write( "\"" );
-
-    writer.write( "?>" );
-  }
-
-  private void processEndDocument() {
-    stack.clear();
-    document = null;
-  }
-
-  private void processStartElement( StartElement event ) throws XPathExpressionException {
-    //System.out.println( "SE=" + event );
-
-    // Create a new "empty" element and add it to the document.
-    Element element = bufferElement( event );
-    Level parent = stack.peek();
-    parent.node.appendChild( element );
-
-    // If already buffering just continue to do so.
-    // Note: Don't currently support nested buffer or scope descriptors.
-    if( currentlyBuffering() ) {
-      pushLevel( parent, event, element, parent.scopeNode, parent.scopeConfig );
-      bufferAttributes( event, element );
-    // Else not currently buffering
-    } else {
-      // See if there is a matching path descriptor in the current scope.
-      UrlRewriteFilterPathDescriptor descriptor = pickFirstMatchingPath( parent );
-      if( descriptor != null ) {
-        // If this is a buffer descriptor then switch to buffering and buffer the attributes.
-        if( descriptor instanceof UrlRewriteFilterBufferDescriptor ) {
-          pushLevel( parent, event, element, element, (UrlRewriteFilterBufferDescriptor)descriptor );
-          bufferAttributes( event, element );
-        // Otherwise if this is a scope descriptor then change the scope and stream the attributes.
-        } else if( descriptor instanceof UrlRewriteFilterScopeDescriptor ) {
-          pushLevel( parent, event, element, element, (UrlRewriteFilterScopeDescriptor)descriptor );
-          streamElement( event, element );
-        // Else found an unexpected matching path.
-        } else {
-          // This is likely because there is an <apply> targeted at the text of an element.
-          // That "convenience" config will be taken care of in the streamElement() processing.
-          pushLevel( parent, event, element, parent.scopeNode, parent.scopeConfig );
-          streamElement( event, element );
-        }
-      // If there is no matching path descriptor then continue streaming.
-      } else {
-        pushLevel( parent, event, element, parent.scopeNode, parent.scopeConfig );
-        streamElement( event, element );
-      }
-    }
-  }
-
-  private void processEndElement( EndElement event ) throws XPathExpressionException, IOException {
-    //System.out.println( "EE=" + event );
-    boolean buffering = currentlyBuffering();
-    Level child = stack.pop();
-    if( buffering ) {
-      if( child.node == child.scopeNode ) {
-        processBufferedElement( child );
-      }
-    } else {
-      if( ! isEmptyElement ) {
-        QName n = event.getName();
-        writer.write( "</" );
-        String p = n.getPrefix();
-        if( p != null && !p.isEmpty() ) {
-          writer.write( p );
-          writer.write( ":" );
-        }
-        writer.write( n.getLocalPart() );
-        writer.write( ">" );
-      }
-      child.node.getParentNode().removeChild( child.node );
-    }
-  }
-
-  private Element bufferElement( StartElement event ) {
-    QName qname = event.getName();
-    String prefix = qname.getPrefix();
-    String uri = qname.getNamespaceURI();
-    Element element;
-    if( uri == null || uri.isEmpty() ) {
-      element = document.createElement( qname.getLocalPart() );
-    } else {
-      element = document.createElementNS( qname.getNamespaceURI(), qname.getLocalPart() );
-      if( prefix != null && !prefix.isEmpty() ) {
-        element.setPrefix( prefix );
-      }
-    }
-    // Always need to buffer the namespaces regardless of what else happens so that XPath will work on attributes
-    // namespace qualified attributes.
-    bufferNamespaces( event, element );
-    return element;
-  }
-
-  private void bufferNamespaces( StartElement event, Element element ) {
-    Iterator namespaces = event.getNamespaces();
-    while( namespaces.hasNext() ) {
-      Namespace namespace = (Namespace)namespaces.next();
-      if( namespace.isDefaultNamespaceDeclaration() ) {
-        element.setAttribute( "xmlns", namespace.getNamespaceURI() );
-      } else {
-        element.setAttribute( "xmlns:" + namespace.getPrefix(), namespace.getNamespaceURI() );
-      }
-    }
-  }
-
-  private void streamElement( StartElement event, Element element ) throws XPathExpressionException {
-    writer.write( "<" );
-    QName qname = event.getName();
-    String prefix = event.getName().getPrefix();
-    if( prefix != null && !prefix.isEmpty() ) {
-      writer.write( prefix );
-      writer.write( ":" );
-    }
-    writer.write( qname.getLocalPart() );
-    streamNamespaces( event );
-    streamAttributes( event, element );
-    if( isEmptyElement ) {
-      writer.write("/>");
-    } else {
-      writer.write(">");
-    }
-  }
-
-  private void processBufferedElement( Level level, UrlRewriteFilterGroupDescriptor config ) throws XPathExpressionException {
-    for( UrlRewriteFilterPathDescriptor selector : config.getSelectors() ) {
-      if( selector instanceof UrlRewriteFilterApplyDescriptor ) {
-        XPathExpression path = (XPathExpression)selector.compiledPath( XPATH_COMPILER );
-        Object node = path.evaluate( level.scopeNode, XPathConstants.NODE );
-        if( node != null ) {
-          UrlRewriteFilterApplyDescriptor apply = (UrlRewriteFilterApplyDescriptor)selector;
-          if( node instanceof Element ) {
-            Element element = (Element)node;
-            String value = element.getTextContent();
-            value = filterText( extractQName( element ), value, apply.rule() );
-            element.setTextContent( value );
-          } else if( node instanceof Text ) {
-            Text text = (Text)node;
-            String value = text.getWholeText();
-            value = filterText( extractQName( text.getParentNode() ), value, apply.rule() );
-            text.replaceWholeText( value );
-          } else if( node instanceof Attr ) {
-            Attr attr = (Attr)node;
-            String value = attr.getValue();
-            value = filterAttribute( extractQName( attr.getOwnerElement() ), extractQName( attr ), value, apply.rule() );
-            attr.setValue( value );
-          } else {
-            throw new IllegalArgumentException( RES.unexpectedSelectedNodeType( node ) );
-          }
-        }
-      } else if( selector instanceof UrlRewriteFilterDetectDescriptor ) {
-        XPathExpression path = (XPathExpression)selector.compiledPath( XPATH_COMPILER );
-        Object node = path.evaluate( level.scopeNode, XPathConstants.NODE );
-        if( node != null ) {
-          UrlRewriteFilterDetectDescriptor detect = (UrlRewriteFilterDetectDescriptor)selector;
-          String value = null;
-          if( node instanceof Element ) {
-            Element element = (Element)node;
-            value = element.getTextContent();
-          } else if( node instanceof Text ) {
-            Text text = (Text)node;
-            value = text.getWholeText();
-          } else if( node instanceof Attr ) {
-            Attr attr = (Attr)node;
-            value = attr.getValue();
-          } else {
-            throw new IllegalArgumentException( RES.unexpectedSelectedNodeType( node ) );
-          }
-          if( detect.compiledValue( REGEX_COMPILER ).matcher( value ).matches() ) {
-            processBufferedElement( level, detect );
-          }
-        }
-      } else {
-        throw new IllegalArgumentException( RES.unexpectedRewritePathSelector( selector ) );
-      }
-    }
-  }
-
-  private void processBufferedElement( Level level ) throws XPathExpressionException, IOException {
-    processBufferedElement( level, level.scopeConfig );
-    writeBufferedElement( level.node, writer );
-  }
-
-  private QName extractQName( Node node ) {
-    QName qname;
-    String localName = node.getLocalName();
-    if( localName == null ) {
-      qname = new QName( node.getNodeName() );
-    } else {
-      if ( node.getPrefix() == null ) { 
-        qname = new QName( node.getNamespaceURI(), localName );
-      } else {
-        qname = new QName( node.getNamespaceURI(), localName, node.getPrefix() );
-      }
-      
-    }
-    return qname;
-  }
-
-  private void bufferAttributes( StartElement event, Element element ) {
-    Iterator attributes = event.getAttributes();
-    while( attributes.hasNext() ) {
-      Attribute attribute = (Attribute)attributes.next();
-      bufferAttribute( element, attribute );
-    }
-  }
-
-  private Attr bufferAttribute( Element element, Attribute attribute ) {
-    QName name = attribute.getName();
-    String prefix = name.getPrefix();
-    String uri = name.getNamespaceURI();
-    Attr node;
-    if( uri == null || uri.isEmpty() ) {
-      node = document.createAttribute( name.getLocalPart() );
-      element.setAttributeNode( node );
-    } else {
-      node = document.createAttributeNS( uri, name.getLocalPart() );
-      if( prefix != null && !prefix.isEmpty() ) {
-        node.setPrefix( prefix );
-      }
-      element.setAttributeNodeNS( node );
-    }
-    node.setTextContent( attribute.getValue() );
-    return node;
-  }
-
-  private void streamNamespaces( StartElement event ) {
-    Iterator i = event.getNamespaces();
-    while( i.hasNext() ) {
-      Namespace ns = (Namespace)i.next();
-      writer.write( " xmlns" );
-      if( !ns.isDefaultNamespaceDeclaration() ) {
-        writer.write( ":" );
-        writer.write( ns.getPrefix() );
-      }
-      writer.write( "=\"" );
-      writer.write( ns.getNamespaceURI() );
-      writer.write( "\"" );
-    }
-  }
-
-  private void streamAttributes( StartElement event, Element element ) throws XPathExpressionException {
-    Iterator i = event.getAttributes();
-    while( i.hasNext() ) {
-      Attribute attribute = (Attribute)i.next();
-      streamAttribute( element, attribute );
-    }
-  }
-
-  private void streamAttribute( Element element, Attribute attribute ) throws XPathExpressionException {
-    Attr node;
-    QName name = attribute.getName();
-    String prefix = name.getPrefix();
-    String uri = name.getNamespaceURI();
-    if( uri == null || uri.isEmpty() ) {
-      node = document.createAttribute( name.getLocalPart() );
-      element.setAttributeNode( node );
-    } else {
-      node = document.createAttributeNS( uri, name.getLocalPart() );
-      if( prefix != null && !prefix.isEmpty() ) {
-        node.setPrefix( prefix );
-      }
-      element.setAttributeNodeNS( node );
-    }
-
-    String value = attribute.getValue();
-    Level level = stack.peek();
-    if( ( level.scopeConfig ) == null || ( level.scopeConfig.getSelectors().isEmpty() ) ) {
-      value = filterAttribute( null, attribute.getName(), value, null );
-      node.setValue( value );
-    } else {
-      UrlRewriteFilterPathDescriptor path = pickFirstMatchingPath( level );
-      if( path instanceof UrlRewriteFilterApplyDescriptor ) {
-        String rule = ((UrlRewriteFilterApplyDescriptor)path).rule();
-        value = filterAttribute( null, attribute.getName(), value, rule );
-        node.setValue( value );
-      }
-    }
-
-    //dump( document );
-
-    if( prefix == null || prefix.isEmpty() ) {
-      writer.write( " " );
-      writer.write( name.getLocalPart() );
-    } else {
-      writer.write( " " );
-      writer.write( prefix );
-      writer.write( ":" );
-      writer.write( name.getLocalPart() );
-    }
-    writer.write( "=\"" );
-    writer.write( value );
-    writer.write( "\"" );
-    element.removeAttributeNode( node );
-  }
-
-  private void processCharacters( Characters event ) throws XPathExpressionException {
-    //System.out.println( "T[" + event.isCData() + "," + event.isWhiteSpace() + "," + event.isIgnorableWhiteSpace() + "]=" + event );
-    Level level = stack.peek();
-    Node node = stack.peek().node;
-    if( event.isCData() ) {
-      node.appendChild( document.createCDATASection( event.getData() ) );
-    } else {
-      node.appendChild( document.createTextNode( event.getData() ) );
-    }
-    if( !currentlyBuffering() ) {
-      String value = event.getData();
-      if( !event.isWhiteSpace() ) {
-        if( level.scopeConfig == null || level.scopeConfig.getSelectors().isEmpty() ) {
-          value = filterText( extractQName( node ), value, null );
-        } else {
-          UrlRewriteFilterPathDescriptor path = pickFirstMatchingPath( level );
-          if( path instanceof UrlRewriteFilterApplyDescriptor ) {
-            String rule = ((UrlRewriteFilterApplyDescriptor)path).rule();
-            value = filterText( extractQName( node ), value, rule );
-          }
-        }
-      }
-      if( event.isCData() ) {
-        writer.write( "<![CDATA[" );
-        writer.write( value );
-        writer.write( "]]>" );
-      } else {
-        writer.write( StringEscapeUtils.escapeXml( value ) );
-      }  
-    }
-  }
-
-  private void processComment( Comment event ) {
-    //System.out.println( "C=" + event );
-    if( currentlyBuffering() ) {
-      stack.peek().node.appendChild( document.createComment( event.getText() ) );
-    } else {
-      writer.write( "<!--" );
-      writer.write( event.getText() );
-      writer.write( "-->" );
-    }
-  }
-
-  @Override
-  public void close() throws IOException {
-    try {
-      parser.close();
-    } catch( XMLStreamException e ) {
-      throw new IOException( e );
-    }
-    reader.close();
-    writer.close();
-    stack.clear();
-  }
-
-  protected UrlRewriteFilterPathDescriptor pickFirstMatchingPath( Level level ) {
-    UrlRewriteFilterPathDescriptor match = null;
-    if( level.scopeConfig != null ) {
-      for( UrlRewriteFilterPathDescriptor selector : level.scopeConfig.getSelectors() ) {
-        try {
-          XPathExpression path = (XPathExpression)selector.compiledPath( XPATH_COMPILER );
-          Object node = path.evaluate( level.scopeNode, XPathConstants.NODE );
-          if( node != null ) {
-            match = selector;
-            break;
-          }
-        } catch( XPathExpressionException e ) {
-          throw new IllegalArgumentException( selector.path(), e );
-        }
-      }
-    }
-    return match;
-  }
-
-  private boolean currentlyBuffering() {
-    return stack.peek().buffered;
-  }
-
-  private Level pushLevel( Level parent, XMLEvent event, Node node, Node scopeNode, UrlRewriteFilterGroupDescriptor scopeConfig ) {
-    Level level = new Level( parent, event, node, scopeNode, scopeConfig );
-    stack.push( level );
-    return level;
-  }
-
-  private static class Level {
-//    private Level parent;
-//    private XMLEvent event;
-    private Node node;
-    private UrlRewriteFilterGroupDescriptor scopeConfig;
-    private Node scopeNode;
-    private boolean buffered;
-
-    private Level( Level parent, XMLEvent event, Node node, Node scopeNode, UrlRewriteFilterGroupDescriptor scopeConfig ) {
-//      this.parent = parent;
-//      this.event = event;
-      this.node = node;
-      this.scopeConfig = scopeConfig;
-      this.scopeNode = scopeNode;
-      this.buffered = ( ( parent != null ) && parent.buffered ) ||
-                      ( ( scopeConfig != null ) && ( scopeConfig instanceof UrlRewriteFilterBufferDescriptor ) );
-    }
-  }
-
-  private static class XmlPathCompiler implements UrlRewriteFilterPathDescriptor.Compiler<XPathExpression> {
-    private static XPath XPATH = XPathFactory.newInstance().newXPath();
-    @Override
-    public XPathExpression compile( String expression, XPathExpression compiled ) {
-      try {
-        return XPATH.compile( expression );
-      } catch( XPathExpressionException e ) {
-        throw new IllegalArgumentException( e );
-      }
-    }
-  }
-
-  private static class RegexCompiler implements UrlRewriteFilterPathDescriptor.Compiler<Pattern> {
-    @Override
-    public Pattern compile( String expression, Pattern compiled ) {
-      if( compiled != null ) {
-        return compiled;
-      } else {
-        return Pattern.compile( expression );
-      }
-    }
-  }
-
-  private static final void writeBufferedElement( Node node, Writer writer ) throws IOException {
-    try {
-      Transformer t = XmlUtils.getTransformer( false, false, 0, true );
-      t.transform( new DOMSource( node ), new StreamResult( writer ) );
-    } catch( TransformerException e ) {
-      throw new IOException( e );
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlRewriteRulesDigester.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlRewriteRulesDigester.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlRewriteRulesDigester.java
deleted file mode 100644
index 640d731..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlRewriteRulesDigester.java
+++ /dev/null
@@ -1,239 +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.hadoop.gateway.filter.rewrite.impl.xml;
-
-import org.apache.commons.digester3.Digester;
-import org.apache.commons.digester3.Rule;
-import org.apache.commons.digester3.SetPropertiesRule;
-import org.apache.commons.digester3.binder.AbstractRulesModule;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterGroupDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterPathDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFlowDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteStepDescriptorFactory;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteFilterApplyDescriptorImpl;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteFilterBufferDescriptorImpl;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteFilterDetectDescriptorImpl;
-import org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteFilterScopeDescriptorImpl;
-import org.xml.sax.Attributes;
-
-public class XmlRewriteRulesDigester extends AbstractRulesModule implements XmlRewriteRulesTags {
-
-  @Override
-  protected void configure() {
-    forPattern( ROOT ).addRule( new RulesFactory() );
-    forPattern( ROOT ).addRule( new SetPropertiesRule() );
-
-    for( String name : UrlRewriteFunctionDescriptorFactory.getNames() ) {
-      forPattern( ROOT + "/" + FUNCTIONS + "/" + name ).addRule( new FunctionFactory() );
-      forPattern( ROOT + "/" + FUNCTIONS + "/" + name ).addRule( new SetPropertiesRule() );
-    }
-
-    forPattern( ROOT + "/" + RULE ).addRule( new RuleFactory() );
-    forPattern( ROOT + "/" + RULE ).addRule( new SetPropertiesRule() );
-    for( String type : UrlRewriteStepDescriptorFactory.getTypes() ) {
-      forPattern( "*/" + type ).addRule( new StepFactory() );
-      forPattern( "*/" + type ).addRule( new SetPropertiesRule() );
-    }
-
-    forPattern( ROOT + "/" + FILTER ).addRule( new FilterFactory() );
-    forPattern( ROOT + "/" + FILTER ).addRule( new SetPropertiesRule() );
-    forPattern( ROOT + "/" + FILTER + "/" + CONTENT ).addRule( new FilterContentFactory() );
-    forPattern( ROOT + "/" + FILTER + "/" + CONTENT ).addRule( new SetPropertiesRule() );
-
-    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/*/" + APPLY ).addRule( new FilterApplyFactory() );
-    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/*/" + APPLY ).addRule( new SetPropertiesRule() );
-
-    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/" + SCOPE ).addRule( new FilterScopeFactory() );
-    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/" + SCOPE ).addRule( new SetPropertiesRule() );
-
-    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/" + BUFFER ).addRule( new FilterBufferFactory() );
-    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/" + BUFFER ).addRule( new SetPropertiesRule() );
-
-    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/" + BUFFER + "/" + DETECT ).addRule( new FilterDetectFactory() );
-    forPattern( ROOT + "/" + FILTER + "/" + CONTENT + "/" + BUFFER + "/" + DETECT ).addRule( new SetPropertiesRule() );
-
-//    forPattern( "*/" + MATCH ).addRule( new MatchFactory() );
-//    forPattern( "*/" + MATCH ).addRule( new SetPropertiesRule() );
-//    forPattern( "*/" + CHECK ).addRule( new CheckFactory() );
-//    forPattern( "*/" + CHECK ).addRule( new SetPropertiesRule() );
-//    forPattern( "*/" + CONTROL ).addRule( new ControlFactory() );
-//    forPattern( "*/" + CONTROL ).addRule( new SetPropertiesRule() );
-//    forPattern( "*/" + ACTION ).addRule( new ActionFactory() );
-//    forPattern( "*/" + ACTION ).addRule( new SetPropertiesRule() );
-  }
-
-  private static class RulesFactory extends FactoryRule {
-    @Override
-    public Object create( String namespace, String name, Attributes attributes ) {
-      return UrlRewriteRulesDescriptorFactory.create();
-    }
-  }
-
-  private static class RuleFactory extends Rule {
-    @Override
-    public void begin( String namespace, String name, Attributes attributes ) throws Exception {
-      Digester digester = getDigester();
-      UrlRewriteRulesDescriptor rules = digester.peek();
-      UrlRewriteRuleDescriptor rule = rules.newRule();
-      getDigester().push( rule );
-    }
-
-    @Override
-    public void end( String namespace, String name ) throws Exception {
-      Digester digester = getDigester();
-      UrlRewriteRuleDescriptor rule = digester.pop();
-      UrlRewriteRulesDescriptor rules = digester.peek();
-      rules.addRule( rule );
-    }
-  }
-
-  private static class StepFactory extends FactoryRule {
-    @Override
-    public Object create( String namespace, String name, Attributes attributes ) {
-      UrlRewriteFlowDescriptor flow = getDigester().peek();
-      return flow.addStep( name );
-    }
-  }
-
-  private static class FunctionFactory extends FactoryRule {
-    @Override
-    public Object create( String namespace, String name, Attributes attributes ) {
-      UrlRewriteRulesDescriptor rules = getDigester().peek();
-      return rules.addFunction( name );
-    }
-  }
-
-  private static class FilterFactory extends FactoryRule {
-    @Override
-    public Object create( String namespace, String name, Attributes attributes ) {
-      UrlRewriteRulesDescriptor parent = getDigester().peek();
-      return parent.addFilter( attributes.getValue( "name" ) );
-    }
-  }
-
-  private static class FilterContentFactory extends FactoryRule {
-    @Override
-    public Object create( String namespace, String name, Attributes attributes ) {
-      UrlRewriteFilterDescriptor parent = getDigester().peek();
-      UrlRewriteFilterContentDescriptor descriptor = parent.addContent( attributes.getValue( "type" ) );
-      if (attributes.getValue( "asType" ) != null) {
-        descriptor = descriptor.asType(attributes.getValue( "asType" ));
-      }
-      return descriptor;
-    }
-  }
-
-  private static class FilterApplyFactory extends FactoryRule {
-    @Override
-    public Object create( String namespace, String name, Attributes attributes ) {
-      UrlRewriteFilterGroupDescriptor parent = getDigester().peek();
-      UrlRewriteFilterPathDescriptor child = new UrlRewriteFilterApplyDescriptorImpl();
-      child.path( attributes.getValue( "path" ) );
-      parent.addSelector( child );
-      return child;
-    }
-  }
-
-  private static class FilterScopeFactory extends FactoryRule {
-    @Override
-    public Object create( String namespace, String name, Attributes attributes ) {
-      UrlRewriteFilterGroupDescriptor parent = getDigester().peek();
-      UrlRewriteFilterPathDescriptor child = new UrlRewriteFilterScopeDescriptorImpl();
-      child.path( attributes.getValue( "path" ) );
-      parent.addSelector( child );
-      return child;
-    }
-  }
-
-  private static class FilterBufferFactory extends FactoryRule {
-    @Override
-    public Object create( String namespace, String name, Attributes attributes ) {
-      UrlRewriteFilterGroupDescriptor parent = getDigester().peek();
-      UrlRewriteFilterPathDescriptor child = new UrlRewriteFilterBufferDescriptorImpl();
-      child.path( attributes.getValue( "path" ) );
-      parent.addSelector( child );
-      return child;
-    }
-  }
-
-  private static class FilterDetectFactory extends FactoryRule {
-    @Override
-    public Object create( String namespace, String name, Attributes attributes ) {
-      UrlRewriteFilterGroupDescriptor parent = getDigester().peek();
-      UrlRewriteFilterPathDescriptor child = new UrlRewriteFilterDetectDescriptorImpl();
-      child.path( attributes.getValue( "path" ) );
-      parent.addSelector( child );
-      return child;
-    }
-  }
-
-//  private static class MatchFactory extends FactoryRule {
-//    @Override
-//    public Object create( String namespace, String name, Attributes attributes ) {
-//      UrlRewriteRuleDescriptor rule = getDigester().peek();
-//      return rule.addMatch();
-//    }
-//  }
-//
-//  private static class CheckFactory extends FactoryRule {
-//    @Override
-//    public Object create( String namespace, String name, Attributes attributes ) {
-//      UrlRewriteRuleDescriptor rule = getDigester().peek();
-//      return rule.addCheck();
-//    }
-//  }
-//
-//  private static class ActionFactory extends FactoryRule {
-//    @Override
-//    public Object create( String namespace, String name, Attributes attributes ) {
-//      UrlRewriteRuleDescriptor rule = getDigester().peek();
-//      return rule.addAction();
-//    }
-//  }
-//
-//  private static class ControlFactory extends FactoryRule {
-//    @Override
-//    public Object create( String namespace, String name, Attributes attributes ) {
-//      UrlRewriteRuleDescriptor rule = getDigester().peek();
-//      return rule.addControl();
-//    }
-//  }
-
-  private static abstract class FactoryRule extends Rule {
-
-    protected abstract Object create( String namespace, String name, Attributes attributes );
-
-    @Override
-    public void begin( String namespace, String name, Attributes attributes ) throws Exception {
-      getDigester().push( create( namespace, name, attributes ) );
-    }
-
-    @Override
-    public void end( String namespace, String name ) throws Exception {
-      getDigester().pop();
-    }
-
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlRewriteRulesTags.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlRewriteRulesTags.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlRewriteRulesTags.java
deleted file mode 100644
index 6af7301..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlRewriteRulesTags.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.hadoop.gateway.filter.rewrite.impl.xml;
-
-/**
- * <rules>
- *   <filter name="">
- *     <content type="json"> == <scope path="$"/>
- *       <apply/>
- *       <select>
- *         <choice>
- *           <apply/>
- *         </choice>
- *       </select>
- *     </content>
- *   </filter>
- * </rules>
- */
-public interface XmlRewriteRulesTags {
-
-  static final String ROOT = "rules";
-
-  static final String FUNCTIONS = "functions";
-
-  static final String RULE = "rule";
-
-//  static final String MATCH = "match";
-//  static final String CHECK = "check";
-//  static final String CONTROL = "control";
-//  static final String ACTION = "action";
-
-  static final String FILTER = "filter";
-  static final String CONTENT = "content";
-  static final String SCOPE = "scope";
-  static final String BUFFER = "buffer";
-  static final String DETECT = "detect";
-  static final String APPLY = "apply";
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteFilterReader.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteFilterReader.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteFilterReader.java
deleted file mode 100644
index f9b39e5..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteFilterReader.java
+++ /dev/null
@@ -1,82 +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.hadoop.gateway.filter.rewrite.impl.xml;
-
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.util.urltemplate.Parser;
-import org.apache.hadoop.gateway.util.urltemplate.Resolver;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import javax.xml.namespace.QName;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.stream.XMLStreamException;
-import java.io.IOException;
-import java.io.Reader;
-import java.net.URISyntaxException;
-
-import static org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriter.Direction;
-
-public class XmlUrlRewriteFilterReader extends XmlFilterReader {
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-
-  private Resolver resolver;
-  private UrlRewriter rewriter;
-  private Direction direction;
-
-  public XmlUrlRewriteFilterReader( Reader reader, UrlRewriter rewriter, Resolver resolver, Direction direction, UrlRewriteFilterContentDescriptor config )
-      throws IOException, ParserConfigurationException, XMLStreamException {
-    super( reader, config );
-    this.resolver = resolver;
-    this.rewriter = rewriter;
-    this.direction = direction;
-  }
-
-  //TODO: Need to limit which values are attempted to be filtered by the name.
-  private String filterValueString( String name, String value, String rule ) {
-    try {
-      Template input = Parser.parseLiteral( value );
-      if( input != null ) {
-        Template output = rewriter.rewrite( resolver, input, direction, rule );
-        if( output != null ) {
-          value = output.getPattern();
-        } else {
-          LOG.failedToFilterValue( value, rule );
-        }
-      } else {
-        LOG.failedToParseValueForUrlRewrite( value );
-      }
-    } catch( URISyntaxException e ) {
-      LOG.failedToParseValueForUrlRewrite( value );
-    }
-    return value;
-  }
-
-  @Override
-  protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
-    return filterValueString( attributeName.getLocalPart(), attributeValue, ruleName );
-  }
-
-  @Override
-  protected String filterText( QName elementName, String text, String ruleName ) {
-    return filterValueString( elementName.getLocalPart(), text, ruleName );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporter.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporter.java
deleted file mode 100644
index 1cc10a3..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporter.java
+++ /dev/null
@@ -1,188 +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.hadoop.gateway.filter.rewrite.impl.xml;
-
-import org.apache.commons.beanutils.BeanUtils;
-import org.apache.hadoop.gateway.filter.rewrite.api.*;
-import org.apache.hadoop.gateway.filter.rewrite.i18n.UrlRewriteMessages;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteRulesExporter;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.util.XmlUtils;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.TransformerException;
-import java.beans.BeanInfo;
-import java.beans.IntrospectionException;
-import java.beans.Introspector;
-import java.beans.PropertyDescriptor;
-import java.io.IOException;
-import java.io.Writer;
-import java.lang.reflect.InvocationTargetException;
-
-public class XmlUrlRewriteRulesExporter implements UrlRewriteRulesExporter, XmlRewriteRulesTags {
-
-  private static final UrlRewriteMessages LOG = MessagesFactory.get( UrlRewriteMessages.class );
-  
-  @Override
-  public String getFormat() {
-    return "xml";
-  }
-
-  @Override
-  public void store( UrlRewriteRulesDescriptor descriptor, Writer writer ) throws IOException {
-    try {
-      Document document = XmlUtils.createDocument();
-
-      Element root = document.createElement( ROOT );
-      document.appendChild( root );
-
-      if( !descriptor.getFunctions().isEmpty() ) {
-        Element functionsElement = document.createElement( FUNCTIONS );
-        root.appendChild( functionsElement );
-        for( UrlRewriteFunctionDescriptor function : descriptor.getFunctions() ) {
-          Element functionElement = createElement( document, function.name(), function );
-          functionsElement.appendChild( functionElement );
-        }
-      }
-
-      if( !descriptor.getRules().isEmpty() ) {
-        for( UrlRewriteRuleDescriptor rule : descriptor.getRules() ) {
-          Element ruleElement = createRule( document, rule );
-          root.appendChild( ruleElement );
-        }
-      }
-
-      if( !descriptor.getFilters().isEmpty() ) {
-        for( UrlRewriteFilterDescriptor filter : descriptor.getFilters() ) {
-          Element filterElement = createFilter( document, filter );
-          root.appendChild( filterElement );
-        }
-      }
-
-      XmlUtils.writeXml( document, writer );
-
-    } catch( ParserConfigurationException e ) {
-      throw new IOException( e );
-    } catch( TransformerException e ) {
-      throw new IOException( e );
-    } catch( InvocationTargetException e ) {
-      LOG.failedToWriteRulesDescriptor( e );
-    } catch( NoSuchMethodException e ) {
-      LOG.failedToWriteRulesDescriptor( e );
-    } catch( IntrospectionException e ) {
-      LOG.failedToWriteRulesDescriptor( e );
-    } catch( IllegalAccessException e ) {
-      LOG.failedToWriteRulesDescriptor( e );
-    }
-  }
-
-  private Element createFilter( Document document, UrlRewriteFilterDescriptor parent )
-      throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
-    Element parentElement = createElement( document, FILTER, parent );
-    for( UrlRewriteFilterContentDescriptor child: parent.getContents() ) {
-      Element childElement = createFilterContent( document, child );
-      parentElement.appendChild( childElement );
-    }
-    return parentElement;
-  }
-
-  private Element createFilterContent( Document document, UrlRewriteFilterContentDescriptor parent )
-      throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
-    Element parentElement = createElement( document, CONTENT, parent );
-    for( UrlRewriteFilterPathDescriptor child: parent.getSelectors() ) {
-      Element childElement = createFilterSelector( document, child );
-      parentElement.appendChild( childElement );
-    }
-    return parentElement;
-  }
-
-  private Element createFilterSelector( Document document, UrlRewriteFilterPathDescriptor parent )
-      throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
-    Element parentElement = createElement( document, toTagName( parent ), parent );
-    if( parent instanceof UrlRewriteFilterGroupDescriptor ) {
-      for( UrlRewriteFilterPathDescriptor child: ((UrlRewriteFilterGroupDescriptor)parent).getSelectors() ) {
-        Element childElement = createFilterSelector( document, child );
-        parentElement.appendChild( childElement );
-      }
-    }
-    return parentElement;
-  }
-
-  private Element createRule( Document document, UrlRewriteRuleDescriptor rule )
-      throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
-    Element ruleElement = createElement( document, RULE, rule );
-    for( UrlRewriteStepDescriptor step: rule.steps() ) {
-      Element childElement = createStep( document, step );
-      ruleElement.appendChild( childElement );
-    }
-    return ruleElement;
-  }
-
-  private Element createStep( Document document, UrlRewriteStepDescriptor step )
-      throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
-    Element parentElement = createElement( document, step.type(), step );
-    if( step instanceof UrlRewriteFlowDescriptor ) {
-      UrlRewriteFlowDescriptor flow = (UrlRewriteFlowDescriptor)step;
-      for( Object child: flow.steps() ) {
-        UrlRewriteStepDescriptor childStep = (UrlRewriteStepDescriptor)child;
-        Element childElement = createStep( document, childStep );
-        parentElement.appendChild( childElement );
-      }
-
-    }
-    return parentElement;
-  }
-
-  private Element createElement( Document document, String name, Object bean )
-      throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
-    Element element = document.createElement( name );
-    BeanInfo beanInfo = Introspector.getBeanInfo( bean.getClass(), Object.class );
-    for( PropertyDescriptor propInfo: beanInfo.getPropertyDescriptors() ) {
-      String propName = propInfo.getName();
-      if( propInfo.getReadMethod() != null && String.class.isAssignableFrom( propInfo.getPropertyType() ) ) {
-        String propValue = BeanUtils.getProperty( bean, propName );
-        if( propValue != null && !propValue.isEmpty() ) {
-          // Doing it the hard way to avoid having the &'s in the query string escaped at &amp;
-          Attr attr = document.createAttribute( propName );
-          attr.setValue( propValue );
-          element.setAttributeNode( attr );
-          //element.setAttribute( propName, propValue );
-        }
-      }
-    }
-    return element;
-  }
-
-  private static String toTagName( final UrlRewriteFilterPathDescriptor descriptor ) {
-    if( descriptor instanceof UrlRewriteFilterApplyDescriptor ) {
-      return APPLY;
-    } else if( descriptor instanceof UrlRewriteFilterDetectDescriptor ) {
-      return DETECT;
-    } else if( descriptor instanceof UrlRewriteFilterBufferDescriptor ) {
-      return BUFFER;
-    } else if( descriptor instanceof UrlRewriteFilterScopeDescriptor ) {
-      return SCOPE;
-    } else {
-      throw new IllegalArgumentException();
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesImporter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesImporter.java b/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesImporter.java
deleted file mode 100644
index ec3c2c2..0000000
--- a/gateway-provider-rewrite/src/main/java/org/apache/hadoop/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesImporter.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.hadoop.gateway.filter.rewrite.impl.xml;
-
-import org.apache.commons.digester3.Digester;
-import org.apache.commons.digester3.ExtendedBaseRules;
-import org.apache.commons.digester3.binder.DigesterLoader;
-import org.apache.hadoop.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
-import org.apache.hadoop.gateway.filter.rewrite.spi.UrlRewriteRulesImporter;
-import org.xml.sax.SAXException;
-
-import java.io.IOException;
-import java.io.Reader;
-
-import static org.apache.commons.digester3.binder.DigesterLoader.newLoader;
-
-public class XmlUrlRewriteRulesImporter implements UrlRewriteRulesImporter {
-
-  private static DigesterLoader loader = newLoader( new XmlRewriteRulesDigester() );
-
-  @Override
-  public String getFormat() {
-    return "xml";
-  }
-
-  @Override
-  public UrlRewriteRulesDescriptor load( Reader reader ) throws IOException {
-    Digester digester = loader.newDigester( new ExtendedBaseRules() );
-    digester.setValidating( false );
-    try {
-      UrlRewriteRulesDescriptor rules = digester.parse( reader );
-      return rules;
-    } catch( SAXException e ) {
-      throw new IOException( e );
-    }
-  }
-}


[12/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/filter/HadoopAuthFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/filter/HadoopAuthFilter.java b/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/filter/HadoopAuthFilter.java
new file mode 100755
index 0000000..03182ec
--- /dev/null
+++ b/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/filter/HadoopAuthFilter.java
@@ -0,0 +1,68 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.hadoopauth.filter;
+
+import java.util.Enumeration;
+import java.util.Properties;
+
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+
+import org.apache.knox.gateway.hadoopauth.HadoopAuthMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+
+/*
+ * see http://hadoop.apache.org/docs/current/hadoop-auth/Configuration.html
+ *
+ * CONFIG_PREFIX = "config.prefix
+ * AUTH_TYPE = "type", AUTH_TOKEN_VALIDITY = "token.validity"
+ * COOKIE_DOMAIN = "cookie.domain", COOKIE_PATH = "cookie.path"
+ * SIGNATURE_SECRET = "signature.secret
+ * TYPE = "kerberos", PRINCIPAL = TYPE + ".principal", KEYTAB = TYPE + ".keytab"
+
+ * config.prefix=hadoop.auth.config (default: null)
+ * hadoop.auth.config.signature.secret=SECRET (default: a simple random number)
+ * hadoop.auth.config.type=simple|kerberos|CLASS (default: none, would throw exception)
+ * hadoop.auth.config.token.validity=SECONDS (default: 3600 seconds)
+ * hadoop.auth.config.cookie.domain=DOMAIN(default: null)
+ * hadoop.auth.config.cookie.path=PATH (default: null)
+ * hadoop.auth.config.kerberos.principal=HTTP/localhost@LOCALHOST (default: null)
+ * hadoop.auth.config.kerberos.keytab=/etc/knox/conf/knox.service.keytab (default: null)
+ */
+
+public class HadoopAuthFilter extends 
+    org.apache.hadoop.security.authentication.server.AuthenticationFilter {
+  
+  private static HadoopAuthMessages log = MessagesFactory.get( HadoopAuthMessages.class );
+  
+  @Override
+  protected Properties getConfiguration(String configPrefix, FilterConfig filterConfig) throws ServletException {
+    Properties props = new Properties();
+    Enumeration<?> names = filterConfig.getInitParameterNames();
+    while (names.hasMoreElements()) {
+      String name = (String) names.nextElement();
+      if (name.startsWith(configPrefix)) {
+        String value = filterConfig.getInitParameter(name);
+        log.initializingHadoopAuthProperty(name, value);
+        props.put(name.substring(configPrefix.length()), value);
+      }
+    }
+    return props;
+  }
+  
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/filter/HadoopAuthPostFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/filter/HadoopAuthPostFilter.java b/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/filter/HadoopAuthPostFilter.java
new file mode 100755
index 0000000..3c0a6ae
--- /dev/null
+++ b/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/filter/HadoopAuthPostFilter.java
@@ -0,0 +1,108 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.hadoopauth.filter;
+
+import java.io.IOException;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+
+import javax.security.auth.Subject;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+import org.apache.knox.gateway.audit.api.AuditService;
+import org.apache.knox.gateway.audit.api.AuditServiceFactory;
+import org.apache.knox.gateway.audit.api.ResourceType;
+import org.apache.knox.gateway.audit.log4j.audit.AuditConstants;
+import org.apache.knox.gateway.filter.AbstractGatewayFilter;
+import org.apache.knox.gateway.hadoopauth.HadoopAuthMessages;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.audit.api.Action;
+import org.apache.knox.gateway.audit.api.ActionOutcome;
+import org.apache.knox.gateway.audit.api.Auditor;
+
+public class HadoopAuthPostFilter implements Filter {
+
+  private static HadoopAuthMessages log = MessagesFactory.get( HadoopAuthMessages.class );
+  private static AuditService auditService = AuditServiceFactory.getAuditService();
+  private static Auditor auditor = auditService.getAuditor(
+      AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
+      AuditConstants.KNOX_COMPONENT_NAME );
+
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+  }
+
+  @Override
+  public void destroy() {
+  }
+  
+  @Override
+  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+      throws IOException, ServletException {
+    HttpServletRequest httpRequest = (HttpServletRequest)request;
+    String principal = httpRequest.getRemoteUser();
+    if (principal != null) {
+        Subject subject = new Subject();
+        subject.getPrincipals().add(new PrimaryPrincipal(principal));
+        log.hadoopAuthAssertedPrincipal(principal);
+        auditService.getContext().setUsername( principal ); //KM: Audit Fix
+        String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
+        auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
+        doAs(httpRequest, response, chain, subject);
+    } 
+    else {
+      ((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN, "User not authenticated");
+    }
+  }
+
+  private void doAs(final ServletRequest request, final ServletResponse response, final FilterChain chain, Subject subject)
+      throws IOException, ServletException {
+      try {
+        Subject.doAs(
+            subject,
+            new PrivilegedExceptionAction<Object>() {
+              public Object run() throws Exception {
+                chain.doFilter(request, response);
+                return null;
+              }
+            }
+            );
+      }
+      catch (PrivilegedActionException e) {
+        Throwable t = e.getCause();
+        if (t instanceof IOException) {
+          throw (IOException) t;
+        }
+        else if (t instanceof ServletException) {
+          throw (ServletException) t;
+        }
+        else {
+          throw new ServletException(t);
+        }
+      }
+    }
+  
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-hadoopauth/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-hadoopauth/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-hadoopauth/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100755
index 7e247eb..0000000
--- a/gateway-provider-security-hadoopauth/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.hadoopauth.deploy.HadoopAuthDeploymentContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-hadoopauth/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-hadoopauth/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-hadoopauth/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100755
index 0000000..79740fc
--- /dev/null
+++ b/gateway-provider-security-hadoopauth/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.hadoopauth.deploy.HadoopAuthDeploymentContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/JWTMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/JWTMessages.java b/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/JWTMessages.java
deleted file mode 100644
index f6969c6..0000000
--- a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/JWTMessages.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.hadoop.gateway.provider.federation.jwt;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-import org.apache.hadoop.gateway.i18n.messages.StackTrace;
-
-@Messages(logger="org.apache.hadoop.gateway.provider.federation.jwt")
-public interface JWTMessages {
-  @Message( level = MessageLevel.WARN, text = "Failed to validate the audience attribute." )
-  void failedToValidateAudience();
-
-  @Message( level = MessageLevel.WARN, text = "Failed to verify the token signature." )
-  void failedToVerifyTokenSignature();
-
-  @Message( level = MessageLevel.INFO, text = "Access token has expired; a new one must be acquired." )
-  void tokenHasExpired();
-
-  @Message( level = MessageLevel.WARN, text = "Expected Bearer token is missing." )
-  void missingBearerToken();
-
-  @Message( level = MessageLevel.INFO, text = "Unable to verify token: {0}" )
-  void unableToVerifyToken(@StackTrace( level = MessageLevel.ERROR) Exception e);
-
-  @Message( level = MessageLevel.ERROR, text = "Unable to verify token: {0}" )
-  void unableToIssueToken(@StackTrace( level = MessageLevel.DEBUG) Exception e);
-
-  @Message( level = MessageLevel.DEBUG, text = "Sending redirect to: {0}" )
-  void sendRedirectToLoginURL(String loginURL);
-
-  @Message( level = MessageLevel.ERROR, text = "Required configuration element for authentication provider is missing." )
-  void missingAuthenticationProviderUrlConfiguration();
-
-  @Message( level = MessageLevel.DEBUG, text = "{0} Cookie has been found and is being processed." )
-  void cookieHasBeenFound(String cookieName);
-
-  @Message( level = MessageLevel.DEBUG, text = "Audience claim has been validated." )
-  void jwtAudienceValidated();
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/AccessTokenFederationContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/AccessTokenFederationContributor.java b/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/AccessTokenFederationContributor.java
deleted file mode 100644
index 2245336..0000000
--- a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/AccessTokenFederationContributor.java
+++ /dev/null
@@ -1,51 +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.hadoop.gateway.provider.federation.jwt.deploy;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-import java.util.List;
-
-public class AccessTokenFederationContributor extends ProviderDeploymentContributorBase {
-
-  private static final String FILTER_CLASSNAME = "org.apache.hadoop.gateway.provider.federation.jwt.filter.AccessTokenFederationFilter";
-
-  @Override
-  public String getRole() {
-    return "federation";
-  }
-
-  @Override
-  public String getName() {
-    return "AccessTokenProvider";
-  }
-
-  @Override
-  public void contributeProvider( DeploymentContext context, Provider provider ) {
-  }
-
-  @Override
-  public void contributeFilter( DeploymentContext context, Provider provider, Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
-    resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/JWTAccessTokenAssertionContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/JWTAccessTokenAssertionContributor.java b/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/JWTAccessTokenAssertionContributor.java
deleted file mode 100644
index 3920225..0000000
--- a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/JWTAccessTokenAssertionContributor.java
+++ /dev/null
@@ -1,63 +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.hadoop.gateway.provider.federation.jwt.deploy;
-
-import java.util.List;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.services.security.CryptoService;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-public class JWTAccessTokenAssertionContributor extends
-    ProviderDeploymentContributorBase {
-  private static final String ENCRYPT_ACCESS_TOKENS = "encrypt_access_tokens";
-  private static final String GATEWAY = "__gateway";
-  private static final String FILTER_CLASSNAME = "org.apache.hadoop.gateway.provider.federation.jwt.filter.JWTAccessTokenAssertionFilter";
-  private CryptoService crypto;
-
-  @Override
-  public String getRole() {
-    return "identity-assertion";
-  }
-
-  @Override
-  public String getName() {
-    return "JWTAccessTokenAsserter";
-  }
-
-  @Override
-  public void initializeContribution(DeploymentContext context) {
-    // TODO Auto-generated method stub
-    super.initializeContribution(context);
-    crypto.createAndStoreEncryptionKeyForCluster(GATEWAY, ENCRYPT_ACCESS_TOKENS);
-  }
-
-  @Override
-  public void contributeFilter(DeploymentContext context, Provider provider, Service service, 
-      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
-    resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
-  }
-  
-  public void setCryptoService(CryptoService crypto) {
-    this.crypto = crypto;
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/JWTAuthCodeAssertionContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/JWTAuthCodeAssertionContributor.java b/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/JWTAuthCodeAssertionContributor.java
deleted file mode 100644
index 72e8f1c..0000000
--- a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/JWTAuthCodeAssertionContributor.java
+++ /dev/null
@@ -1,51 +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.hadoop.gateway.provider.federation.jwt.deploy;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-import java.util.List;
-
-public class JWTAuthCodeAssertionContributor extends ProviderDeploymentContributorBase {
-
-  private static final String FILTER_CLASSNAME = "org.apache.hadoop.gateway.provider.federation.jwt.filter.JWTAuthCodeAssertionFilter";
-
-  @Override
-  public String getRole() {
-    return "identity-assertion";
-  }
-
-  @Override
-  public String getName() {
-    return "JWTAuthCodeAsserter";
-  }
-
-  @Override
-  public void contributeProvider( DeploymentContext context, Provider provider ) {
-  }
-
-  @Override
-  public void contributeFilter( DeploymentContext context, Provider provider, Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
-    resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/JWTFederationContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/JWTFederationContributor.java b/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/JWTFederationContributor.java
deleted file mode 100644
index ec70531..0000000
--- a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/JWTFederationContributor.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.hadoop.gateway.provider.federation.jwt.deploy;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-public class JWTFederationContributor extends ProviderDeploymentContributorBase {
-
-  private static final String FILTER_CLASSNAME = "org.apache.hadoop.gateway.provider.federation.jwt.filter.JWTFederationFilter";
-
-  @Override
-  public String getRole() {
-    return "federation";
-  }
-
-  @Override
-  public String getName() {
-    return "JWTProvider";
-  }
-
-  @Override
-  public void contributeProvider( DeploymentContext context, Provider provider ) {
-  }
-
-  @Override
-  public void contributeFilter( DeploymentContext context, Provider provider, Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
-    // blindly add all the provider params as filter init params
-    if (params == null) {
-      params = new ArrayList<FilterParamDescriptor>();
-    }
-    Map<String, String> providerParams = provider.getParams();
-    for(Entry<String, String> entry : providerParams.entrySet()) {
-      params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
-    }
-    resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/SSOCookieFederationContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/SSOCookieFederationContributor.java b/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/SSOCookieFederationContributor.java
deleted file mode 100644
index 2d36384..0000000
--- a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/deploy/SSOCookieFederationContributor.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.hadoop.gateway.provider.federation.jwt.deploy;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-public class SSOCookieFederationContributor extends ProviderDeploymentContributorBase {
-
-  private static final String FILTER_CLASSNAME = "org.apache.hadoop.gateway.provider.federation.jwt.filter.SSOCookieFederationFilter";
-
-  @Override
-  public String getRole() {
-    return "federation";
-  }
-
-  @Override
-  public String getName() {
-    return "SSOCookieProvider";
-  }
-
-  @Override
-  public void contributeProvider( DeploymentContext context, Provider provider ) {
-  }
-
-  @Override
-  public void contributeFilter( DeploymentContext context, Provider provider, Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
-    // blindly add all the provider params as filter init params
-    if (params == null) {
-      params = new ArrayList<FilterParamDescriptor>();
-    }
-    Map<String, String> providerParams = provider.getParams();
-    for(Entry<String, String> entry : providerParams.entrySet()) {
-      params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
-    }
-    resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/AbstractJWTFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/AbstractJWTFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/AbstractJWTFilter.java
deleted file mode 100644
index 8627b3f..0000000
--- a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/AbstractJWTFilter.java
+++ /dev/null
@@ -1,263 +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.hadoop.gateway.provider.federation.jwt.filter;
-
-import java.io.IOException;
-import java.security.Principal;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.security.interfaces.RSAPublicKey;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import javax.security.auth.Subject;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.hadoop.gateway.audit.api.Action;
-import org.apache.hadoop.gateway.audit.api.ActionOutcome;
-import org.apache.hadoop.gateway.audit.api.AuditContext;
-import org.apache.hadoop.gateway.audit.api.AuditService;
-import org.apache.hadoop.gateway.audit.api.AuditServiceFactory;
-import org.apache.hadoop.gateway.audit.api.Auditor;
-import org.apache.hadoop.gateway.audit.api.ResourceType;
-import org.apache.hadoop.gateway.audit.log4j.audit.AuditConstants;
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.provider.federation.jwt.JWTMessages;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.security.token.JWTokenAuthority;
-import org.apache.hadoop.gateway.services.security.token.TokenServiceException;
-import org.apache.hadoop.gateway.services.security.token.impl.JWTToken;
-
-/**
- *
- */
-public abstract class AbstractJWTFilter implements Filter {
-  static JWTMessages log = MessagesFactory.get( JWTMessages.class );
-  protected List<String> audiences;
-  protected JWTokenAuthority authority;
-  protected String verificationPEM = null;
-  protected RSAPublicKey publicKey = null;
-  private static AuditService auditService = AuditServiceFactory.getAuditService();
-  private static Auditor auditor = auditService.getAuditor(
-      AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
-      AuditConstants.KNOX_COMPONENT_NAME );
-
-  public abstract void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
-      throws IOException, ServletException;
-
-  /**
-   * 
-   */
-  public AbstractJWTFilter() {
-    super();
-  }
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-    ServletContext context = filterConfig.getServletContext();
-    if (context != null) {
-      GatewayServices services = (GatewayServices) context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
-      if (services != null) {
-        authority = (JWTokenAuthority) services.getService(GatewayServices.TOKEN_SERVICE);
-      }
-    }
-  }
-
-  /**
-   * @param expectedAudiences
-   * @return
-   */
-  protected List<String> parseExpectedAudiences(String expectedAudiences) {
-    ArrayList<String> audList = null;
-    // setup the list of valid audiences for token validation
-    if (expectedAudiences != null) {
-      // parse into the list
-      String[] audArray = expectedAudiences.split(",");
-      audList = new ArrayList<String>();
-      for (String a : audArray) {
-        audList.add(a);
-      }
-    }
-    return audList;
-  }
-
-  protected boolean tokenIsStillValid(JWTToken jwtToken) {
-    // if there is no expiration date then the lifecycle is tied entirely to
-    // the cookie validity - otherwise ensure that the current time is before
-    // the designated expiration time
-    Date expires = jwtToken.getExpiresDate();
-    return (expires == null || expires != null && new Date().before(expires));
-  }
-
-  /**
-   * Validate whether any of the accepted audience claims is present in the
-   * issued token claims list for audience. Override this method in subclasses
-   * in order to customize the audience validation behavior.
-   *
-   * @param jwtToken
-   *          the JWT token where the allowed audiences will be found
-   * @return true if an expected audience is present, otherwise false
-   */
-  protected boolean validateAudiences(JWTToken jwtToken) {
-    boolean valid = false;
-    
-    String[] tokenAudienceList = jwtToken.getAudienceClaims();
-    // if there were no expected audiences configured then just
-    // consider any audience acceptable
-    if (audiences == null) {
-      valid = true;
-    } else {
-      // if any of the configured audiences is found then consider it
-      // acceptable
-      if (tokenAudienceList != null) {
-        for (String aud : tokenAudienceList) {
-          if (audiences.contains(aud)) {
-            log.jwtAudienceValidated();
-            valid = true;
-            break;
-          }
-        }
-      }
-    }
-    return valid;
-  }
-
-  protected void continueWithEstablishedSecurityContext(Subject subject, final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
-    Principal principal = (Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0];
-    AuditContext context = auditService.getContext();
-    if (context != null) {
-      context.setUsername( principal.getName() );
-      String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
-      if (sourceUri != null) {
-        auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
-      }
-    }
-
-    try {
-      Subject.doAs(
-        subject,
-        new PrivilegedExceptionAction<Object>() {
-          @Override
-          public Object run() throws Exception {
-            chain.doFilter(request, response);
-            return null;
-          }
-        }
-        );
-    }
-    catch (PrivilegedActionException e) {
-      Throwable t = e.getCause();
-      if (t instanceof IOException) {
-        throw (IOException) t;
-      }
-      else if (t instanceof ServletException) {
-        throw (ServletException) t;
-      }
-      else {
-        throw new ServletException(t);
-      }
-    }
-  }
-
-  protected Subject createSubjectFromToken(JWTToken token) {
-    final String principal = token.getSubject();
-
-    @SuppressWarnings("rawtypes")
-    HashSet emptySet = new HashSet();
-    Set<Principal> principals = new HashSet<>();
-    Principal p = new PrimaryPrincipal(principal);
-    principals.add(p);
-      
-    // The newly constructed Sets check whether this Subject has been set read-only 
-    // before permitting subsequent modifications. The newly created Sets also prevent 
-    // illegal modifications by ensuring that callers have sufficient permissions.
-    //
-    // To modify the Principals Set, the caller must have AuthPermission("modifyPrincipals"). 
-    // To modify the public credential Set, the caller must have AuthPermission("modifyPublicCredentials"). 
-    // To modify the private credential Set, the caller must have AuthPermission("modifyPrivateCredentials").
-    javax.security.auth.Subject subject = new javax.security.auth.Subject(true, principals, emptySet, emptySet);
-    return subject;
-  }
-  
-  protected boolean validateToken(HttpServletRequest request, HttpServletResponse response,
-      FilterChain chain, JWTToken token)
-      throws IOException, ServletException {
-    boolean verified = false;
-    try {
-      if (publicKey == null) {
-        verified = authority.verifyToken(token);
-      }
-      else {
-        verified = authority.verifyToken(token, publicKey);
-      }
-    } catch (TokenServiceException e) {
-      log.unableToVerifyToken(e);
-    }
-    
-    if (verified) {
-      // confirm that issue matches intended target - which for this filter must be KNOXSSO
-      if (token.getIssuer().equals("KNOXSSO")) {
-        // if there is no expiration data then the lifecycle is tied entirely to
-        // the cookie validity - otherwise ensure that the current time is before
-        // the designated expiration time
-        if (tokenIsStillValid(token)) {
-          boolean audValid = validateAudiences(token);
-          if (audValid) {
-            return true;
-          }
-          else {
-            log.failedToValidateAudience();
-            handleValidationError(request, response, HttpServletResponse.SC_BAD_REQUEST, 
-                                  "Bad request: missing required token audience");
-          }
-        }
-        else {
-          log.tokenHasExpired();
-          handleValidationError(request, response, HttpServletResponse.SC_BAD_REQUEST, 
-                                "Bad request: token has expired");
-        }
-      }
-      else {
-        handleValidationError(request, response, HttpServletResponse.SC_UNAUTHORIZED, null);
-      }
-    }
-    else {
-      log.failedToVerifyTokenSignature();
-      handleValidationError(request, response, HttpServletResponse.SC_UNAUTHORIZED, null);
-    }
-
-    return false;
-  }
-  
-  protected abstract void handleValidationError(HttpServletRequest request, HttpServletResponse response, int status, 
-                                                String error) throws IOException;
-  
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/AccessTokenFederationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/AccessTokenFederationFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/AccessTokenFederationFilter.java
deleted file mode 100644
index 9a78745..0000000
--- a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/AccessTokenFederationFilter.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.hadoop.gateway.provider.federation.jwt.filter;
-
-import java.io.IOException;
-import java.security.Principal;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.text.ParseException;
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.security.auth.Subject;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.provider.federation.jwt.JWTMessages;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.security.token.JWTokenAuthority;
-import org.apache.hadoop.gateway.services.security.token.TokenServiceException;
-import org.apache.hadoop.gateway.services.security.token.impl.JWTToken;
-
-public class AccessTokenFederationFilter implements Filter {
-  private static JWTMessages log = MessagesFactory.get( JWTMessages.class );
-  private static final String BEARER = "Bearer ";
-  
-  private JWTokenAuthority authority;
-  
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-    GatewayServices services = (GatewayServices) filterConfig.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
-    authority = (JWTokenAuthority) services.getService(GatewayServices.TOKEN_SERVICE);
-  }
-
-  public void destroy() {
-  }
-
-  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
-      throws IOException, ServletException {
-    String header = ((HttpServletRequest) request).getHeader("Authorization");
-    if (header != null && header.startsWith(BEARER)) {
-      // what follows the bearer designator should be the JWT token being used to request or as an access token
-      String wireToken = header.substring(BEARER.length());
-      JWTToken token;
-      try {
-        token = JWTToken.parseToken(wireToken);
-      } catch (ParseException e) {
-        throw new ServletException("ParseException encountered while processing the JWT token: ", e);
-      }
-
-      boolean verified = false;
-      try {
-        verified = authority.verifyToken(token);
-      } catch (TokenServiceException e) {
-        log.unableToVerifyToken(e);
-      }
-      if (verified) {
-        long expires = Long.parseLong(token.getExpires());
-        if (expires > System.currentTimeMillis()) {
-          if (((HttpServletRequest) request).getRequestURL().indexOf(token.getAudience().toLowerCase()) != -1) {
-            Subject subject = createSubjectFromToken(token);
-            continueWithEstablishedSecurityContext(subject, (HttpServletRequest)request, (HttpServletResponse)response, chain);
-          }
-          else {
-            log.failedToValidateAudience();
-            sendUnauthorized(response);
-            return; // break the chain
-          }
-        }
-        else {
-          log.tokenHasExpired();
-          sendUnauthorized(response);
-          return; // break the chain
-        }
-      }
-      else {
-        log.failedToVerifyTokenSignature();
-        sendUnauthorized(response);
-        return; // break the chain
-      }
-    }
-    else {
-      log.missingBearerToken();
-      sendUnauthorized(response);
-      return; // break the chain
-    }
-  }
-
-  private void sendUnauthorized(ServletResponse response) throws IOException {
-    ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
-    return;
-  }
-  
-  private void continueWithEstablishedSecurityContext(Subject subject, final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException {
-    try {
-      Subject.doAs(
-        subject,
-        new PrivilegedExceptionAction<Object>() {
-          @Override
-          public Object run() throws Exception {
-            chain.doFilter(request, response);
-            return null;
-          }
-        }
-        );
-    }
-    catch (PrivilegedActionException e) {
-      Throwable t = e.getCause();
-      if (t instanceof IOException) {
-        throw (IOException) t;
-      }
-      else if (t instanceof ServletException) {
-        throw (ServletException) t;
-      }
-      else {
-        throw new ServletException(t);
-      }
-    }
-  }
-  
-  private Subject createSubjectFromToken(JWTToken token) {
-    final String principal = token.getPrincipal();
-
-    HashSet emptySet = new HashSet();
-    Set<Principal> principals = new HashSet<>();
-    Principal p = new PrimaryPrincipal(principal);
-    principals.add(p);
-    
-//        The newly constructed Sets check whether this Subject has been set read-only 
-//        before permitting subsequent modifications. The newly created Sets also prevent 
-//        illegal modifications by ensuring that callers have sufficient permissions.
-//
-//        To modify the Principals Set, the caller must have AuthPermission("modifyPrincipals"). 
-//        To modify the public credential Set, the caller must have AuthPermission("modifyPublicCredentials"). 
-//        To modify the private credential Set, the caller must have AuthPermission("modifyPrivateCredentials").
-    javax.security.auth.Subject subject = new javax.security.auth.Subject(true, principals, emptySet, emptySet);
-    return subject;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/JWTAccessTokenAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/JWTAccessTokenAssertionFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/JWTAccessTokenAssertionFilter.java
deleted file mode 100644
index f8d9a02..0000000
--- a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/JWTAccessTokenAssertionFilter.java
+++ /dev/null
@@ -1,164 +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.hadoop.gateway.provider.federation.jwt.filter;
-
-import java.io.IOException;
-import java.security.AccessController;
-import java.security.Principal;
-import java.text.ParseException;
-import java.util.HashMap;
-
-import javax.security.auth.Subject;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.hadoop.gateway.filter.security.AbstractIdentityAssertionFilter;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.provider.federation.jwt.JWTMessages;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-import org.apache.hadoop.gateway.services.security.token.JWTokenAuthority;
-import org.apache.hadoop.gateway.services.security.token.TokenServiceException;
-import org.apache.hadoop.gateway.services.security.token.impl.JWTToken;
-import org.apache.hadoop.gateway.util.JsonUtils;
-
-public class JWTAccessTokenAssertionFilter extends AbstractIdentityAssertionFilter {
-  private static final String SVC_URL = "svc";
-  private static final String EXPIRES_IN = "expires_in";
-  private static final String TOKEN_TYPE = "token_type";
-  private static final String ACCESS_TOKEN = "access_token";
-  private static final String BEARER = "Bearer ";
-  private static JWTMessages log = MessagesFactory.get( JWTMessages.class );
-  private long validity;
-  private JWTokenAuthority authority = null;
-  private ServiceRegistry sr;
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-    super.init(filterConfig);
-    String validityStr = filterConfig.getInitParameter("validity");
-    if (validityStr == null) {
-      validityStr = "3600"; // 1 hr. in secs
-    }
-    validity = Long.parseLong(validityStr);
-
-    GatewayServices services = (GatewayServices) filterConfig.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
-    authority = (JWTokenAuthority) services.getService(GatewayServices.TOKEN_SERVICE);
-    sr = (ServiceRegistry) services.getService(GatewayServices.SERVICE_REGISTRY_SERVICE);
-  }
-  
-  @Override
-  public void doFilter(ServletRequest request, ServletResponse response,
-      FilterChain chain) throws IOException, ServletException {
-    String jsonResponse = null;
-    
-    String header = ((HttpServletRequest) request).getHeader("Authorization");
-    if (header != null && header.startsWith(BEARER)) {
-      // what follows the bearer designator should be the JWT token being used to request or as an access token
-      String wireToken = header.substring(BEARER.length());
-      JWTToken token;
-      try {
-        token = JWTToken.parseToken(wireToken);
-      } catch (ParseException e) {
-        throw new ServletException("ParseException encountered while processing the JWT token: ", e);
-      }
-      // ensure that there is a valid jwt token available and that there isn't a misconfiguration of filters
-      if (token != null) {
-        try {
-          authority.verifyToken(token);
-        }
-        catch (TokenServiceException e) {
-          log.unableToVerifyToken(e);
-        }
-      }
-      else {
-        throw new ServletException("Expected JWT Token not provided as Bearer token");
-      }
-      
-      // authorization of the user for the requested service (and resource?) should have been done by
-      // the JWTFederationFilter - once we get here we can assume that it is authorized and we just need
-      // to assert the identity via an access token
-
-      Subject subject = Subject.getSubject(AccessController.getContext());
-      String principalName = getPrincipalName(subject);
-      principalName = mapper.mapUserPrincipal(principalName);
-      
-      // calculate expiration timestamp: validity * 1000 + currentTimeInMillis
-      long expires = System.currentTimeMillis() + validity * 1000;
-      
-      String serviceName = request.getParameter("service-name");
-      String clusterName = request.getParameter("cluster-name");
-      String accessToken = getAccessToken(principalName, serviceName, expires);
-      
-      String serviceURL = sr.lookupServiceURL(clusterName, serviceName);
-      
-      HashMap<String, Object> map = new HashMap<>();
-      // TODO: populate map from JWT authorization code
-      map.put(ACCESS_TOKEN, accessToken);
-      map.put(TOKEN_TYPE, BEARER);
-      map.put(EXPIRES_IN, expires);
-      
-      // TODO: this url needs to be rewritten when in gateway deployments....
-      map.put(SVC_URL, serviceURL);
-      
-      jsonResponse = JsonUtils.renderAsJsonString(map);
-      
-      response.getWriter().write(jsonResponse);
-      //KNOX-685: response.getWriter().flush();
-      return; // break filter chain
-    }
-    else {
-      // no token provided in header
-      // something is really wrong since the JWTFederationFilter should have verified its existence already
-      // TODO: may have to check cookie and url as well before sending error
-      ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
-      return; //break filter chain
-    }
-  }
-
-  private String getAccessToken(final String principalName, String serviceName, long expires) {
-    String accessToken = null;
-
-    Principal p = new Principal() {
-
-      @Override
-      public String getName() {
-        // TODO Auto-generated method stub
-        return principalName;
-      }
-    };
-    JWTToken token = null;
-    try {
-      token = authority.issueToken(p, serviceName, "RS256", expires);
-      // Coverity CID 1327961
-      if( token != null ) {
-        accessToken = token.toString();
-      }
-    } catch (TokenServiceException e) {
-      log.unableToIssueToken(e);
-    }
-
-    return accessToken;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/JWTAuthCodeAssertionFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/JWTAuthCodeAssertionFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/JWTAuthCodeAssertionFilter.java
deleted file mode 100644
index 07cdf62..0000000
--- a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/JWTAuthCodeAssertionFilter.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.hadoop.gateway.provider.federation.jwt.filter;
-
-import java.io.IOException;
-import java.security.AccessController;
-import java.util.HashMap;
-
-import javax.security.auth.Subject;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-
-import org.apache.hadoop.gateway.filter.security.AbstractIdentityAssertionFilter;
-import org.apache.hadoop.gateway.services.GatewayServices;
-import org.apache.hadoop.gateway.services.registry.ServiceRegistry;
-import org.apache.hadoop.gateway.services.security.token.JWTokenAuthority;
-import org.apache.hadoop.gateway.services.security.token.TokenServiceException;
-import org.apache.hadoop.gateway.services.security.token.impl.JWTToken;
-import org.apache.hadoop.gateway.util.JsonUtils;
-
-public class JWTAuthCodeAssertionFilter extends AbstractIdentityAssertionFilter {
-  private static final String BEARER = "Bearer ";
-  
-  private JWTokenAuthority authority = null;
-
-  private ServiceRegistry sr;
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-    super.init(filterConfig);
-    String validityStr = filterConfig.getInitParameter("validity");
-    if (validityStr == null) {
-      validityStr = "3600"; // 1 hr. in secs
-    }
-//    validity = Long.parseLong(validityStr);
-
-    GatewayServices services = (GatewayServices) filterConfig.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
-    authority = (JWTokenAuthority) services.getService(GatewayServices.TOKEN_SERVICE);
-    sr = (ServiceRegistry) services.getService(GatewayServices.SERVICE_REGISTRY_SERVICE);
-  }
-  
-  @Override
-  public void doFilter(ServletRequest request, ServletResponse response,
-      FilterChain chain) throws IOException, ServletException {
-
-      Subject subject = Subject.getSubject(AccessController.getContext());
-      String principalName = getPrincipalName(subject);
-      principalName = mapper.mapUserPrincipal(principalName);
-      JWTToken authCode;
-      try {
-        authCode = authority.issueToken(subject, "RS256");
-        // get the url for the token service
-        String url = null; 
-        if (sr != null) {
-          url = sr.lookupServiceURL("token", "TGS");
-        }
-        
-        HashMap<String, Object> map = new HashMap<>();
-        // TODO: populate map from JWT authorization code
-        // Coverity CID 1327960
-        if( authCode != null ) {
-          map.put( "iss", authCode.getIssuer() );
-          map.put( "sub", authCode.getPrincipal() );
-          map.put( "aud", authCode.getAudience() );
-          map.put( "exp", authCode.getExpires() );
-          map.put( "code", authCode.toString() );
-        }
-        if (url != null) {
-          map.put("tke", url);
-        }
-        
-        String jsonResponse = JsonUtils.renderAsJsonString(map);
-        
-        response.getWriter().write(jsonResponse);
-        //KNOX-685: response.getWriter().flush();
-      } catch (TokenServiceException e) {
-        // TODO Auto-generated catch block
-        e.printStackTrace();
-      }
-      return; // break filter chain
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/JWTFederationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/JWTFederationFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/JWTFederationFilter.java
deleted file mode 100644
index 2cbccf6..0000000
--- a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/JWTFederationFilter.java
+++ /dev/null
@@ -1,109 +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.hadoop.gateway.provider.federation.jwt.filter;
-
-import org.apache.hadoop.gateway.services.security.token.impl.JWTToken;
-import org.apache.hadoop.gateway.util.CertificateUtils;
-
-import javax.security.auth.Subject;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import java.io.IOException;
-import java.text.ParseException;
-
-public class JWTFederationFilter extends AbstractJWTFilter {
-
-  public static final String KNOX_TOKEN_AUDIENCES = "knox.token.audiences";
-  public static final String TOKEN_VERIFICATION_PEM = "knox.token.verification.pem";
-  private static final String KNOX_TOKEN_QUERY_PARAM_NAME = "knox.token.query.param.name";
-  private static final String BEARER = "Bearer ";
-  private String paramName = "knoxtoken";
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-      super.init(filterConfig);
-
-    // expected audiences or null
-    String expectedAudiences = filterConfig.getInitParameter(KNOX_TOKEN_AUDIENCES);
-    if (expectedAudiences != null) {
-      audiences = parseExpectedAudiences(expectedAudiences);
-    }
-
-    // query param name for finding the provided knoxtoken
-    String queryParamName = filterConfig.getInitParameter(KNOX_TOKEN_QUERY_PARAM_NAME);
-    if (queryParamName != null) {
-      paramName = queryParamName;
-    }
-
-    // token verification pem
-    String verificationPEM = filterConfig.getInitParameter(TOKEN_VERIFICATION_PEM);
-    // setup the public key of the token issuer for verification
-    if (verificationPEM != null) {
-      publicKey = CertificateUtils.parseRSAPublicKey(verificationPEM);
-    }
-  }
-
-  public void destroy() {
-  }
-
-  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
-      throws IOException, ServletException {
-    String header = ((HttpServletRequest) request).getHeader("Authorization");
-    String wireToken = null;
-    if (header != null && header.startsWith(BEARER)) {
-      // what follows the bearer designator should be the JWT token being used to request or as an access token
-      wireToken = header.substring(BEARER.length());
-    }
-    else {
-      // check for query param
-      wireToken = ((HttpServletRequest) request).getParameter(paramName);
-    }
-    
-    if (wireToken != null) {
-      try {
-        JWTToken token = new JWTToken(wireToken);
-        if (validateToken((HttpServletRequest)request, (HttpServletResponse)response, chain, token)) {
-          Subject subject = createSubjectFromToken(token);
-          continueWithEstablishedSecurityContext(subject, (HttpServletRequest)request, (HttpServletResponse)response, chain);
-        }
-      } catch (ParseException ex) {
-        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
-      }
-    }
-    else {
-      // no token provided in header
-      ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
-    }
-  }
-
-  protected void handleValidationError(HttpServletRequest request, HttpServletResponse response, int status,
-                                       String error) throws IOException {
-    if (error != null) {
-      response.sendError(status, error);   
-    }
-    else {
-      response.sendError(status);
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/SSOCookieFederationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/SSOCookieFederationFilter.java b/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/SSOCookieFederationFilter.java
deleted file mode 100644
index 2e37c76..0000000
--- a/gateway-provider-security-jwt/src/main/java/org/apache/hadoop/gateway/provider/federation/jwt/filter/SSOCookieFederationFilter.java
+++ /dev/null
@@ -1,168 +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.hadoop.gateway.provider.federation.jwt.filter;
-
-import java.io.IOException;
-import java.text.ParseException;
-
-import javax.security.auth.Subject;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.provider.federation.jwt.JWTMessages;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.apache.hadoop.gateway.services.security.token.impl.JWTToken;
-import org.apache.hadoop.gateway.util.CertificateUtils;
-
-public class SSOCookieFederationFilter extends AbstractJWTFilter {
-  public static final String SSO_COOKIE_NAME = "sso.cookie.name";
-  public static final String SSO_EXPECTED_AUDIENCES = "sso.expected.audiences";
-  public static final String SSO_AUTHENTICATION_PROVIDER_URL = "sso.authentication.provider.url";
-  public static final String SSO_VERIFICATION_PEM = "sso.token.verification.pem";
-  private static JWTMessages log = MessagesFactory.get( JWTMessages.class );
-  private static final String ORIGINAL_URL_QUERY_PARAM = "originalUrl=";
-  private static final String DEFAULT_SSO_COOKIE_NAME = "hadoop-jwt";
-
-  private String cookieName;
-  private String authenticationProviderUrl;
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-    super.init(filterConfig);
-    
-    // configured cookieName
-    cookieName = filterConfig.getInitParameter(SSO_COOKIE_NAME);
-    if (cookieName == null) {
-      cookieName = DEFAULT_SSO_COOKIE_NAME;
-    }
-
-    // expected audiences or null
-    String expectedAudiences = filterConfig.getInitParameter(SSO_EXPECTED_AUDIENCES);
-    if (expectedAudiences != null) {
-      audiences = parseExpectedAudiences(expectedAudiences);
-    }
-
-    // url to SSO authentication provider
-    authenticationProviderUrl = filterConfig.getInitParameter(SSO_AUTHENTICATION_PROVIDER_URL);
-    if (authenticationProviderUrl == null) {
-      log.missingAuthenticationProviderUrlConfiguration();
-      throw new ServletException("Required authentication provider URL is missing.");
-    }
-
-    // token verification pem
-    String verificationPEM = filterConfig.getInitParameter(SSO_VERIFICATION_PEM);
-    // setup the public key of the token issuer for verification
-    if (verificationPEM != null) {
-      publicKey = CertificateUtils.parseRSAPublicKey(verificationPEM);
-    }
-  }
-
-  public void destroy() {
-  }
-
-  @Override
-  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
-      throws IOException, ServletException {
-    String wireToken = null;
-    HttpServletRequest req = (HttpServletRequest) request;
-
-    String loginURL = constructLoginURL(req);
-    wireToken = getJWTFromCookie(req);
-    if (wireToken == null) {
-      if (req.getMethod().equals("OPTIONS")) {
-        // CORS preflight requests to determine allowed origins and related config
-        // must be able to continue without being redirected
-        Subject sub = new Subject();
-        sub.getPrincipals().add(new PrimaryPrincipal("anonymous"));
-        continueWithEstablishedSecurityContext(sub, req, (HttpServletResponse) response, chain);
-      }
-      log.sendRedirectToLoginURL(loginURL);
-      ((HttpServletResponse) response).sendRedirect(loginURL);
-    }
-    else {
-      try {
-        JWTToken token = new JWTToken(wireToken);
-        if (validateToken((HttpServletRequest)request, (HttpServletResponse)response, chain, token)) {
-          Subject subject = createSubjectFromToken(token);
-          continueWithEstablishedSecurityContext(subject, (HttpServletRequest)request, (HttpServletResponse)response, chain);
-        }
-      } catch (ParseException ex) {
-        ((HttpServletResponse) response).sendRedirect(loginURL);
-      }
-    }
-  }
-
-  protected void handleValidationError(HttpServletRequest request, HttpServletResponse response, int status,
-                                       String error) throws IOException {
-    String loginURL = constructLoginURL(request);
-    response.sendRedirect(loginURL);
-  }
-
-  /**
-   * Encapsulate the acquisition of the JWT token from HTTP cookies within the
-   * request.
-   *
-   * @param req servlet request to get the JWT token from
-   * @return serialized JWT token
-   */
-  protected String getJWTFromCookie(HttpServletRequest req) {
-    String serializedJWT = null;
-    Cookie[] cookies = req.getCookies();
-    if (cookies != null) {
-      for (Cookie cookie : cookies) {
-        if (cookieName.equals(cookie.getName())) {
-          log.cookieHasBeenFound(cookieName);
-          serializedJWT = cookie.getValue();
-          break;
-        }
-      }
-    }
-    return serializedJWT;
-  }
-
-  /**
-   * Create the URL to be used for authentication of the user in the absence of
-   * a JWT token within the incoming request.
-   *
-   * @param request for getting the original request URL
-   * @return url to use as login url for redirect
-   */
-  protected String constructLoginURL(HttpServletRequest request) {
-    String delimiter = "?";
-    if (authenticationProviderUrl.contains("?")) {
-      delimiter = "&";
-    }
-    String loginURL = authenticationProviderUrl + delimiter
-        + ORIGINAL_URL_QUERY_PARAM
-        + request.getRequestURL().append(getOriginalQueryString(request));
-    return loginURL;
-  }
-
-  private String getOriginalQueryString(HttpServletRequest request) {
-    String originalQueryString = request.getQueryString();
-    return (originalQueryString == null) ? "" : "?" + originalQueryString;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/JWTMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/JWTMessages.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/JWTMessages.java
new file mode 100644
index 0000000..39df1bb
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/JWTMessages.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.knox.gateway.provider.federation.jwt;
+
+import org.apache.knox.gateway.i18n.messages.Message;
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.Messages;
+import org.apache.knox.gateway.i18n.messages.StackTrace;
+
+@Messages(logger="org.apache.hadoop.gateway.provider.federation.jwt")
+public interface JWTMessages {
+  @Message( level = MessageLevel.WARN, text = "Failed to validate the audience attribute." )
+  void failedToValidateAudience();
+
+  @Message( level = MessageLevel.WARN, text = "Failed to verify the token signature." )
+  void failedToVerifyTokenSignature();
+
+  @Message( level = MessageLevel.INFO, text = "Access token has expired; a new one must be acquired." )
+  void tokenHasExpired();
+
+  @Message( level = MessageLevel.WARN, text = "Expected Bearer token is missing." )
+  void missingBearerToken();
+
+  @Message( level = MessageLevel.INFO, text = "Unable to verify token: {0}" )
+  void unableToVerifyToken(@StackTrace( level = MessageLevel.ERROR) Exception e);
+
+  @Message( level = MessageLevel.ERROR, text = "Unable to verify token: {0}" )
+  void unableToIssueToken(@StackTrace( level = MessageLevel.DEBUG) Exception e);
+
+  @Message( level = MessageLevel.DEBUG, text = "Sending redirect to: {0}" )
+  void sendRedirectToLoginURL(String loginURL);
+
+  @Message( level = MessageLevel.ERROR, text = "Required configuration element for authentication provider is missing." )
+  void missingAuthenticationProviderUrlConfiguration();
+
+  @Message( level = MessageLevel.DEBUG, text = "{0} Cookie has been found and is being processed." )
+  void cookieHasBeenFound(String cookieName);
+
+  @Message( level = MessageLevel.DEBUG, text = "Audience claim has been validated." )
+  void jwtAudienceValidated();
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/AccessTokenFederationContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/AccessTokenFederationContributor.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/AccessTokenFederationContributor.java
new file mode 100644
index 0000000..e500550
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/AccessTokenFederationContributor.java
@@ -0,0 +1,51 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.provider.federation.jwt.deploy;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+import java.util.List;
+
+public class AccessTokenFederationContributor extends ProviderDeploymentContributorBase {
+
+  private static final String FILTER_CLASSNAME = "AccessTokenFederationFilter";
+
+  @Override
+  public String getRole() {
+    return "federation";
+  }
+
+  @Override
+  public String getName() {
+    return "AccessTokenProvider";
+  }
+
+  @Override
+  public void contributeProvider( DeploymentContext context, Provider provider ) {
+  }
+
+  @Override
+  public void contributeFilter( DeploymentContext context, Provider provider, Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
+    resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTAccessTokenAssertionContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTAccessTokenAssertionContributor.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTAccessTokenAssertionContributor.java
new file mode 100644
index 0000000..92912fd
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTAccessTokenAssertionContributor.java
@@ -0,0 +1,63 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.provider.federation.jwt.deploy;
+
+import java.util.List;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.services.security.CryptoService;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+public class JWTAccessTokenAssertionContributor extends
+    ProviderDeploymentContributorBase {
+  private static final String ENCRYPT_ACCESS_TOKENS = "encrypt_access_tokens";
+  private static final String GATEWAY = "__gateway";
+  private static final String FILTER_CLASSNAME = "JWTAccessTokenAssertionFilter";
+  private CryptoService crypto;
+
+  @Override
+  public String getRole() {
+    return "identity-assertion";
+  }
+
+  @Override
+  public String getName() {
+    return "JWTAccessTokenAsserter";
+  }
+
+  @Override
+  public void initializeContribution(DeploymentContext context) {
+    // TODO Auto-generated method stub
+    super.initializeContribution(context);
+    crypto.createAndStoreEncryptionKeyForCluster(GATEWAY, ENCRYPT_ACCESS_TOKENS);
+  }
+
+  @Override
+  public void contributeFilter(DeploymentContext context, Provider provider, Service service,
+      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
+    resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
+  }
+  
+  public void setCryptoService(CryptoService crypto) {
+    this.crypto = crypto;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTAuthCodeAssertionContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTAuthCodeAssertionContributor.java b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTAuthCodeAssertionContributor.java
new file mode 100644
index 0000000..1ec8ce6
--- /dev/null
+++ b/gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/deploy/JWTAuthCodeAssertionContributor.java
@@ -0,0 +1,51 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.provider.federation.jwt.deploy;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+import java.util.List;
+
+public class JWTAuthCodeAssertionContributor extends ProviderDeploymentContributorBase {
+
+  private static final String FILTER_CLASSNAME = "JWTAuthCodeAssertionFilter";
+
+  @Override
+  public String getRole() {
+    return "identity-assertion";
+  }
+
+  @Override
+  public String getName() {
+    return "JWTAuthCodeAsserter";
+  }
+
+  @Override
+  public void contributeProvider( DeploymentContext context, Provider provider ) {
+  }
+
+  @Override
+  public void contributeFilter( DeploymentContext context, Provider provider, Service service, ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
+    resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
+  }
+}


[15/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/rewrite.xml b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/rewrite.xml
new file mode 100644
index 0000000..b5d4f50
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/rewrite.xml
@@ -0,0 +1,106 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!--
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+-->
+<rules>
+
+    <filter>
+        <role>rewrite</role>
+        <name>url-rewrite</name>
+        <class>org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletFilter</class>
+        <param><name>url.rule</name><value>{rule-name}</value></param>
+        <param><name>request.filter</name><value>{filters-name}</value></param>
+        <param><name>response.filter</name><value>{filters-name}</value></param>
+    </filter>
+
+    <!--
+    If no filter/rule specified it should attempt to filter everything like it did before.
+    -->
+
+    <filter name="WEBHDFS/request">
+        <content type="http/header">
+            <apply target="Location" rule="{rewrite-rule-name}"/>
+            <apply>...</apply>
+        </content>
+        <content type="http/cookie">
+            <apply target="hadoop.auth" rule="{rewrite-rule-name}"/>
+        </content>
+        <content type="*/json" name="{filter-impl-name}">
+            <select node="/config/property">
+                <choice source="name" pattern="YarnNodeManager ">
+                    <apply target="value[2]" rule="{rewrite-rule-name}"/>
+                    <apply target="value[3]" rule="{rewrite-rule-name}"/>
+                </choice>
+                <choice>...</choice>
+            </select>
+        </content>
+    </filter>
+
+    <!--
+    If there isn't a ContentFilter for the required type it is a failure.
+    The default ContentFilter ie type="*/*" can be present to transparently stream content.
+    The most specific content filter applies.
+
+    The most specific apply choice applies.
+    Missing rule="" uses URL pattern matching.
+    The rule="*" uses URL pattern matching.
+    The rule="-" prevents any rule being applied.
+
+    ContentParser
+    ContentParserFactory
+    ContentParserEvent
+
+    ContentFilter
+    ContentFilterFactory
+    ContentFilterAction
+    ContentFilterApply
+    ContentFilterChoice
+    ContentFilterSelect
+    ContentFilterSelectNode
+
+    ContentPath
+    ContentPathNode
+    ContentPathMatcher
+    ContentPathParser
+    -->
+
+    <rule dir="IN" name="WEBHDFS/webhdfs/namenode/root/inbound" pattern="*://*:*/**/webhdfs/{version}/?{**}">
+        <rewrite template="http://vm:50070/webhdfs/{version}/?{**}"/>
+    </rule>
+    <rule dir="IN" name="WEBHDFS/webhdfs/namenode/file/inbound" pattern="*://*:*/**/webhdfs/{version}/{path=**}?{**}">
+        <rewrite template="http://vm:50070/webhdfs/{version}/{path=**}?{**}"/>
+    </rule>
+    <rule dir="IN" name="WEBHDFS/webhdfs/datanode/inbound" pattern="*://*:*/**/webhdfs/data/{version}/{path=**}?**">
+        <decode-query/>
+        <match pattern="*://*:*/**/webhdfs/data/{version}/{path=**}?{host}&amp;{port}&amp;{**}"/>
+        <rewrite template="http://{host}:{port}/{path=**}?{**}"/>
+    </rule>
+    <rule dir="OUT" name="WEBHDFS/webhdfs/datanode/outbound" pattern="*://*:*/**?**">
+        <match pattern="*://{host}:{port}/{path=**}?{**}"/>
+        <rewrite template="{$frontend[url]}/webhdfs/data/{version}/{path=**}?{host}&amp;{port}&amp;{**}"/>
+        <encode-query/>
+    </rule>
+    <rule dir="IN" name="WEBHCAT/webhcat/request" pattern="*://*:*/**/templeton/{version}/{path=**}?{**}">
+        <rewrite template="http://vm:50111/templeton/{version}/{path=**}?{**}"/>
+    </rule>
+    <rule dir="IN" name="OOZIE/oozie/root/inbound" pattern="*://*:*/**/oozie/{**}?{**}">
+        <rewrite template="http://vm:11000/oozie/{**}?{**}"/>
+    </rule>
+    <rule dir="IN" name="OOZIE/oozie/v1/inbound" pattern="*://*:*/**/oozie/v1/{**}?{**}">
+        <rewrite template="http://vm:11000/oozie/v1/{**}?{**}"/>
+    </rule>
+
+</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest.java
new file mode 100644
index 0000000..7ac4626
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest.java
@@ -0,0 +1,1003 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.xml;
+
+import org.apache.commons.digester3.Digester;
+import org.apache.commons.digester3.ExtendedBaseRules;
+import org.apache.commons.digester3.binder.DigesterLoader;
+import org.apache.commons.io.IOUtils;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterApplyDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterBufferDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterContentDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFilterDetectDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptorFactory;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteStepFlow;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriter;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteCheckDescriptorExt;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteControlDescriptor;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptor;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptorExt;
+import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteActionDescriptorBase;
+import org.apache.hadoop.test.TestUtils;
+import org.hamcrest.Matchers;
+import org.junit.Before;
+import org.junit.Test;
+import org.xml.sax.SAXException;
+import org.xmlmatchers.namespace.SimpleNamespaceContext;
+
+import javax.xml.namespace.QName;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLStreamException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Reader;
+import java.io.StringReader;
+import java.nio.charset.Charset;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.apache.commons.digester3.binder.DigesterLoader.newLoader;
+import static org.hamcrest.CoreMatchers.hasItem;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.*;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.fail;
+import static org.xmlmatchers.XmlMatchers.hasXPath;
+import static org.xmlmatchers.transform.XmlConverters.the;
+
+public class XmlFilterReaderTest {
+
+  public static class NoopXmlFilterReader extends XmlFilterReader {
+    public NoopXmlFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException, ParserConfigurationException, XMLStreamException {
+      super( reader, config );
+    }
+
+    @Override
+    protected String filterText( QName elementName, String text, String ruleName ) {
+      return text;
+    }
+
+    @Override
+    protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
+      return attributeValue;
+    }
+  }
+
+  public static class MapXmlFilterReader extends XmlFilterReader {
+    private Map<String,String> map;
+
+    public MapXmlFilterReader( Reader reader, Map<String,String> map ) throws IOException, ParserConfigurationException, XMLStreamException {
+      super( reader, null );
+      this.map = map;
+    }
+
+    @Override
+    protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
+      return map.get( attributeValue.trim() );
+    }
+
+    @Override
+    protected String filterText( QName elementName, String text, String ruleName ) {
+      return map.get( text.trim() );
+    }
+  }
+
+  @Test
+  public void testSimple() throws IOException, ParserConfigurationException, XMLStreamException {
+    String inputXml = "<root/>";
+    StringReader inputReader = new StringReader( inputXml );
+    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
+    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+    assertThat( the( outputHtml ), hasXPath( "/root" ) );
+  }
+
+  @Test
+  public void testSimpleStreaming() throws IOException, ParserConfigurationException, XMLStreamException {
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
+
+    String inputXml = "<root/>";
+    StringReader inputReader = new StringReader( inputXml );
+    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, contentConfig );
+    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+    assertThat( the( outputHtml ), hasXPath( "/root" ) );
+  }
+
+//  @Test
+//  public void testSimpleScoped() throws IOException, ParserConfigurationException, XMLStreamException {
+//    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+//    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+//    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
+//
+//    String inputXml = "<root/>";
+//    StringReader inputReader = new StringReader( inputXml );
+//    XmlStaxFilterReader filterReader = new NoopXmlFilterReader( inputReader );
+//    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+//    assertThat( the( outputHtml ), hasXPath( "/root" ) );
+//  }
+
+  @Test
+  public void testSimpleBuffered() throws IOException, ParserConfigurationException, XMLStreamException {
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
+    UrlRewriteFilterBufferDescriptor scopeConfig = contentConfig.addBuffer( "/root" );
+
+    String input = "<root/>";
+    //System.out.println( "INPUT=" + input );
+    StringReader inputReader = new StringReader( input );
+    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, contentConfig );
+    String output = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( "OUTPUT=" + output );
+    assertThat( the( output ), hasXPath( "/root" ) );
+  }
+
+  @Test
+  public void testSimpleNested() throws IOException, ParserConfigurationException, XMLStreamException {
+    String inputXml = "<root><child1><child11/><child12/></child1><child2><child21/><child22/></child2></root>";
+    StringReader inputReader = new StringReader( inputXml );
+    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
+    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+    assertThat( the( outputHtml ), hasXPath( "/root" ) );
+    assertThat( the( outputHtml ), hasXPath( "/root/child1" ) );
+    assertThat( the( outputHtml ), hasXPath( "/root/child1/child11" ) );
+    assertThat( the( outputHtml ), hasXPath( "/root/child1/child12" ) );
+    assertThat( the( outputHtml ), hasXPath( "/root/child2" ) );
+    assertThat( the( outputHtml ), hasXPath( "/root/child2/child21" ) );
+    assertThat( the( outputHtml ), hasXPath( "/root/child2/child22" ) );
+  }
+
+  @Test
+  public void testSimpleWithNamespace() throws IOException, ParserConfigurationException, XMLStreamException {
+    String inputXml = "<ns:root xmlns:ns='http://hortonworks.com/xml/ns'></ns:root>";
+    StringReader inputReader = new StringReader( inputXml );
+    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
+    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+
+    //System.out.println( outputHtml );
+    SimpleNamespaceContext ns = new SimpleNamespaceContext();
+    ns.bind( "ns", "http://hortonworks.com/xml/ns" );
+    assertThat( the( outputHtml ), hasXPath( "/ns:root", ns ) );
+  }
+
+  @Test
+  public void testSimpleTextNode() throws IOException, ParserConfigurationException, XMLStreamException {
+    String inputXml = "<root>text</root>";
+    StringReader inputReader = new StringReader( inputXml );
+    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
+    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( "OUTPUT=" + outputXml );
+    assertThat( the( outputXml ), hasXPath( "/root/text()", equalTo( "text" ) ) );
+  }
+
+  @Test
+  public void testSimpleAttribute() throws IOException, ParserConfigurationException, XMLStreamException {
+    String inputXml = "<root name='value'/>";
+    StringReader inputReader = new StringReader( inputXml );
+    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
+    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( outputHtml );
+    assertThat( the( outputXml ), hasXPath( "/root/@name", equalTo( "value" ) ) );
+  }
+
+  @Test
+  public void testSimpleTextNodeBuffered() throws IOException, ParserConfigurationException, XMLStreamException {
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
+    UrlRewriteFilterBufferDescriptor scopeConfig = contentConfig.addBuffer( "/root" );
+
+    String inputXml = "<root>text</root>";
+    StringReader inputReader = new StringReader( inputXml );
+    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, contentConfig );
+    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( outputHtml );
+    assertThat( the( outputHtml ), hasXPath( "/root/text()", equalTo( "text" ) ) );
+  }
+
+  @Test
+  public void testSimpleAttributeBuffered() throws IOException, ParserConfigurationException, XMLStreamException {
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
+    UrlRewriteFilterBufferDescriptor scopeConfig = contentConfig.addBuffer( "/root" );
+
+    String inputXml = "<root name='value'/>";
+    StringReader inputReader = new StringReader( inputXml );
+    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, contentConfig );
+    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( outputHtml );
+    assertThat( the( outputHtml ), hasXPath( "/root/@name", equalTo( "value" ) ) );
+  }
+
+  @Test
+  public void testMappedText() throws IOException, ParserConfigurationException, XMLStreamException {
+    Map<String,String> map = new HashMap<>();
+    map.put( "input-text", "output-text" );
+    String inputXml = "<root>input-text</root>";
+    StringReader inputReader = new StringReader( inputXml );
+    XmlFilterReader filterReader = new MapXmlFilterReader( inputReader, map );
+    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( outputHtml );
+    assertThat( the( outputHtml ), hasXPath( "/root/text()", equalTo( "output-text" ) ) );
+  }
+
+  @Test
+  public void testMappedAttribute() throws IOException, ParserConfigurationException, XMLStreamException {
+    Map<String,String> map = new HashMap<>();
+    map.put( "input-text", "output-text" );
+    String inputXml = "<root attribute='input-text'/>";
+    StringReader inputReader = new StringReader( inputXml );
+    XmlFilterReader filterReader = new MapXmlFilterReader( inputReader, map );
+    String outputHtml = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( outputHtml );
+    assertThat( the( outputHtml ), hasXPath( "/root/@attribute", equalTo( "output-text" ) ) );
+  }
+
+  @Test
+  public void testCombined() throws IOException, ParserConfigurationException, XMLStreamException {
+    Map<String,String> map = new HashMap<>();
+    map.put( "attr1-input", "attr1-output" );
+    map.put( "attr2-input", "attr2-output" );
+    map.put( "attr3-input", "attr3-output" );
+    map.put( "attr4-input", "attr4-output" );
+    map.put( "attr5-input", "attr5-output" );
+    map.put( "attr6-input", "attr6-output" );
+    map.put( "attr7-input", "attr7-output" );
+    map.put( "root-input1", "root-output1" );
+    map.put( "root-input2", "root-output2" );
+    map.put( "root-input3", "root-output3" );
+    map.put( "child1-input", "child1-output" );
+    map.put( "child2-input", "child2-output" );
+
+    String inputXml =
+          "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
+            "<!-- Comment -->\n" +
+            "<ns1:root xmlns:ns1='http://hortonworks.com/xml/ns1' attr1='attr1-input' ns1:attr2='attr2-input'>\n" +
+            "  root-input1\n" +
+            "  <child1 attr3='attr3-input' ns1:attr4='attr4-input'>\n" +
+            "    child1-input\n" +
+            "  </child1>\n" +
+            "  root-input2\n" +
+            "  <ns2:child2 xmlns:ns2='http://hortonworks.com/xml/ns2' attr5='attr5-input' ns1:attr6='attr6-input' ns2:attr7='attr7-input'>\n" +
+            "    child2-input\n" +
+            "  </ns2:child2>\n" +
+            "  root-input3\n" +
+            "</ns1:root>";
+    //System.out.println( inputXml );
+
+    StringReader inputReader = new StringReader( inputXml );
+    XmlFilterReader filterReader = new MapXmlFilterReader( inputReader, map );
+    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( outputXml );
+    //System.out.flush();
+
+    SimpleNamespaceContext ns = new SimpleNamespaceContext();
+    ns.bind( "n1", "http://hortonworks.com/xml/ns1" );
+    ns.bind( "n2", "http://hortonworks.com/xml/ns2" );
+
+    assertThat( the( outputXml ), hasXPath( "/n1:root", ns ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/@attr1", ns, equalTo( "attr1-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/@n1:attr2", ns, equalTo( "attr2-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/text()[1]", ns, equalTo( "root-output1" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/text()[2]", ns, equalTo( "root-output2" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/text()[3]", ns, equalTo( "root-output3" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/child1", ns ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/child1/@attr3", ns, equalTo( "attr3-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/child1/@n1:attr4", ns, equalTo( "attr4-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/child1/text()", ns, equalTo( "child1-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2", ns ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/@attr5", ns, equalTo( "attr5-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/@n1:attr6", ns, equalTo( "attr6-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/@n2:attr7", ns, equalTo( "attr7-output" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/n1:root/n2:child2/text()", ns, equalTo( "child2-output" ) ) );
+  }
+
+  public static class XmlRewriteRulesDescriptorDigesterTest {
+
+    private static DigesterLoader loader = newLoader( new XmlRewriteRulesDigester() );
+    private static Digester digester = loader.newDigester( new ExtendedBaseRules() );
+
+    @Before
+    public void setupTest() {
+      digester.setValidating( false );
+    }
+
+    @Test
+    public void testRuleParsing() throws IOException, SAXException {
+      Reader reader = new StringReader( "<rules/>" );
+      UrlRewriteRulesDescriptor config = digester.parse( reader );
+      assertThat( config.getRules().isEmpty(), is( true ) );
+
+      reader = new StringReader( "<rules><rule></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().size(), is( 1 ) );
+      UrlRewriteRuleDescriptor rule = config.getRules().get( 0 );
+      assertThat( rule, notNullValue() );
+      assertThat( rule.name(), nullValue() );
+      assertThat( rule.pattern(), nullValue() );
+      assertThat( rule.directions(), nullValue() );
+      assertThat( rule.flow(), nullValue() );
+
+      reader = new StringReader( "<rules><rule name=\"test-name\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule, notNullValue() );
+      assertThat( rule.name(), is( "test-name" ) );
+      assertThat( rule.pattern(), nullValue() );
+      assertThat( rule.directions(), nullValue() );
+      assertThat( rule.flow(), nullValue() );
+
+      reader = new StringReader( "<rules><rule scope=\"test-scope\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule, notNullValue() );
+      assertThat( rule.name(), nullValue() );
+      assertThat( rule.scope(), is( "test-scope" ) );
+      assertThat( rule.pattern(), nullValue() );
+      assertThat( rule.directions(), nullValue() );
+      assertThat( rule.flow(), nullValue() );
+
+      reader = new StringReader( "<rules><rule name=\"test-name\" scope=\"test-scope\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule, notNullValue() );
+      assertThat( rule.name(), is( "test-name" ) );
+      assertThat( rule.scope(), is( "test-scope" ) );
+      assertThat( rule.pattern(), nullValue() );
+      assertThat( rule.directions(), nullValue() );
+      assertThat( rule.flow(), nullValue() );
+
+      reader = new StringReader( "<rules><rule pattern=\"test-pattern\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule, notNullValue() );
+      assertThat( rule.name(), nullValue() );
+      assertThat( rule.pattern(), is( "test-pattern" ) );
+      assertThat( rule.directions(), nullValue() );
+      assertThat( rule.flow(), nullValue() );
+
+      reader = new StringReader( "<rules><rule dir=\"request\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule, notNullValue() );
+      assertThat( rule.name(), nullValue() );
+      assertThat( rule.pattern(), nullValue() );
+      assertThat( rule.directions().size(), is( 1 ) );
+      assertThat( rule.directions(), Matchers.contains( UrlRewriter.Direction.IN ) );
+      assertThat( rule.flow(), nullValue() );
+
+      reader = new StringReader( "<rules><rule flow=\"all\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule, notNullValue() );
+      assertThat( rule.name(), nullValue() );
+      assertThat( rule.pattern(), nullValue() );
+      assertThat( rule.directions(), nullValue() );
+      assertThat( rule.flow(), Matchers.is( UrlRewriteStepFlow.ALL ) );
+    }
+
+    @Test
+    public void testDirectionParsing() throws IOException, SAXException {
+      Reader reader;
+      UrlRewriteRulesDescriptor config;
+
+      reader = new StringReader( "<rules><rule dir=\"request\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"Request\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"in\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"req\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"Req\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"REQ\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"inbound\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"Inbound\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"INBOUND\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"in\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"In\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"IN\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"i\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+      reader = new StringReader( "<rules><rule dir=\"I\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+
+
+      reader = new StringReader( "<rules><rule dir=\"response\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"Response\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"out\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"res\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"Res\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"RES\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"outbound\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"Outbound\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"OUTBOUND\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"out\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"Out\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"OUT\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"o\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+      reader = new StringReader( "<rules><rule dir=\"O\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.OUT ) );
+
+
+      reader = new StringReader( "<rules><rule dir=\"request,response\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), hasItem( UrlRewriter.Direction.IN ) );
+      assertThat( config.getRules().get( 0 ).directions(), hasItem( UrlRewriter.Direction.OUT ) );
+    }
+
+    @Test
+    public void testFlowParsing() throws IOException, SAXException {
+      Reader reader;
+      UrlRewriteRulesDescriptor config;
+
+      reader = new StringReader( "<rules><rule dir=\"request\"></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config.getRules().get( 0 ).directions(), contains( UrlRewriter.Direction.IN ) );
+    }
+
+    @Test
+    public void testMatchParsing() throws IOException, SAXException {
+      Reader reader;
+      UrlRewriteRulesDescriptor config;
+      UrlRewriteRuleDescriptor rule;
+      UrlRewriteMatchDescriptorExt match;
+      List<? extends UrlRewriteStepDescriptor> steps;
+
+      reader = new StringReader( "<rules><rule><match></match></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config, notNullValue() );
+      assertThat( config.getRules(), notNullValue() );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule.steps(), notNullValue() );
+      assertThat( rule.steps().size(), is( 1 ) );
+      match = (UrlRewriteMatchDescriptorExt)rule.steps().get( 0 );
+      assertThat( match, notNullValue() );
+      //assertThat( match.type(), nullValue() );
+      assertThat( match.operation(), nullValue() );
+      assertThat( match.pattern(), nullValue() );
+
+      reader = new StringReader( "<rules><rule><match type=\"test-type\" op=\"test-op\" pattern=\"test-pattern\"></match></rule></rules>" );
+      config = digester.parse( reader );
+      match = (UrlRewriteMatchDescriptorExt)config.getRules().get( 0 ).steps().get( 0 );
+      //assertThat( match.type(), is("test-type") );
+      assertThat( match.operation(), is( "test-op" ) );
+      assertThat( match.pattern(), is( "test-pattern" ) );
+
+      reader = new StringReader( "<rules><rule name=\"test\"><match><match pattern=\"test-pattern\"></match></match></rule></rules>" );
+      config = digester.parse( reader );
+      steps = ((UrlRewriteMatchDescriptor)config.getRule( "test" ).steps().get( 0 )).steps();
+      assertThat( steps, notNullValue() );
+      assertThat( steps.size(), is( 1 ) );
+      assertThat( steps.get( 0 ), notNullValue() );
+      match = (UrlRewriteMatchDescriptorExt)steps.get( 0 );
+      assertThat( match.pattern(), is( "test-pattern" ) );
+    }
+
+    @Test
+    public void testCheckParsing() throws IOException, SAXException {
+      Reader reader;
+      UrlRewriteRulesDescriptor config;
+      UrlRewriteRuleDescriptor rule;
+      List<UrlRewriteStepDescriptor> steps;
+      UrlRewriteCheckDescriptorExt step;
+
+      reader = new StringReader( "<rules><rule><check></check></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config, notNullValue() );
+      assertThat( config.getRules(), notNullValue() );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule.steps(), notNullValue() );
+      assertThat( rule.steps().size(), is( 1 ) );
+      step = (UrlRewriteCheckDescriptorExt)rule.steps().get( 0 );
+      assertThat( step, notNullValue() );
+      //assertThat( step.type(), nullValue() );
+      assertThat( step.operation(), nullValue() );
+      assertThat( step.input(), nullValue() );
+      assertThat( step.value(), nullValue() );
+
+      reader = new StringReader( "<rules><rule><check type=\"test-type\" op=\"test-op\" input=\"test-input\" value=\"test-value\"></check></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config, notNullValue() );
+      assertThat( config.getRules(), notNullValue() );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule.steps(), notNullValue() );
+      assertThat( rule.steps().size(), is( 1 ) );
+      step = (UrlRewriteCheckDescriptorExt)rule.steps().get( 0 );
+      assertThat( step, notNullValue() );
+      //assertThat( step.type(), is( "test-type" ) );
+      assertThat( step.operation(), is( "test-op" ) );
+      assertThat( step.input(), is( "test-input" ) );
+      assertThat( step.value(), is( "test-value" ) );
+    }
+
+    @Test
+    public void testActionParsing() throws IOException, SAXException {
+      Reader reader;
+      UrlRewriteRulesDescriptor config;
+      UrlRewriteRuleDescriptor rule;
+      UrlRewriteActionDescriptorBase step;
+
+      reader = new StringReader( "<rules><rule><action></action></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config, notNullValue() );
+      assertThat( config.getRules(), notNullValue() );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule.steps(), notNullValue() );
+      assertThat( rule.steps().size(), is( 1 ) );
+      step = (UrlRewriteActionDescriptorBase)rule.steps().get( 0 );
+      assertThat( step, notNullValue() );
+      //assertThat( step.type(), nullValue() );
+      assertThat( step.parameter(), nullValue() );
+
+      reader = new StringReader( "<rules><rule><action type=\"test-type\" param=\"test-param\"></action></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config, notNullValue() );
+      assertThat( config.getRules(), notNullValue() );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule.steps(), notNullValue() );
+      assertThat( rule.steps().size(), is( 1 ) );
+      step = (UrlRewriteActionDescriptorBase)rule.steps().get( 0 );
+      assertThat( step, notNullValue() );
+      //assertThat( step.type(), is( "test-type" ) );
+      assertThat( step.parameter(), is( "test-param" ) );
+    }
+
+    @Test
+    public void testControlParsing() throws IOException, SAXException {
+      Reader reader;
+      UrlRewriteRulesDescriptor config;
+      UrlRewriteRuleDescriptor rule;
+      List<UrlRewriteStepDescriptor> steps;
+
+      reader = new StringReader( "<rules><rule><control></control></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config, notNullValue() );
+      assertThat( config.getRules(), notNullValue() );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule.steps(), notNullValue() );
+      assertThat( rule.steps().size(), is( 1 ) );
+      UrlRewriteControlDescriptor step = (UrlRewriteControlDescriptor)rule.steps().get( 0 );
+      assertThat( step, notNullValue() );
+      assertThat(  step.flow(), nullValue() );
+
+      reader = new StringReader( "<rules><rule><control flow=\"or\"></control></rule></rules>" );
+      config = digester.parse( reader );
+      assertThat( config, notNullValue() );
+      assertThat( config.getRules(), notNullValue() );
+      assertThat( config.getRules().size(), is( 1 ) );
+      rule = config.getRules().get( 0 );
+      assertThat( rule.steps(), notNullValue() );
+      assertThat( rule.steps().size(), is( 1 ) );
+      step = (UrlRewriteControlDescriptor)rule.steps().get( 0 );
+      assertThat( step, notNullValue() );
+      assertThat( step.flow(), is( UrlRewriteStepFlow.OR ) );
+    }
+  }
+
+  @Test
+  public void testTagNameLetterCase() throws Exception {
+    String inputXml = "<Root/>";
+    StringReader inputReader = new StringReader( inputXml );
+
+    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
+    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
+    assertThat( the( outputXml ), hasXPath( "/Root" ) );
+  }
+
+  @Test
+  public void testXmlWithHtmlTagNames() throws Exception {
+    String inputXml = "<root><br><table name=\"table1\"/><table name=\"table2\"/></br></root>";
+    StringReader inputReader = new StringReader( inputXml );
+
+    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
+    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
+    assertThat( the( outputXml ), hasXPath( "/root/br/table[1]/@name", equalTo( "table1" ) ) );
+    assertThat( the( outputXml ), hasXPath( "/root/br/table[2]/@name", equalTo( "table2" ) ) );
+  }
+
+  @Test
+  public void testStreamedApplyForElements() throws Exception {
+    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties-elements.xml" );
+    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
+
+    //System.out.println( "INPUT=" + input );
+
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
+    UrlRewriteFilterApplyDescriptor applyConfig = contentConfig.addApply( "/properties/property/value/text()", "test-rule-2" );
+
+    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
+
+    XmlFilterReader filter = new TestXmlFilterReader( new StringReader( input ), contentConfig );
+    String output = IOUtils.toString( filter );
+
+    //System.out.println( "OUTPUT=" + output );
+
+    assertThat( the( output ), hasXPath( "/properties/property[1]/name/text()", equalTo( "test-name-1" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[1]/value/text()", equalTo( "text:test-rule-2{test-value-1}" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[2]/name/text()", equalTo( "test-name-2" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[2]/value/text()", equalTo( "text:test-rule-2{test-value-2}" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[3]/name/text()", equalTo( "test-name-3" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[3]/value/text()", equalTo( "text:test-rule-2{test-value-3}" ) ) );
+  }
+
+  @Test
+  public void testStreamedApplyForElementsConfigShortcut() throws Exception {
+    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties-elements.xml" );
+    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
+
+    //System.out.println( "INPUT=" + input );
+
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
+    UrlRewriteFilterApplyDescriptor applyConfig = contentConfig.addApply( "/properties/property/value", "test-rule-2" );
+
+    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
+
+    XmlFilterReader filter = new TestXmlFilterReader( new StringReader( input ), contentConfig );
+    String output = IOUtils.toString( filter );
+
+    //System.out.println( "OUTPUT=" + output );
+
+    assertThat( the( output ), hasXPath( "/properties/property[1]/name/text()", equalTo( "test-name-1" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[1]/value/text()", equalTo( "text:test-rule-2{test-value-1}" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[2]/name/text()", equalTo( "test-name-2" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[2]/value/text()", equalTo( "text:test-rule-2{test-value-2}" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[3]/name/text()", equalTo( "test-name-3" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[3]/value/text()", equalTo( "text:test-rule-2{test-value-3}" ) ) );
+  }
+
+  @Test
+  public void testStreamedApplyForAttributes() throws Exception {
+    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties-attributes.xml" );
+    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
+
+    //System.out.println( "INPUT=" + input );
+
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
+    UrlRewriteFilterApplyDescriptor applyConfig = contentConfig.addApply( "/properties/property/@value", "test-rule-2" );
+
+    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
+
+    XmlFilterReader filter = new TestXmlFilterReader( new StringReader( input ), contentConfig );
+    String output = IOUtils.toString( filter );
+
+    //System.out.println( "OUTPUT=" + output );
+
+    assertThat( the( output ), hasXPath( "/properties/property[1]/@name", equalTo( "test-name-1" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[1]/@value", equalTo( "attr:test-rule-2{test-value-1}" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[2]/@name", equalTo( "test-name-2" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[2]/@value", equalTo( "attr:test-rule-2{test-value-2}" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[3]/@name", equalTo( "test-name-3" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[3]/@value", equalTo( "attr:test-rule-2{test-value-3}" ) ) );
+  }
+
+  @Test
+  public void testBufferedApplyForAttributes() throws Exception {
+    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties-attributes.xml" );
+    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
+
+    //System.out.println( "INPUT=" + input );
+
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
+    UrlRewriteFilterBufferDescriptor bufferconfig = contentConfig.addBuffer( "/properties/property" );
+    UrlRewriteFilterApplyDescriptor applyConfig = bufferconfig.addApply( "@value", "test-rule-2" );
+
+    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
+
+    XmlFilterReader filter = new TestXmlFilterReader( new StringReader( input ), contentConfig );
+    String output = IOUtils.toString( filter );
+
+    //System.out.println( "OUTPUT=" + output );
+
+    assertThat( the( output ), hasXPath( "/properties/property[1]/@name", equalTo( "test-name-1" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[1]/@value", equalTo( "attr:test-rule-2{test-value-1}" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[2]/@name", equalTo( "test-name-2" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[2]/@value", equalTo( "attr:test-rule-2{test-value-2}" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[3]/@name", equalTo( "test-name-3" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[3]/@value", equalTo( "attr:test-rule-2{test-value-3}" ) ) );
+  }
+
+  @Test
+  public void testBufferedDetectApplyForElements() throws Exception {
+    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties-elements.xml" );
+    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
+
+    //System.out.println( "INPUT=" + input );
+
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
+    UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "/properties/property" );
+    UrlRewriteFilterDetectDescriptor detectConfig = bufferConfig.addDetect( "name", "test-name-2" );
+    UrlRewriteFilterApplyDescriptor applyConfig = detectConfig.addApply( "value", "test-rule-2" );
+
+    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
+
+    XmlFilterReader filter = new TestXmlFilterReader( new StringReader( input ), contentConfig );
+    String output = IOUtils.toString( filter );
+
+    //System.out.println( "OUTPUT=" + output );
+
+    assertThat( the( output ), hasXPath( "/properties/property[1]/name/text()", equalTo( "test-name-1" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[1]/value/text()", equalTo( "test-value-1" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[2]/name/text()", equalTo( "test-name-2" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[2]/value/text()", equalTo( "text:test-rule-2{test-value-2}" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[3]/name/text()", equalTo( "test-name-3" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[3]/value/text()", equalTo( "test-value-3" ) ) );
+  }
+
+  @Test
+  public void testBufferedDetectApplyForAttributes() throws Exception {
+    InputStream stream = TestUtils.getResourceStream( this.getClass(), "properties-attributes.xml" );
+    String input = IOUtils.toString( stream, Charset.forName( "UTF-8" ) );
+
+    //System.out.println( "INPUT=" + input );
+
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
+    UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "/properties/property" );
+    UrlRewriteFilterDetectDescriptor detectConfig = bufferConfig.addDetect( "@name", "test-name-2" );
+    UrlRewriteFilterApplyDescriptor applyConfig = detectConfig.addApply( "@value", "test-rule-2" );
+
+    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
+
+    XmlFilterReader filter = new TestXmlFilterReader( new StringReader( input ), contentConfig );
+    String output = IOUtils.toString( filter );
+
+    //System.out.println( "OUTPUT=" + output );
+
+    assertThat( the( output ), hasXPath( "/properties/property[1]/@name", equalTo( "test-name-1" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[1]/@value", equalTo( "test-value-1" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[2]/@name", equalTo( "test-name-2" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[2]/@value", equalTo( "attr:test-rule-2{test-value-2}" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[3]/@name", equalTo( "test-name-3" ) ) );
+    assertThat( the( output ), hasXPath( "/properties/property[3]/@value", equalTo( "test-value-3" ) ) );
+  }
+
+  @Test
+  public void testInvalidConfigShouldThrowException() throws Exception {
+    String input = "<root url='http://mock-host:42/test-input-path-1'><url>http://mock-host:42/test-input-path-2</url></root>";
+
+    //System.out.println( "INPUT=" + input );
+
+    UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
+    UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "*/xml" );
+    contentConfig.addApply( "$.url", "test-rule" );
+
+    //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
+
+    try {
+      XmlFilterReader filter = new TestXmlFilterReader( new StringReader( input ), contentConfig );
+      IOUtils.toString( filter );
+      fail( "Should have thrown an IllegalArgumentException." );
+    } catch ( IOException e ) {
+      fail( "Should have thrown an IllegalArgumentException." );
+    } catch ( IllegalArgumentException e ) {
+      if(System.getProperty("java.vendor").contains("IBM")){
+        assertThat( e.getMessage(), containsString( "Extra illegal tokens: 'url'" ) );
+      }else {
+        assertThat( e.getMessage(), containsString( "$.url" ) );
+      }
+    }
+  }
+
+  @Test
+  public void testDefaultNamespace() throws IOException, ParserConfigurationException, XMLStreamException {
+    String input = "<root xmlns=\"ns\"><node attribute=\"attr\">nodevalue</node></root>";
+    StringReader inputReader = new StringReader( input );
+    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
+    String output = IOUtils.toString( filterReader );
+    //check default namespace URI
+    assertThat( the( output ), hasXPath( "/*/namespace::*[name()='']", equalTo( "ns" ) ) );
+    assertThat( the( output ), hasXPath( "/*[namespace-uri()='ns' and name()='root']/*[namespace-uri()='ns' and name()='node']", equalTo( "nodevalue" ) ) );
+    assertThat( the( output ), hasXPath( "/*[namespace-uri()='ns' and name()='root']/*[namespace-uri()='ns' and name()='node']/@attribute", equalTo( "attr" ) ) );
+  }
+
+  @Test
+  public void testEscapeCharactersBugKnox616() throws Exception {
+    String input, output;
+    StringReader reader;
+    XmlFilterReader filter;
+
+    input = "<tag/>";
+    reader = new StringReader( input );
+    filter = new NoopXmlFilterReader( reader, null );
+    output = IOUtils.toString( filter );
+    assertThat( output, containsString( "<tag/>" ) );
+
+    input = "<tag></tag>";
+    reader = new StringReader( input );
+    filter = new NoopXmlFilterReader( reader, null );
+    output = IOUtils.toString( filter );
+    assertThat( output, containsString( "<tag/>" ) );
+
+    input = "<tag>&lt;</tag>";
+    reader = new StringReader( input );
+    filter = new NoopXmlFilterReader( reader, null );
+    output = IOUtils.toString( filter );
+    assertThat( the( output ), hasXPath( "/tag" ) );
+    assertThat( output, containsString( "<tag>&lt;</tag>" ) );
+
+    input = "<tag>&amp;</tag>";
+    reader = new StringReader( input );
+    filter = new NoopXmlFilterReader( reader, null );
+    output = IOUtils.toString( filter );
+    assertThat( output, containsString( "<tag>&amp;</tag>" ) );
+
+    input = "<document><empty/><![CDATA[<xyz>wibble</xyz>]]></document>";
+    reader = new StringReader( input );
+    filter = new NoopXmlFilterReader( reader, null );
+    output = IOUtils.toString( filter );
+    assertThat( output, containsString( "<?xml version=\"1.0\" standalone=\"no\"?><document><empty/><![CDATA[<xyz>wibble</xyz>]]></document>" ));
+
+    input="<?xml version=\"1.0\" standalone=\"no\"?>"+
+"<document>" +
+"   <noempty test=\"a\"> </noempty>"+
+"  <!-- This is the first comment -->"+
+"   <empty/>"+
+"   <![CDATA[<xyz>wibble</xyz>]]>"+
+"   <here>"+
+"      <moreempty/>"+
+"       <!-- This is the second comment -->"+
+"      <![CDATA[<xyz>noop</xyz>]]>"+
+"   </here>"+
+"</document>";
+    reader = new StringReader( input );
+    filter = new NoopXmlFilterReader( reader, null );
+    output = IOUtils.toString( filter );
+    assertThat( output, containsString( "<?xml version=\"1.0\" standalone=\"no\"?><document>   <noempty test=\"a\"> </noempty>  <!-- This is the first comment -->   <empty/>   <![CDATA[<xyz>wibble</xyz>]]>   <here>      <moreempty/>       <!-- This is the second comment -->      <![CDATA[<xyz>noop</xyz>]]>   </here></document>"));
+  }
+
+  @Test
+  public void testSpecialTextNodeBugKnox394() throws IOException, ParserConfigurationException, XMLStreamException {
+    String inputXml = "<tag>${oozieTemplateMarkup}</tag>";
+    StringReader inputReader = new StringReader( inputXml );
+    XmlFilterReader filterReader = new NoopXmlFilterReader( inputReader, null );
+    String outputXml = new String( IOUtils.toCharArray( filterReader ) );
+    //System.out.println( "OUTPUT=" + outputXml );
+    assertThat( the( outputXml ), hasXPath( "/tag/text()", equalTo( "${oozieTemplateMarkup}" ) ) );
+  }
+
+
+  private class TestXmlFilterReader extends XmlFilterReader {
+
+    protected TestXmlFilterReader( Reader reader, UrlRewriteFilterContentDescriptor contentConfig ) throws IOException, ParserConfigurationException, XMLStreamException {
+      super( reader, contentConfig );
+    }
+
+    @Override
+    protected String filterAttribute( QName elementName, QName attributeName, String attributeValue, String ruleName ) {
+      return "attr:" + ruleName + "{" + attributeValue + "}";
+    }
+
+    @Override
+    protected String filterText( QName elementName, String text, String ruleName ) {
+      return "text:" + ruleName + "{" + text + "}";
+    }
+
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporterTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporterTest.java b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporterTest.java
new file mode 100644
index 0000000..08a3314
--- /dev/null
+++ b/gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporterTest.java
@@ -0,0 +1,215 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter.rewrite.impl.xml;
+
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRuleDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptor;
+import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteRulesDescriptorFactory;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteActionDescriptor;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteActionRewriteDescriptorExt;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteCheckDescriptor;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteControlDescriptor;
+import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteMatchDescriptor;
+import org.junit.Test;
+import org.xmlmatchers.XmlMatchers;
+import org.xmlmatchers.transform.XmlConverters;
+
+import javax.xml.transform.Source;
+import java.io.IOException;
+import java.io.StringWriter;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+public class XmlUrlRewriteRulesExporterTest {
+
+  @Test
+  public void testEmptyRules() throws IOException {
+    UrlRewriteRulesDescriptor rules = UrlRewriteRulesDescriptorFactory.create();
+    StringWriter writer = new StringWriter();
+    UrlRewriteRulesDescriptorFactory.store( rules, "xml", writer );
+
+    String xml = writer.toString();
+    assertThat( XmlConverters.the( xml ), XmlMatchers.hasXPath( "/rules" ) );
+  }
+
+  @Test
+  public void testSingleNamedRule() throws IOException {
+    UrlRewriteRulesDescriptor rules = UrlRewriteRulesDescriptorFactory.create();
+    rules.addRule( "first" ).scope( "test-scope" );
+
+    StringWriter writer = new StringWriter();
+    UrlRewriteRulesDescriptorFactory.store( rules, "xml", writer );
+
+    String str = writer.toString();
+    //System.out.println( str );
+    Source xml = XmlConverters.the( str );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule)", is( "1" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@name", is( "first" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@scope", is( "test-scope" ) ) );
+  }
+
+  @Test
+  public void testMatchStep() throws Exception {
+    UrlRewriteRulesDescriptor rules = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteRuleDescriptor rule = rules.addRule( "test-rule" ).pattern("test-pattern-rule");
+    UrlRewriteMatchDescriptor match = rule.addStep( "match" );
+    match.operation("test-operation").pattern( "test-pattern-step" ).flow( "all" );
+
+    StringWriter writer = new StringWriter();
+    UrlRewriteRulesDescriptorFactory.store( rules, "xml", writer );
+
+    String str = writer.toString();
+    //System.out.println( str );
+    Source xml = XmlConverters.the( str );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule)", is( "1" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@name", is( "test-rule" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@pattern", is( "test-pattern-rule" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule/match)", is( "1" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match/@flow", is( "ALL" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match/@oper", is( "test-operation" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match/@pattern", is( "test-pattern-step" ) ) );
+  }
+
+  @Test
+  public void testControlStep() throws Exception {
+    UrlRewriteRulesDescriptor rules = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteRuleDescriptor rule = rules.addRule( "test-rule" );
+    UrlRewriteControlDescriptor control = rule.addStep( "control" );
+    control.flow( "or" );
+
+    StringWriter writer = new StringWriter();
+    UrlRewriteRulesDescriptorFactory.store( rules, "xml", writer );
+
+    String str = writer.toString();
+    //System.out.println( str );
+    Source xml = XmlConverters.the( str );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule)", is( "1" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@name", is( "test-rule" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/control" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule/control)", is( "1" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/control/@flow", is( "OR" ) ) );
+  }
+
+  @Test
+  public void testCheckStep() throws Exception {
+    UrlRewriteRulesDescriptor rules = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteRuleDescriptor rule = rules.addRule( "test-rule" );
+    UrlRewriteCheckDescriptor step = rule.addStep( "check" );
+    step.operation("test-operation").input("test-input").value("test-value").flow( "all" );
+
+    StringWriter writer = new StringWriter();
+    UrlRewriteRulesDescriptorFactory.store( rules, "xml", writer );
+
+    String str = writer.toString();
+    //System.out.println( str );
+    Source xml = XmlConverters.the( str );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule)", is( "1" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@name", is( "test-rule" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/@oper", is("test-operation") ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/@input", is("test-input") ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/@value", is("test-value") ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/@flow", is("ALL") ) );
+  }
+
+  @Test
+  public void testRewriteStep() throws Exception {
+    UrlRewriteRulesDescriptor rules = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteRuleDescriptor rule = rules.addRule( "test-rule" );
+    UrlRewriteActionRewriteDescriptorExt step = rule.addStep( "rewrite" );
+    step.operation("test-operation").parameter( "test-param" );
+
+    StringWriter writer = new StringWriter();
+    UrlRewriteRulesDescriptorFactory.store( rules, "xml", writer );
+
+    String str = writer.toString();
+    //System.out.println( str );
+    Source xml = XmlConverters.the( str );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule)", is( "1" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@name", is( "test-rule" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/rewrite" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/rewrite/@oper", is("test-operation") ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/rewrite/@template", is("test-param") ) );
+  }
+
+  @Test
+  public void testNestedStep() throws Exception {
+    UrlRewriteRulesDescriptor rules = UrlRewriteRulesDescriptorFactory.create();
+    UrlRewriteRuleDescriptor rule = rules.addRule( "test-rule" );
+
+    UrlRewriteMatchDescriptor match = rule.addStep( "match" );
+    UrlRewriteMatchDescriptor matchMatch = match.addStep( "match" );
+    UrlRewriteCheckDescriptor matchCheck = match.addStep( "check" );
+    UrlRewriteControlDescriptor matchControl = match.addStep( "control" );
+    UrlRewriteActionDescriptor matchRewrite = match.addStep( "rewrite" );
+
+    UrlRewriteCheckDescriptor check = rule.addStep( "check" );
+    UrlRewriteMatchDescriptor checkMatch = check.addStep( "match" );
+    UrlRewriteCheckDescriptor checkCheck = check.addStep( "check" );
+    UrlRewriteControlDescriptor checkControl = check.addStep( "control" );
+    UrlRewriteActionDescriptor checkRewrite = check.addStep( "rewrite" );
+
+    UrlRewriteControlDescriptor control = rule.addStep( "control" );
+    UrlRewriteMatchDescriptor controlMatch = control.addStep( "match" );
+    UrlRewriteCheckDescriptor controlCheck = control.addStep( "check" );
+    UrlRewriteControlDescriptor controlControl = control.addStep( "control" );
+    UrlRewriteActionDescriptor controlRewrite = control.addStep( "rewrite" );
+
+    UrlRewriteActionDescriptor rewrite = rule.addStep( "rewrite" );
+
+    StringWriter writer = new StringWriter();
+    UrlRewriteRulesDescriptorFactory.store( rules, "xml", writer );
+
+    String str = writer.toString();
+    //System.out.println( str );
+    Source xml = XmlConverters.the( str );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "count(/rules/rule)", is( "1" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/@name", is( "test-rule" ) ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match/match" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match/check" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match/control" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/match/rewrite" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/match" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/check" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/control" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/check/rewrite" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/control" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/control/match" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/control/check" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/control/control" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/control/rewrite" ) );
+    assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/rewrite" ) );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules-different-scope.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules-different-scope.xml b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules-different-scope.xml
deleted file mode 100644
index 6c27476..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules-different-scope.xml
+++ /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.
--->
-<rules>
-
-    <rule name="test-rule-1" dir="OUT" pattern="*://*:*/**?**">
-        <match pattern="*://{host}:{port}/{path=**}?{**}" />
-        <rewrite template="output-mock-scheme-1://output-mock-host-1:{port}/{path=**}" />
-    </rule>
-
-    <rule name="service-1/test-rule-2" dir="OUT" pattern="*://*:*/**?**">
-        <match pattern="*://{host}:{port}/{path=**}?{**}" />
-        <rewrite template="output-mock-scheme-2://output-mock-host-2:{port}/{path=**}" />
-    </rule>
-
-    <rule name="test-rule-3" dir="OUT" pattern="*://*:*/no-query">
-        <match pattern="{scheme}://{host}:{port}/{path=**}" />
-        <rewrite template="{scheme}://output-mock-host-3:{port}/{path=**}" />
-    </rule>
-
-    <rule name="service-2/test-rule-4" dir="OUT" pattern="*://*:*/no-query">
-        <match pattern="{scheme}://{host}:{port}/{path=**}" />
-        <rewrite template="{scheme}://output-mock-host-4:{port}/{path=**}" />
-    </rule>
-
-    <rule name="service-1/test-rule-5" dir="OUT" pattern="*://*:*/no-query">
-        <match pattern="{scheme}://{host}:{port}/{path=**}" />
-        <rewrite template="{scheme}://output-mock-host-5:{port}/{path=**}" />
-    </rule>
-
-    <rule name="test-rule-6" dir="IN" pattern="*://*:*/**?**">
-        <match pattern="*://{host}:{port}/{path=**}?{**}" />
-        <rewrite template="input-mock-scheme-1://input-mock-host-1:{port}/{path=**}" />
-    </rule>
-
-    <rule name="service-2/test-rule-7" dir="IN" pattern="*://*:*/**?**">
-        <match pattern="*://{host}:{port}/{path=**}?{**}" />
-        <rewrite template="input-mock-scheme-2://input-mock-host-2:{port}/{path=**}" />
-    </rule>
-
-</rules>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules.xml b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules.xml
deleted file mode 100644
index e3be214..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite-with-same-rules.xml
+++ /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.
--->
-<rules>
-
-    <rule name="test-rule-1" dir="OUT" pattern="*://*:*/**?**">
-        <match pattern="*://{host}:{port}/{path=**}?{**}" />
-        <rewrite template="output-mock-scheme-1://output-mock-host-1:{port}/{path=**}" />
-    </rule>
-
-    <rule name="test-rule-2" dir="OUT" pattern="*://*:*/**?**">
-        <match pattern="*://{host}:{port}/{path=**}?{**}" />
-        <rewrite template="output-mock-scheme-2://output-mock-host-2:{port}/{path=**}" />
-    </rule>
-
-    <rule name="test-rule-3" dir="OUT" pattern="*://*:*/no-query">
-        <match pattern="{scheme}://{host}:{port}/{path=**}" />
-        <rewrite template="{scheme}://output-mock-host-3:{port}/{path=**}" />
-    </rule>
-
-    <rule name="test-rule-4" dir="OUT" pattern="*://*:*/no-query">
-        <match pattern="{scheme}://{host}:{port}/{path=**}" />
-        <rewrite template="{scheme}://output-mock-host-4:{port}/{path=**}" />
-    </rule>
-
-</rules>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite.xml b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite.xml
deleted file mode 100644
index 84836d5..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteProcessorTest/rewrite.xml
+++ /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.
--->
-<rules>
-    <rule name="test-rule-1" url="{scheme=*}://{host=*}:{port=*}/{path=**}">
-        <rewrite param="{scheme}://{host}:{port}/test-output-path"/>
-    </rule>
-
-    <rule dir="OUT" name="test-rule-2">
-        <match pattern="*://*:*/{path=**}?{**}"/>
-        <rewrite template="test-scheme-output://test-host-output:777/test-path-output/{path}?{**}"/>
-    </rule>
-
-    <rule name="test-rule-with-complex-flow" flow="OR">
-        <match pattern="*://*:*/~/{path=**}?{**}">
-            <rewrite template="test-scheme-output://test-host-output:777/test-path-output/test-home/{path}?{**}"/>
-        </match>
-        <match pattern="*://*:*/{path=**}?{**}">
-            <rewrite template="test-scheme-output://test-host-output:42/test-path-output/{path}?{**}"/>
-        </match>
-    </rule>
-
-</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/empty.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/empty.xml b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/empty.xml
deleted file mode 100644
index 1e2850e..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/empty.xml
+++ /dev/null
@@ -1,16 +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.
--->
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-complete.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-complete.xml b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-complete.xml
deleted file mode 100644
index 54789c5..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-complete.xml
+++ /dev/null
@@ -1,33 +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.
--->
-<rules>
-    <filter name="test-filter-name-1">
-        <content type="test-content-type-1/test-content-subtype-1">
-            <apply path="test-apply-path-1" rule="test-apply-rule-1"/>
-            <scope path="test-scope-path-1">
-                <apply path="test-apply-path-2" rule="test-apply-rule-2"/>
-            </scope>
-            <buffer path="test-buffer-path-1">
-                <apply path="test-apply-path-3" rule="test-apply-rule-3"/>
-                <detect path="test-detect-path-1" value="test-detect-value-1">
-                    <apply path="test-apply-path-4" rule="test-apply-rule-4"/>
-                </detect>
-            </buffer>
-        </content>
-    </filter>
-</rules>

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-sample.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-sample.xml b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-sample.xml
deleted file mode 100644
index 60da1d3..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-sample.xml
+++ /dev/null
@@ -1,37 +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.
--->
-<rules>
-    <filter name="WEBHDFS/request">
-        <content type="http/header">
-            <apply target="Location" rule="{rewrite-rule-name}"/>
-            <apply>...</apply>
-        </content>
-        <content type="http/cookie">
-            <apply target="hadoop.auth" rule="{rewrite-rule-name}"/>
-        </content>
-        <content type="*/json" name="{filter-impl-name}">
-            <select node="/config/property">
-                <choice source="name" pattern="YarnNodeManager ">
-                    <apply target="value[2]" rule="{rewrite-rule-name}"/>
-                    <apply target="value[3]" rule="{rewrite-rule-name}"/>
-                </choice>
-                <choice>...</choice>
-            </select>
-        </content>
-    </filter>
-</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-simple.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-simple.xml b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-simple.xml
deleted file mode 100644
index f31de77..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/filter-simple.xml
+++ /dev/null
@@ -1,24 +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.
--->
-<rules>
-    <filter name="test-filter-1">
-        <content type="test-content-type-1/test-content-subtype-1">
-            <apply path="test-apply-path-1" rule="test-apply-rule-1"/>
-        </content>
-    </filter>
-</rules>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/invalid.xml
----------------------------------------------------------------------
diff --git a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/invalid.xml b/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/invalid.xml
deleted file mode 100644
index 6508f3f..0000000
--- a/gateway-provider-rewrite/src/test/resources/org/apache/hadoop/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest/invalid.xml
+++ /dev/null
@@ -1,18 +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.
--->
-</invalid>
\ No newline at end of file


[08/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/deploy/PicketlinkConf.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/deploy/PicketlinkConf.java b/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/deploy/PicketlinkConf.java
new file mode 100644
index 0000000..5b3b6e0
--- /dev/null
+++ b/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/deploy/PicketlinkConf.java
@@ -0,0 +1,194 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.picketlink.deploy;
+
+/**
+ * Provides a serializable configuration file for adding to
+ * the webapp as an XML string for picketlink.xml
+ *
+ */
+public class PicketlinkConf {
+  public static final String INDENT = "    ";
+  public static final String LT_OPEN = "<";
+  public static final String LT_CLOSE = "</";
+  public static final String GT = ">";
+  public static final String GT_CLOSE = "/>";
+  public static final String NL = "\n";
+  public static final String PICKETLINK_XMLNS = "urn:picketlink:identity-federation:config:2.1";
+  public static final String PICKETLINK_SP_XMLNS = "urn:picketlink:identity-federation:config:1.0";
+  public static final String C14N_METHOD = "http://www.w3.org/2001/10/xml-exc-c14n#";
+  public static final String KEYPROVIDER_ELEMENT = "KeyProvider";
+  public static final String KEYPROVIDER_CLASSNAME = "org.picketlink.identity.federation.core.impl.KeyStoreKeyManager";
+  public static final String AUTH_HANDLER_CLASSNAME = "org.picketlink.identity.federation.web.handlers.saml2.SAML2AuthenticationHandler";
+  public static final String ROLE_GEN_HANDLER_CLASSNAME = "org.picketlink.identity.federation.web.handlers.saml2.RolesGenerationHandler";
+  public static final String PICKETLINK_ELEMENT = "PicketLink";
+  public static final String PICKETLINKSP_ELEMENT = "PicketLinkSP";
+  public static final String HANDLERS_ELEMENT = "Handlers";
+  public static final String HANDLER_ELEMENT = "Handler";
+  public static final String OPTION_ELEMENT = "Option";
+  public static final String VAL_ALIAS_ELEMENT = "ValidatingAlias";
+  public static final String AUTH_ELEMENT = "Auth";
+
+  private String serverEnvironment = "jetty";
+  private String bindingType = "POST";
+  private String idpUsesPostingBinding = "true";
+  private String supportsSignatures = "true";
+  private String identityURL = null;
+  private String serviceURL = null;
+  private String keystoreURL = null;
+  private String keystorePass = null;
+  private String signingKeyAlias = null;
+  private String signingKeyPass = null;
+  private String validatingKeyAlias = null;
+  private String validatingKeyValue = null;
+  private String nameIDFormat = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent";
+  private String clockSkewMilis = null;
+  private String assertionSessionAttributeName = "org.picketlink.sp.assertion";
+  
+  public String getServerEnvironment() {
+    return serverEnvironment;
+  }
+  public void setServerEnvironment(String serverEnvironment) {
+    this.serverEnvironment = serverEnvironment;
+  }
+  public String getBindingType() {
+    return bindingType;
+  }
+  public void setBindingType(String bindingType) {
+    this.bindingType = bindingType;
+  }
+  public String getIdpUsesPostingBinding() {
+    return idpUsesPostingBinding;
+  }
+  public void setIdpUsesPostingBinding(String idpUsesPostingBinding) {
+    this.idpUsesPostingBinding = idpUsesPostingBinding;
+  }
+  public String getSupportsSignatures() {
+    return supportsSignatures;
+  }
+  public void setSupportsSignatures(String supportsSignatures) {
+    this.supportsSignatures = supportsSignatures;
+  }
+  public String getIdentityURL() {
+    return identityURL;
+  }
+  public void setIdentityURL(String identityURL) {
+    this.identityURL = identityURL;
+  }
+  public String getServiceURL() {
+    return serviceURL;
+  }
+  public void setServiceURL(String serviceURL) {
+    this.serviceURL = serviceURL;
+  }
+  public String getKeystoreURL() {
+    return keystoreURL;
+  }
+  public void setKeystoreURL(String keystoreURL) {
+    this.keystoreURL = keystoreURL;
+  }
+  public String getKeystorePass() {
+    return keystorePass;
+  }
+  public void setKeystorePass(String keystorePass) {
+    this.keystorePass = keystorePass;
+  }
+  public String getSigningKeyAlias() {
+    return signingKeyAlias;
+  }
+  public void setSigningKeyAlias(String signingKeyAlias) {
+    this.signingKeyAlias = signingKeyAlias;
+  }
+  public String getSigningKeyPass() {
+    return signingKeyPass;
+  }
+  public void setSigningKeyPass(String signingKeyPass) {
+    this.signingKeyPass = signingKeyPass;
+  }
+  public String getValidatingKeyAlias() {
+    return validatingKeyAlias;
+  }
+  public void setValidatingAliasKey(String validatingKeyAlias) {
+    this.validatingKeyAlias = validatingKeyAlias;
+  }
+  public String getValidatingKeyValue() {
+    return validatingKeyValue;
+  }
+  public void setValidatingAliasValue(String validatingKeyValue) {
+    this.validatingKeyValue = validatingKeyValue;
+  }
+  public String getNameIDFormat() {
+    return nameIDFormat;
+  }
+  public void setNameIDFormat(String nameIDFormat) {
+    this.nameIDFormat = nameIDFormat;
+  }
+  public String getClockSkewMilis() {
+    return clockSkewMilis;
+  }
+  public void setClockSkewMilis(String clockSkewMilis) {
+    this.clockSkewMilis = clockSkewMilis;
+  }
+  public String getAssertionSessionAttributeName() {
+    return assertionSessionAttributeName;
+  }
+  public void setAssertionSessionAttributeName(
+      String assertionSessionAttributeName) {
+    this.assertionSessionAttributeName = assertionSessionAttributeName;
+  }
+  @Override
+  public String toString() {
+    // THIS IS HORRID REPLACE WITH DOM+TRANSFORM
+    StringBuffer xml = new StringBuffer();
+    xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>").append(NL)
+    .append(LT_OPEN).append(PICKETLINK_ELEMENT).append(" xmlns=\"").append(PICKETLINK_XMLNS).append("\"" + GT).append(NL)
+      .append(INDENT).append(LT_OPEN).append(PICKETLINKSP_ELEMENT).append(" xmlns=\"").append(PICKETLINK_SP_XMLNS + "\"").append(NL)
+      .append(INDENT).append(INDENT).append("ServerEnvironment").append("=\"").append(serverEnvironment).append("\"").append(NL)
+      .append(INDENT).append(INDENT).append("BindingType").append("=\"").append(bindingType).append("\"").append(NL)
+      .append(INDENT).append(INDENT).append("IDPUsesPostBinding").append("=\"").append(idpUsesPostingBinding).append("\"").append(NL)
+      .append(INDENT).append(INDENT).append("SupportsSignatures").append("=\"").append(supportsSignatures).append("\"").append(NL)
+      .append(INDENT).append(INDENT).append("CanonicalizationMethod").append("=\"").append(C14N_METHOD).append("\"").append(GT).append(NL).append(NL)
+      .append(INDENT).append(INDENT).append(LT_OPEN).append("IdentityURL").append(GT).append(identityURL).append(LT_CLOSE).append("IdentityURL").append(GT).append(NL)
+      .append(INDENT).append(INDENT).append(LT_OPEN).append("ServiceURL").append(GT).append(serviceURL).append(LT_CLOSE).append("ServiceURL").append(GT).append(NL)
+      .append(INDENT).append(INDENT).append(LT_OPEN).append(KEYPROVIDER_ELEMENT).append(" ").append("ClassName=\"").append(KEYPROVIDER_CLASSNAME + "\"" + GT).append(NL)
+        .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(AUTH_ELEMENT).append(" Key=\"KeyStoreURL\" Value=\"").append(keystoreURL).append("\"").append(GT_CLOSE).append(NL)
+        .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(AUTH_ELEMENT).append(" Key=\"KeyStorePass\" Value=\"").append(keystorePass).append("\"").append(GT_CLOSE).append(NL)
+        .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(AUTH_ELEMENT).append(" Key=\"SigningKeyAlias\" Value=\"").append(signingKeyAlias).append("\"").append(GT_CLOSE).append(NL)
+        .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(AUTH_ELEMENT).append(" Key=\"SigningKeyPass\" Value=\"").append(signingKeyPass).append("\"").append(GT_CLOSE).append(NL)
+        .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(VAL_ALIAS_ELEMENT).append(" Key=\"").append(validatingKeyAlias).append("\" Value=\"").append(validatingKeyValue).append("\"").append(GT_CLOSE).append(NL)
+      .append(INDENT).append(INDENT).append(LT_CLOSE).append(KEYPROVIDER_ELEMENT).append(GT).append(NL)
+      .append(INDENT).append(LT_CLOSE).append(PICKETLINKSP_ELEMENT).append(GT).append(NL)
+      .append(INDENT).append(LT_OPEN).append(HANDLERS_ELEMENT).append(GT).append(NL)
+        .append(INDENT).append(INDENT).append(LT_OPEN).append(HANDLER_ELEMENT).append(" class=\"").append(AUTH_HANDLER_CLASSNAME).append("\">").append(NL)
+          .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(OPTION_ELEMENT).append(" Key=\"NAMEID_FORMAT\" Value=\"").append(nameIDFormat).append("\"").append(GT_CLOSE).append(NL)
+          .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(OPTION_ELEMENT).append(" Key=\"CLOCK_SKEW_MILIS\" Value=\"").append(clockSkewMilis).append("\"").append(GT_CLOSE).append(NL)
+          .append(INDENT).append(INDENT).append(INDENT).append(LT_OPEN).append(OPTION_ELEMENT).append(" Key=\"ASSERTION_SESSION_ATTRIBUTE_NAME\" Value=\"").append(assertionSessionAttributeName).append("\"").append(GT_CLOSE).append(NL)
+        .append(INDENT).append(INDENT).append(LT_CLOSE).append(HANDLER_ELEMENT).append(GT).append(NL)
+        .append(INDENT).append(INDENT).append(LT_OPEN).append(HANDLER_ELEMENT).append(" class=\"").append(ROLE_GEN_HANDLER_CLASSNAME).append("\"/>").append(NL)
+      .append(INDENT).append(LT_CLOSE).append(HANDLERS_ELEMENT).append(GT).append(NL)
+    .append(LT_CLOSE).append(PICKETLINK_ELEMENT).append(GT).append(NL);
+     
+    return xml.toString();
+  }
+  
+  public static void main(String[] args) {
+    PicketlinkConf conf = new PicketlinkConf();
+    System.out.println(conf.toString());
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/deploy/PicketlinkFederationProviderContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/deploy/PicketlinkFederationProviderContributor.java b/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/deploy/PicketlinkFederationProviderContributor.java
new file mode 100644
index 0000000..d13bdaa
--- /dev/null
+++ b/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/deploy/PicketlinkFederationProviderContributor.java
@@ -0,0 +1,132 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.picketlink.deploy;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.picketlink.PicketlinkMessages;
+import org.apache.knox.gateway.services.security.AliasService;
+import org.apache.knox.gateway.services.security.AliasServiceException;
+import org.apache.knox.gateway.services.security.MasterService;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+import org.jboss.shrinkwrap.api.asset.StringAsset;
+import org.picketlink.identity.federation.web.filters.ServiceProviderContextInitializer;
+
+public class PicketlinkFederationProviderContributor extends
+    ProviderDeploymentContributorBase {
+  private static final String ROLE = "federation";
+  private static final String NAME = "Picketlink";
+  private static final String PICKETLINK_FILTER_CLASSNAME = "org.picketlink.identity.federation.web.filters.SPFilter";
+  private static final String CAPTURE_URL_FILTER_CLASSNAME = "CaptureOriginalURLFilter";
+  private static final String IDENTITY_ADAPTER_CLASSNAME = "PicketlinkIdentityAdapter";
+  private static final String IDENTITY_URL_PARAM = "identity.url";
+  private static final String SERVICE_URL_PARAM = "service.url";
+  private static final String KEYSTORE_URL_PARAM = "keystore.url";
+  private static final String SIGNINGKEY_ALIAS = "gateway-identity";
+  private static final String VALIDATING_ALIAS_KEY = "validating.alias.key";
+  private static final String VALIDATING_ALIAS_VALUE = "validating.alias.value";
+  private static final String CLOCK_SKEW_MILIS = "clock.skew.milis";
+  private static PicketlinkMessages log = MessagesFactory.get( PicketlinkMessages.class );
+
+  private MasterService ms = null;
+  private AliasService as = null;
+
+  @Override
+  public String getRole() {
+    return ROLE;
+  }
+
+  @Override
+  public String getName() {
+    return NAME;
+  }
+  
+  public void setMasterService(MasterService ms) {
+    this.ms = ms;
+  }
+
+  public void setAliasService(AliasService as) {
+    this.as = as;
+  }
+
+  @Override
+  public void initializeContribution(DeploymentContext context) {
+    super.initializeContribution(context);
+  }
+
+  @Override
+  public void contributeProvider(DeploymentContext context, Provider provider) {
+    // LJM TODO: consider creating a picketlink configuration provider to
+    // handle the keystore secrets without putting them in a config file directly.
+    // Once that is done then we can remove the unneeded gateway services from those
+    // that are available to providers.
+    context.getWebAppDescriptor().createListener().listenerClass( ServiceProviderContextInitializer.class.getName());
+
+    PicketlinkConf config = new PicketlinkConf( );
+    Map<String,String> params = provider.getParams();
+    config.setIdentityURL(params.get(IDENTITY_URL_PARAM));
+    config.setServiceURL(params.get(SERVICE_URL_PARAM));
+    config.setKeystoreURL(params.get(KEYSTORE_URL_PARAM));
+    if (ms != null) {
+      config.setKeystorePass(new String(ms.getMasterSecret()));
+    }
+    config.setSigningKeyAlias(SIGNINGKEY_ALIAS);
+    if (as != null) {
+      char[] passphrase = null;
+      try {
+        passphrase = as.getGatewayIdentityPassphrase();
+        config.setSigningKeyPass(new String(passphrase));
+      } catch (AliasServiceException e) {
+        log.unableToGetGatewayIdentityPassphrase(e);
+      }
+    }
+    config.setValidatingAliasKey(params.get(VALIDATING_ALIAS_KEY));
+    config.setValidatingAliasValue(params.get(VALIDATING_ALIAS_VALUE));
+    config.setClockSkewMilis(params.get(CLOCK_SKEW_MILIS));
+    String configStr = config.toString();
+    if( config != null ) {
+      context.getWebArchive().addAsWebInfResource( new StringAsset( configStr ), "picketlink.xml" );
+    }
+  }
+
+  @Override
+  public void contributeFilter(DeploymentContext context, Provider provider, Service service,
+      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
+    // blindly add all the provider params as filter init params
+    if (params == null) {
+      params = new ArrayList<FilterParamDescriptor>();
+    }
+    Map<String, String> providerParams = provider.getParams();
+    for(Entry<String, String> entry : providerParams.entrySet()) {
+      params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
+    }
+    resource.addFilter().name( getName() ).role( getRole() ).impl( CAPTURE_URL_FILTER_CLASSNAME ).params( params );
+    resource.addFilter().name( getName() ).role( getRole() ).impl( PICKETLINK_FILTER_CLASSNAME ).params( params );
+    resource.addFilter().name( getName() ).role( getRole() ).impl( IDENTITY_ADAPTER_CLASSNAME ).params( params );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/filter/CaptureOriginalURLFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/filter/CaptureOriginalURLFilter.java b/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/filter/CaptureOriginalURLFilter.java
new file mode 100644
index 0000000..b062013
--- /dev/null
+++ b/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/filter/CaptureOriginalURLFilter.java
@@ -0,0 +1,89 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.picketlink.filter;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.picketlink.PicketlinkMessages;
+
+import java.io.IOException;
+
+public class CaptureOriginalURLFilter implements Filter {
+  private static PicketlinkMessages log = MessagesFactory.get( PicketlinkMessages.class );
+  private static final String COOKIE_PATH = "cookie.path";
+  private static final String COOKIE_SECURE = "cookie.secure";
+  private String cookiePath = null;
+  private String cookieSecure = null;
+
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+    cookiePath = filterConfig.getInitParameter(COOKIE_PATH);
+    if (cookiePath == null) {
+      cookiePath = "/gateway/idp/knoxsso/api/v1/websso";
+    }
+    cookieSecure = filterConfig.getInitParameter(COOKIE_SECURE);
+    if (cookieSecure == null) {
+      cookieSecure = "true";
+    }
+  }
+
+  @Override
+  public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) throws IOException, ServletException {
+    String original = null;
+    HttpServletRequest request = (HttpServletRequest)servletRequest;
+    String url = request.getParameter("originalUrl");
+    if (url != null) {
+      log.foundOriginalURLInRequest(url);
+      original = request.getParameter("originalUrl");
+      log.settingCookieForOriginalURL();
+      addCookie(servletResponse, original);
+    }
+    filterChain.doFilter(request, servletResponse);
+  }
+
+  @Override
+  public void destroy() {
+
+  }
+
+  private void addCookie(ServletResponse servletResponse, String original) {
+    Cookie c = new Cookie("original-url", original);
+    c.setPath(cookiePath);
+    c.setHttpOnly(true);
+    boolean secureOnly = true;
+    if (cookieSecure != null) {
+      secureOnly = ("false".equals(cookieSecure) ? false : true);
+      if (!secureOnly) {
+        log.secureFlagFalseForCookie();
+      }
+    }
+    c.setSecure(secureOnly);
+    c.setMaxAge(60);
+    ((HttpServletResponse)servletResponse).addCookie(c);
+  }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/filter/PicketlinkIdentityAdapter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/filter/PicketlinkIdentityAdapter.java b/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/filter/PicketlinkIdentityAdapter.java
new file mode 100644
index 0000000..e3811b4
--- /dev/null
+++ b/gateway-provider-security-picketlink/src/main/java/org/apache/knox/gateway/picketlink/filter/PicketlinkIdentityAdapter.java
@@ -0,0 +1,102 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.picketlink.filter;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import javax.security.auth.Subject;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.knox.gateway.audit.api.Action;
+import org.apache.knox.gateway.audit.api.ActionOutcome;
+import org.apache.knox.gateway.audit.api.AuditService;
+import org.apache.knox.gateway.audit.api.AuditServiceFactory;
+import org.apache.knox.gateway.audit.api.Auditor;
+import org.apache.knox.gateway.audit.api.ResourceType;
+import org.apache.knox.gateway.audit.log4j.audit.AuditConstants;
+import org.apache.knox.gateway.filter.AbstractGatewayFilter;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+
+public class PicketlinkIdentityAdapter implements Filter {
+  
+  private static AuditService auditService = AuditServiceFactory.getAuditService();
+  private static Auditor auditor = auditService.getAuditor(
+      AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
+      AuditConstants.KNOX_COMPONENT_NAME );
+  
+
+  @Override
+  public void init( FilterConfig filterConfig ) throws ServletException {
+  }
+
+  public void destroy() {
+  }
+
+  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
+      throws IOException, ServletException {
+    
+    HttpServletRequest httpRequest = (HttpServletRequest) request;
+    String username = httpRequest.getUserPrincipal().getName();
+    PrimaryPrincipal pp = new PrimaryPrincipal(username);
+    Subject subject = new Subject();
+    subject.getPrincipals().add(pp);
+    
+    Principal principal = (Principal) subject.getPrincipals(PrimaryPrincipal.class);
+    auditService.getContext().setUsername( principal.getName() );
+    String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
+    auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
+
+    doAs(request, response, chain, subject);
+  }
+  
+  private void doAs(final ServletRequest request,
+      final ServletResponse response, final FilterChain chain, Subject subject)
+      throws IOException, ServletException {
+    try {
+      Subject.doAs(
+          subject,
+          new PrivilegedExceptionAction<Object>() {
+            public Object run() throws Exception {
+              chain.doFilter(request, response);
+              return null;
+            }
+          }
+          );
+    }
+    catch (PrivilegedActionException e) {
+      Throwable t = e.getCause();
+      if (t instanceof IOException) {
+        throw (IOException) t;
+      }
+      else if (t instanceof ServletException) {
+        throw (ServletException) t;
+      }
+      else {
+        throw new ServletException(t);
+      }
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-picketlink/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-picketlink/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-picketlink/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index ec4affc..0000000
--- a/gateway-provider-security-picketlink/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,19 +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.
-##########################################################################
-
-org.apache.hadoop.gateway.picketlink.deploy.PicketlinkFederationProviderContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-picketlink/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-picketlink/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-picketlink/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..2d6b75c
--- /dev/null
+++ b/gateway-provider-security-picketlink/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,19 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+
+org.apache.knox.gateway.picketlink.deploy.PicketlinkFederationProviderContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-picketlink/src/test/java/org/apache/hadoop/gateway/picketlink/PicketlinkTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-picketlink/src/test/java/org/apache/hadoop/gateway/picketlink/PicketlinkTest.java b/gateway-provider-security-picketlink/src/test/java/org/apache/hadoop/gateway/picketlink/PicketlinkTest.java
deleted file mode 100644
index 4ef3088..0000000
--- a/gateway-provider-security-picketlink/src/test/java/org/apache/hadoop/gateway/picketlink/PicketlinkTest.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.picketlink;
-
-import junit.framework.TestCase;
-
-import org.apache.hadoop.gateway.services.security.token.impl.JWTToken;
-import org.junit.Test;
-
-public class PicketlinkTest extends TestCase {
-  @Test
-  public void testPicketlink() throws Exception {
-    assertTrue(true);
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-picketlink/src/test/java/org/apache/knox/gateway/picketlink/PicketlinkTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-picketlink/src/test/java/org/apache/knox/gateway/picketlink/PicketlinkTest.java b/gateway-provider-security-picketlink/src/test/java/org/apache/knox/gateway/picketlink/PicketlinkTest.java
new file mode 100644
index 0000000..92edc98
--- /dev/null
+++ b/gateway-provider-security-picketlink/src/test/java/org/apache/knox/gateway/picketlink/PicketlinkTest.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.knox.gateway.picketlink;
+
+import junit.framework.TestCase;
+
+import org.junit.Test;
+
+public class PicketlinkTest extends TestCase {
+  @Test
+  public void testPicketlink() throws Exception {
+    assertTrue(true);
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/PreAuthMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/PreAuthMessages.java b/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/PreAuthMessages.java
deleted file mode 100644
index 5b2e991..0000000
--- a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/PreAuthMessages.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.hadoop.gateway.preauth;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-
-@Messages(logger="org.apache.hadoop.gateway.provider.global.csrf")
-public interface PreAuthMessages {
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/deploy/HeaderPreAuthContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/deploy/HeaderPreAuthContributor.java b/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/deploy/HeaderPreAuthContributor.java
deleted file mode 100644
index 52d2131..0000000
--- a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/deploy/HeaderPreAuthContributor.java
+++ /dev/null
@@ -1,66 +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.hadoop.gateway.preauth.deploy;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-public class HeaderPreAuthContributor extends
-    ProviderDeploymentContributorBase {
-  private static final String ROLE = "federation";
-  private static final String NAME = "HeaderPreAuth";
-  private static final String PREAUTH_FILTER_CLASSNAME = "org.apache.hadoop.gateway.preauth.filter.HeaderPreAuthFederationFilter";
-
-  @Override
-  public String getRole() {
-    return ROLE;
-  }
-
-  @Override
-  public String getName() {
-    return NAME;
-  }
-
-  @Override
-  public void initializeContribution(DeploymentContext context) {
-    super.initializeContribution(context);
-  }
-
-  @Override
-  public void contributeFilter(DeploymentContext context, Provider provider, Service service, 
-      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
-    // blindly add all the provider params as filter init params
-    if (params == null) {
-      params = new ArrayList<FilterParamDescriptor>();
-    }
-    Map<String, String> providerParams = provider.getParams();
-    for(Entry<String, String> entry : providerParams.entrySet()) {
-      params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
-    }
-    resource.addFilter().name( getName() ).role( getRole() ).impl( PREAUTH_FILTER_CLASSNAME ).params( params );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/AbstractPreAuthFederationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/AbstractPreAuthFederationFilter.java b/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/AbstractPreAuthFederationFilter.java
deleted file mode 100644
index fa4df69..0000000
--- a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/AbstractPreAuthFederationFilter.java
+++ /dev/null
@@ -1,144 +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.hadoop.gateway.preauth.filter;
-
-import java.io.IOException;
-import java.security.Principal;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.List;
-import java.util.Set;
-
-import javax.security.auth.Subject;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import com.google.common.annotations.VisibleForTesting;
-
-import org.apache.hadoop.gateway.audit.api.Action;
-import org.apache.hadoop.gateway.audit.api.ActionOutcome;
-import org.apache.hadoop.gateway.audit.api.AuditService;
-import org.apache.hadoop.gateway.audit.api.AuditServiceFactory;
-import org.apache.hadoop.gateway.audit.api.Auditor;
-import org.apache.hadoop.gateway.audit.api.ResourceType;
-import org.apache.hadoop.gateway.audit.log4j.audit.AuditConstants;
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-
-/**
- *
- */
-public abstract class AbstractPreAuthFederationFilter implements Filter {
-
-  private List<PreAuthValidator> validators = null;
-  private FilterConfig filterConfig;
-  private static AuditService auditService = AuditServiceFactory.getAuditService();
-  private static Auditor auditor = auditService.getAuditor(
-      AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
-      AuditConstants.KNOX_COMPONENT_NAME );
-
-  /**
-   * 
-   */
-  public AbstractPreAuthFederationFilter() {
-    super();
-  }
-
-  @Override
-  public void init(FilterConfig filterConfig) throws ServletException {
-    this.filterConfig = filterConfig;
-    validators = PreAuthService.getValidators(filterConfig);
-  }
-
-  @VisibleForTesting
-  public List<PreAuthValidator> getValidators() {
-    return validators;
-  }
-
-  @Override
-  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
-      throws IOException, ServletException {
-    HttpServletRequest httpRequest = (HttpServletRequest)request;
-    String principal = getPrimaryPrincipal(httpRequest);
-    if (principal != null) {
-      if (PreAuthService.validate(httpRequest, filterConfig, validators)) {
-        Subject subject = new Subject();
-        subject.getPrincipals().add(new PrimaryPrincipal(principal));
-        addGroupPrincipals(httpRequest, subject.getPrincipals());
-        auditService.getContext().setUsername( principal ); //KM: Audit Fix
-        String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
-        auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
-        doAs(httpRequest, response, chain, subject);
-      }
-      else {
-        // TODO: log preauthenticated SSO validation failure
-        ((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN, "SSO Validation Failure.");
-      }
-    } 
-    else {
-      ((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN, "Missing Required Header for PreAuth SSO Federation");
-    }
-  }
-
-  @Override
-  public void destroy() {
-  }
-
-  private void doAs(final ServletRequest request, final ServletResponse response, final FilterChain chain, Subject subject)
-    throws IOException, ServletException {
-    try {
-      Subject.doAs(
-          subject,
-          new PrivilegedExceptionAction<Object>() {
-            public Object run() throws Exception {
-              chain.doFilter(request, response);
-              return null;
-            }
-          }
-          );
-    }
-    catch (PrivilegedActionException e) {
-      Throwable t = e.getCause();
-      if (t instanceof IOException) {
-        throw (IOException) t;
-      }
-      else if (t instanceof ServletException) {
-        throw (ServletException) t;
-      }
-      else {
-        throw new ServletException(t);
-      }
-    }
-  }
-  
-  /**
-   * @param httpRequest
-   */
-  abstract protected String getPrimaryPrincipal(HttpServletRequest httpRequest);
-
-  /**
-   * @param principals
-   */
-  abstract protected void addGroupPrincipals(HttpServletRequest request, Set<Principal> principals);
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/DefaultValidator.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/DefaultValidator.java b/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/DefaultValidator.java
deleted file mode 100644
index fe1cec5..0000000
--- a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/DefaultValidator.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.hadoop.gateway.preauth.filter;
-
-import javax.servlet.FilterConfig;
-import javax.servlet.http.HttpServletRequest;
-
-/**
- * @since 0.12
- * This class implements the default Validator where really no validation is performed.
- * TODO: log the fact that there is no verification going on to validate
- * +  who is asserting the identity with the a header. Without some validation
- * +  we are assuming the network security is the primary protection method.
- */
-public class DefaultValidator implements PreAuthValidator {
-  public static final String DEFAULT_VALIDATION_METHOD_VALUE = "preauth.default.validation";
-
-  public DefaultValidator() {
-  }
-
-  /**
-   * @param httpRequest
-   * @param filterConfig
-   * @return true if validated, otherwise false
-   * @throws PreAuthValidationException
-   */
-  @Override
-  public boolean validate(HttpServletRequest httpRequest, FilterConfig filterConfig) throws PreAuthValidationException {
-    return true;
-  }
-
-  /**
-   * Return unique validator name
-   *
-   * @return name of validator
-   */
-  @Override
-  public String getName() {
-    return DEFAULT_VALIDATION_METHOD_VALUE;
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/HeaderPreAuthFederationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/HeaderPreAuthFederationFilter.java b/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/HeaderPreAuthFederationFilter.java
deleted file mode 100644
index df88849..0000000
--- a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/HeaderPreAuthFederationFilter.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.hadoop.gateway.preauth.filter;
-
-import java.security.Principal;
-import java.util.Set;
-
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.hadoop.gateway.security.GroupPrincipal;
-
-
-public class HeaderPreAuthFederationFilter extends AbstractPreAuthFederationFilter {
-  static final String CUSTOM_HEADER_PARAM = "preauth.custom.header";
-  static final String CUSTOM_GROUP_HEADER_PARAM = "preauth.custom.group.header";
-  String headerName = "SM_USER";
-  String groupHeaderName = null;
-  
-  @Override
-  public void init(FilterConfig filterConfig) throws ServletException {
-    super.init(filterConfig);
-    String customHeader = filterConfig.getInitParameter(CUSTOM_HEADER_PARAM);
-    if (customHeader != null) {
-      headerName = customHeader;
-    }
-    String customGroupHeader = filterConfig.getInitParameter(CUSTOM_GROUP_HEADER_PARAM);
-    if (customGroupHeader != null) {
-      groupHeaderName = customGroupHeader;
-    }
-  }
-
-  /**
-   * @param httpRequest
-   */
-  @Override
-  protected String getPrimaryPrincipal(HttpServletRequest httpRequest) {
-    return httpRequest.getHeader(headerName);
-  }
-
-  /**
-   * @param principals
-   */
-  @Override
-  protected void addGroupPrincipals(HttpServletRequest request, Set<Principal> principals) {
-    if (groupHeaderName != null) {
-      String headers = request.getHeader(groupHeaderName);
-      if (headers != null) {
-        String[] groups = headers.split(",");
-        for (int i = 0; i < groups.length; i++) {
-          principals.add(new GroupPrincipal(groups[i]));
-        }
-      }
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/IPValidator.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/IPValidator.java b/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/IPValidator.java
deleted file mode 100644
index 9df23b5..0000000
--- a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/IPValidator.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.hadoop.gateway.preauth.filter;
-
-import javax.servlet.FilterConfig;
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.hadoop.gateway.util.IpAddressValidator;
-
-/**
- *
- */
-public class IPValidator implements PreAuthValidator {
-  public static final String IP_ADDRESSES_PARAM = "preauth.ip.addresses";
-  public static final String IP_VALIDATION_METHOD_VALUE = "preauth.ip.validation";
-
-  public IPValidator() {
-  }
-
-  /**
-   * @param httpRequest
-   * @param filterConfig
-   * @return true if validated, otherwise false
-   * @throws PreAuthValidationException
-   */
-  @Override
-  public boolean validate(HttpServletRequest httpRequest, FilterConfig filterConfig)
-      throws PreAuthValidationException {
-    String ipParam = filterConfig.getInitParameter(IP_ADDRESSES_PARAM);
-    IpAddressValidator ipv = new IpAddressValidator(ipParam);
-    return ipv.validateIpAddress(httpRequest.getRemoteAddr());
-  }
-
-  /**
-   * Return unique validator name
-   *
-   * @return name of validator
-   */
-  @Override
-  public String getName() {
-    return IP_VALIDATION_METHOD_VALUE;
-  }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthFederationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthFederationFilter.java b/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthFederationFilter.java
deleted file mode 100644
index 27ae803..0000000
--- a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthFederationFilter.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.hadoop.gateway.preauth.filter;
-
-import java.io.IOException;
-import java.security.AccessController;
-import java.security.Principal;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-import java.util.List;
-
-import javax.security.auth.Subject;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-
-public class PreAuthFederationFilter implements Filter {
-  private static final String CUSTOM_HEADER_PARAM = "preauth.customHeader";
-  private List<PreAuthValidator> validators = null;
-  private FilterConfig filterConfig;
-  private String headerName = "SM_USER";
-
-  @Override
-  public void init(FilterConfig filterConfig) throws ServletException {
-    String customHeader = filterConfig.getInitParameter(CUSTOM_HEADER_PARAM);
-    if (customHeader != null) {
-      headerName = customHeader;
-    }
-    this.filterConfig = filterConfig;
-    validators = PreAuthService.getValidators(filterConfig);
-  }
-
-  @Override
-  public void doFilter(ServletRequest request, ServletResponse response,
-                       FilterChain chain) throws IOException, ServletException {
-    HttpServletRequest httpRequest = (HttpServletRequest) request;
-    if (httpRequest.getHeader(headerName) != null) {
-      if (PreAuthService.validate(httpRequest, filterConfig, validators)) {
-        // TODO: continue as subject
-        chain.doFilter(request, response);
-      } else {
-        // TODO: log preauthenticated SSO validation failure
-        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing Required Header for SSO Validation");
-      }
-    } else {
-      ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing Required Header for PreAuth SSO Federation");
-    }
-  }
-
-  /* (non-Javadoc)
-   * @see javax.servlet.Filter#destroy()
-   */
-  @Override
-  public void destroy() {
-    // TODO Auto-generated method stub
-
-  }
-
-  /**
-   * Recreate the current Subject based upon the provided mappedPrincipal
-   * and look for the groups that should be associated with the new Subject.
-   * Upon finding groups mapped to the principal - add them to the new Subject.
-   * @param mappedPrincipalName
-   * @throws ServletException
-   * @throws IOException
-   */
-  protected void continueChainAsPrincipal(final ServletRequest request, final ServletResponse response,
-                                          final FilterChain chain, String principal) throws IOException, ServletException {
-    Subject subject = null;
-    Principal primaryPrincipal = null;
-
-    // do some check to ensure that the extracted identity matches any existing security context
-    // if not, there is may be someone tampering with the request - consult config to determine
-    // how we are to handle it
-
-    // TODO: make sure that this makes sense with existing sessions or lack thereof
-    Subject currentSubject = Subject.getSubject(AccessController.getContext());
-    if (currentSubject != null) {
-      primaryPrincipal = (PrimaryPrincipal) currentSubject.getPrincipals(PrimaryPrincipal.class).toArray()[0];
-      if (primaryPrincipal != null) {
-        if (!primaryPrincipal.getName().equals(principal)) {
-        }
-      }
-    }
-
-    subject = new Subject();
-    subject.getPrincipals().add(primaryPrincipal);
-    doAs(request, response, chain, subject);
-  }
-
-  private void doAs(final ServletRequest request,
-                    final ServletResponse response, final FilterChain chain, Subject subject)
-      throws IOException, ServletException {
-    try {
-      Subject.doAs(
-          subject,
-          new PrivilegedExceptionAction<Object>() {
-            public Object run() throws Exception {
-              doFilterInternal(request, response, chain);
-              return null;
-            }
-          }
-      );
-    } catch (PrivilegedActionException e) {
-      Throwable t = e.getCause();
-      if (t instanceof IOException) {
-        throw (IOException) t;
-      } else if (t instanceof ServletException) {
-        throw (ServletException) t;
-      } else {
-        throw new ServletException(t);
-      }
-    }
-  }
-
-  private void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
-    chain.doFilter(request, response);
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthService.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthService.java b/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthService.java
deleted file mode 100644
index e1d9751..0000000
--- a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthService.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.hadoop.gateway.preauth.filter;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Strings;
-
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import java.util.ArrayList;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.Collections;
-import java.util.ServiceLoader;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * This class manages few utility methods used across different classes of pre-auth module
- * @since 0.12
- */
-public class PreAuthService {
-
-  public static final String VALIDATION_METHOD_PARAM = "preauth.validation.method";
-  private static ConcurrentHashMap<String, PreAuthValidator> validatorMap;
-
-  static {
-    initializeValidators();
-  }
-
-
-  private static void initializeValidators() {
-    ServiceLoader<PreAuthValidator> servLoader = ServiceLoader.load(PreAuthValidator.class);
-    validatorMap = new ConcurrentHashMap<>();
-    for (Iterator<PreAuthValidator> iterator = servLoader.iterator(); iterator.hasNext(); ) {
-      PreAuthValidator validator = iterator.next();
-      validatorMap.put(validator.getName(), validator);
-    }
-  }
-
-  @VisibleForTesting
-  public static Map<String, PreAuthValidator> getValidatorMap() {
-    return Collections.unmodifiableMap(validatorMap);
-  }
-
-  /**
-   * This method returns appropriate pre-auth Validator as defined in config
-   *
-   * @since 0.12
-   * @param filterConfig
-   * @return List<PreAuthValidator>
-   * @throws ServletException
-   */
-  public static List<PreAuthValidator> getValidators(FilterConfig filterConfig) throws ServletException {
-    String validationMethods = filterConfig.getInitParameter(VALIDATION_METHOD_PARAM);
-    List<PreAuthValidator> vList = new ArrayList<>();
-    if (Strings.isNullOrEmpty(validationMethods)) {
-      validationMethods = DefaultValidator.DEFAULT_VALIDATION_METHOD_VALUE;
-    }
-    Set<String> vMethodSet = new LinkedHashSet<>();
-    Collections.addAll(vMethodSet, validationMethods.trim().split("\\s*,\\s*"));
-    for (String vName : vMethodSet) {
-      if (validatorMap.containsKey(vName)) {
-        vList.add(validatorMap.get(vName));
-      } else {
-        throw new ServletException(String.format("Unable to find validator with name '%s'", validationMethods));
-      }
-    }
-    return vList;
-  }
-
-  public static boolean validate(HttpServletRequest httpRequest, FilterConfig filterConfig, List<PreAuthValidator>
-      validators) {
-    try {
-      for (PreAuthValidator validator : validators) {
-        //Any one validator fails, it will fail the request. loginal AND behavior
-        if (!validator.validate(httpRequest, filterConfig)) {
-          return false;
-        }
-      }
-    } catch (PreAuthValidationException e) {
-      // TODO log exception
-      return false;
-    }
-    return true;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthValidationException.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthValidationException.java b/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthValidationException.java
deleted file mode 100644
index e643033..0000000
--- a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthValidationException.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.hadoop.gateway.preauth.filter;
-
-/**
- * @author larry
- *
- */
-public class PreAuthValidationException extends Exception {
-  PreAuthValidationException(String message) {
-    super(message);
-  }
-
-  PreAuthValidationException(String message, Exception e) {
-    super(message, e);
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthValidator.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthValidator.java b/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthValidator.java
deleted file mode 100644
index 5819801..0000000
--- a/gateway-provider-security-preauth/src/main/java/org/apache/hadoop/gateway/preauth/filter/PreAuthValidator.java
+++ /dev/null
@@ -1,42 +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.hadoop.gateway.preauth.filter;
-
-import javax.servlet.FilterConfig;
-import javax.servlet.http.HttpServletRequest;
-
-/**
- *
- */
-public interface PreAuthValidator {
-  /**
-   * @param httpRequest
-   * @param filterConfig
-   * @return true if validated, otherwise false
-   * @throws PreAuthValidationException
-   */
-  public abstract boolean validate(HttpServletRequest httpRequest, FilterConfig filterConfig) throws
-      PreAuthValidationException;
-
-  /**
-   * Return unique validator name
-   *
-   * @return name of validator
-   */
-  public abstract String getName();
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/PreAuthMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/PreAuthMessages.java b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/PreAuthMessages.java
new file mode 100644
index 0000000..dfe4ca9
--- /dev/null
+++ b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/PreAuthMessages.java
@@ -0,0 +1,24 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.preauth;
+
+import org.apache.knox.gateway.i18n.messages.Messages;
+
+@Messages(logger="org.apache.hadoop.gateway.provider.global.csrf")
+public interface PreAuthMessages {
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/deploy/HeaderPreAuthContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/deploy/HeaderPreAuthContributor.java b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/deploy/HeaderPreAuthContributor.java
new file mode 100644
index 0000000..2a5cebd
--- /dev/null
+++ b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/deploy/HeaderPreAuthContributor.java
@@ -0,0 +1,66 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.preauth.deploy;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+public class HeaderPreAuthContributor extends
+    ProviderDeploymentContributorBase {
+  private static final String ROLE = "federation";
+  private static final String NAME = "HeaderPreAuth";
+  private static final String PREAUTH_FILTER_CLASSNAME = "HeaderPreAuthFederationFilter";
+
+  @Override
+  public String getRole() {
+    return ROLE;
+  }
+
+  @Override
+  public String getName() {
+    return NAME;
+  }
+
+  @Override
+  public void initializeContribution(DeploymentContext context) {
+    super.initializeContribution(context);
+  }
+
+  @Override
+  public void contributeFilter(DeploymentContext context, Provider provider, Service service,
+      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
+    // blindly add all the provider params as filter init params
+    if (params == null) {
+      params = new ArrayList<FilterParamDescriptor>();
+    }
+    Map<String, String> providerParams = provider.getParams();
+    for(Entry<String, String> entry : providerParams.entrySet()) {
+      params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
+    }
+    resource.addFilter().name( getName() ).role( getRole() ).impl( PREAUTH_FILTER_CLASSNAME ).params( params );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/AbstractPreAuthFederationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/AbstractPreAuthFederationFilter.java b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/AbstractPreAuthFederationFilter.java
new file mode 100644
index 0000000..66ee586
--- /dev/null
+++ b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/AbstractPreAuthFederationFilter.java
@@ -0,0 +1,144 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.preauth.filter;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.List;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import com.google.common.annotations.VisibleForTesting;
+
+import org.apache.knox.gateway.audit.api.Action;
+import org.apache.knox.gateway.audit.api.ActionOutcome;
+import org.apache.knox.gateway.audit.api.AuditService;
+import org.apache.knox.gateway.audit.api.AuditServiceFactory;
+import org.apache.knox.gateway.audit.api.Auditor;
+import org.apache.knox.gateway.audit.api.ResourceType;
+import org.apache.knox.gateway.audit.log4j.audit.AuditConstants;
+import org.apache.knox.gateway.filter.AbstractGatewayFilter;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+
+/**
+ *
+ */
+public abstract class AbstractPreAuthFederationFilter implements Filter {
+
+  private List<PreAuthValidator> validators = null;
+  private FilterConfig filterConfig;
+  private static AuditService auditService = AuditServiceFactory.getAuditService();
+  private static Auditor auditor = auditService.getAuditor(
+      AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
+      AuditConstants.KNOX_COMPONENT_NAME );
+
+  /**
+   * 
+   */
+  public AbstractPreAuthFederationFilter() {
+    super();
+  }
+
+  @Override
+  public void init(FilterConfig filterConfig) throws ServletException {
+    this.filterConfig = filterConfig;
+    validators = PreAuthService.getValidators(filterConfig);
+  }
+
+  @VisibleForTesting
+  public List<PreAuthValidator> getValidators() {
+    return validators;
+  }
+
+  @Override
+  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+      throws IOException, ServletException {
+    HttpServletRequest httpRequest = (HttpServletRequest)request;
+    String principal = getPrimaryPrincipal(httpRequest);
+    if (principal != null) {
+      if (PreAuthService.validate(httpRequest, filterConfig, validators)) {
+        Subject subject = new Subject();
+        subject.getPrincipals().add(new PrimaryPrincipal(principal));
+        addGroupPrincipals(httpRequest, subject.getPrincipals());
+        auditService.getContext().setUsername( principal ); //KM: Audit Fix
+        String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
+        auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
+        doAs(httpRequest, response, chain, subject);
+      }
+      else {
+        // TODO: log preauthenticated SSO validation failure
+        ((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN, "SSO Validation Failure.");
+      }
+    } 
+    else {
+      ((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN, "Missing Required Header for PreAuth SSO Federation");
+    }
+  }
+
+  @Override
+  public void destroy() {
+  }
+
+  private void doAs(final ServletRequest request, final ServletResponse response, final FilterChain chain, Subject subject)
+    throws IOException, ServletException {
+    try {
+      Subject.doAs(
+          subject,
+          new PrivilegedExceptionAction<Object>() {
+            public Object run() throws Exception {
+              chain.doFilter(request, response);
+              return null;
+            }
+          }
+          );
+    }
+    catch (PrivilegedActionException e) {
+      Throwable t = e.getCause();
+      if (t instanceof IOException) {
+        throw (IOException) t;
+      }
+      else if (t instanceof ServletException) {
+        throw (ServletException) t;
+      }
+      else {
+        throw new ServletException(t);
+      }
+    }
+  }
+  
+  /**
+   * @param httpRequest
+   */
+  abstract protected String getPrimaryPrincipal(HttpServletRequest httpRequest);
+
+  /**
+   * @param principals
+   */
+  abstract protected void addGroupPrincipals(HttpServletRequest request, Set<Principal> principals);
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/DefaultValidator.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/DefaultValidator.java b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/DefaultValidator.java
new file mode 100644
index 0000000..a51d540
--- /dev/null
+++ b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/DefaultValidator.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.knox.gateway.preauth.filter;
+
+import javax.servlet.FilterConfig;
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ * @since 0.12
+ * This class implements the default Validator where really no validation is performed.
+ * TODO: log the fact that there is no verification going on to validate
+ * +  who is asserting the identity with the a header. Without some validation
+ * +  we are assuming the network security is the primary protection method.
+ */
+public class DefaultValidator implements PreAuthValidator {
+  public static final String DEFAULT_VALIDATION_METHOD_VALUE = "preauth.default.validation";
+
+  public DefaultValidator() {
+  }
+
+  /**
+   * @param httpRequest
+   * @param filterConfig
+   * @return true if validated, otherwise false
+   * @throws PreAuthValidationException
+   */
+  @Override
+  public boolean validate(HttpServletRequest httpRequest, FilterConfig filterConfig) throws PreAuthValidationException {
+    return true;
+  }
+
+  /**
+   * Return unique validator name
+   *
+   * @return name of validator
+   */
+  @Override
+  public String getName() {
+    return DEFAULT_VALIDATION_METHOD_VALUE;
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/HeaderPreAuthFederationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/HeaderPreAuthFederationFilter.java b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/HeaderPreAuthFederationFilter.java
new file mode 100644
index 0000000..eb16ab9
--- /dev/null
+++ b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/HeaderPreAuthFederationFilter.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.knox.gateway.preauth.filter;
+
+import java.security.Principal;
+import java.util.Set;
+
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.knox.gateway.security.GroupPrincipal;
+
+public class HeaderPreAuthFederationFilter extends AbstractPreAuthFederationFilter {
+  static final String CUSTOM_HEADER_PARAM = "preauth.custom.header";
+  static final String CUSTOM_GROUP_HEADER_PARAM = "preauth.custom.group.header";
+  String headerName = "SM_USER";
+  String groupHeaderName = null;
+  
+  @Override
+  public void init(FilterConfig filterConfig) throws ServletException {
+    super.init(filterConfig);
+    String customHeader = filterConfig.getInitParameter(CUSTOM_HEADER_PARAM);
+    if (customHeader != null) {
+      headerName = customHeader;
+    }
+    String customGroupHeader = filterConfig.getInitParameter(CUSTOM_GROUP_HEADER_PARAM);
+    if (customGroupHeader != null) {
+      groupHeaderName = customGroupHeader;
+    }
+  }
+
+  /**
+   * @param httpRequest
+   */
+  @Override
+  protected String getPrimaryPrincipal(HttpServletRequest httpRequest) {
+    return httpRequest.getHeader(headerName);
+  }
+
+  /**
+   * @param principals
+   */
+  @Override
+  protected void addGroupPrincipals(HttpServletRequest request, Set<Principal> principals) {
+    if (groupHeaderName != null) {
+      String headers = request.getHeader(groupHeaderName);
+      if (headers != null) {
+        String[] groups = headers.split(",");
+        for (int i = 0; i < groups.length; i++) {
+          principals.add(new GroupPrincipal(groups[i]));
+        }
+      }
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/IPValidator.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/IPValidator.java b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/IPValidator.java
new file mode 100644
index 0000000..d0c9e5d
--- /dev/null
+++ b/gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/IPValidator.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.knox.gateway.preauth.filter;
+
+import javax.servlet.FilterConfig;
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.knox.gateway.util.IpAddressValidator;
+
+/**
+ *
+ */
+public class IPValidator implements PreAuthValidator {
+  public static final String IP_ADDRESSES_PARAM = "preauth.ip.addresses";
+  public static final String IP_VALIDATION_METHOD_VALUE = "preauth.ip.validation";
+
+  public IPValidator() {
+  }
+
+  /**
+   * @param httpRequest
+   * @param filterConfig
+   * @return true if validated, otherwise false
+   * @throws PreAuthValidationException
+   */
+  @Override
+  public boolean validate(HttpServletRequest httpRequest, FilterConfig filterConfig)
+      throws PreAuthValidationException {
+    String ipParam = filterConfig.getInitParameter(IP_ADDRESSES_PARAM);
+    IpAddressValidator ipv = new IpAddressValidator(ipParam);
+    return ipv.validateIpAddress(httpRequest.getRemoteAddr());
+  }
+
+  /**
+   * Return unique validator name
+   *
+   * @return name of validator
+   */
+  @Override
+  public String getName() {
+    return IP_VALIDATION_METHOD_VALUE;
+  }
+}
\ No newline at end of file


[55/64] knox git commit: KNOX-963 - Use GatewayTestDriver to configure LDAP in gateway-tests

Posted by mo...@apache.org.
KNOX-963 - Use GatewayTestDriver to configure LDAP in gateway-tests


Project: http://git-wip-us.apache.org/repos/asf/knox/repo
Commit: http://git-wip-us.apache.org/repos/asf/knox/commit/6657f2fd
Tree: http://git-wip-us.apache.org/repos/asf/knox/tree/6657f2fd
Diff: http://git-wip-us.apache.org/repos/asf/knox/diff/6657f2fd

Branch: refs/heads/KNOX-998-Package_Restructuring
Commit: 6657f2fd9f52c8303fc9a2d1d72eef38be719288
Parents: d2f0fc0
Author: Colm O hEigeartaigh <co...@apache.org>
Authored: Tue Aug 29 15:28:01 2017 +0100
Committer: Colm O hEigeartaigh <co...@apache.org>
Committed: Tue Aug 29 15:28:01 2017 +0100

----------------------------------------------------------------------
 .../hadoop/gateway/GatewayTestDriver.java       | 20 +++++----
 .../hadoop/gateway/GatewayAdminFuncTest.java    | 26 ++---------
 .../gateway/GatewayAdminTopologyFuncTest.java   | 30 +++----------
 .../hadoop/gateway/GatewayAppFuncTest.java      | 28 ++----------
 .../hadoop/gateway/GatewayBasicFuncTest.java    |  4 +-
 .../hadoop/gateway/GatewayDeployFuncTest.java   | 27 ++----------
 .../GatewayLdapDynamicGroupFuncTest.java        | 43 ++++++-------------
 .../gateway/GatewayLdapGroupFuncTest.java       | 38 ++++-------------
 .../gateway/GatewayLdapPosixGroupFuncTest.java  | 34 +++++----------
 .../gateway/GatewayLocalServiceFuncTest.java    | 27 ++----------
 .../hadoop/gateway/GatewayMultiFuncTest.java    | 30 +++----------
 .../hadoop/gateway/GatewaySampleFuncTest.java   | 26 ++---------
 .../hadoop/gateway/GatewaySslFuncTest.java      | 28 ++----------
 .../apache/hadoop/gateway/Knox242FuncTest.java  | 45 ++++++--------------
 .../gateway/KnoxCliLdapFuncTestNegative.java    | 29 +++----------
 .../gateway/KnoxCliLdapFuncTestPositive.java    | 29 +++----------
 .../hadoop/gateway/KnoxCliSysBindTest.java      | 29 +++----------
 17 files changed, 111 insertions(+), 382 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test-release-utils/src/main/java/org/apache/hadoop/gateway/GatewayTestDriver.java
----------------------------------------------------------------------
diff --git a/gateway-test-release-utils/src/main/java/org/apache/hadoop/gateway/GatewayTestDriver.java b/gateway-test-release-utils/src/main/java/org/apache/hadoop/gateway/GatewayTestDriver.java
index bcbeeea..3135123 100644
--- a/gateway-test-release-utils/src/main/java/org/apache/hadoop/gateway/GatewayTestDriver.java
+++ b/gateway-test-release-utils/src/main/java/org/apache/hadoop/gateway/GatewayTestDriver.java
@@ -95,7 +95,7 @@ public class GatewayTestDriver {
     Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
     return setupLdap( port, path.toFile() );
   }
-  
+
   public int setupLdap( int port, File ldifConfig ) throws Exception {
     ldapTransport = new TcpTransport( port );
     ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", ldifConfig, ldapTransport );
@@ -169,13 +169,17 @@ public class GatewayTestDriver {
   }
 
   public void cleanup() throws Exception {
-    gateway.stop();
-    FileUtils.deleteQuietly( new File( config.getGatewayTopologyDir() ) );
-    FileUtils.deleteQuietly( new File( config.getGatewayConfDir() ) );
-    FileUtils.deleteQuietly( new File( config.getGatewaySecurityDir() ) );
-    FileUtils.deleteQuietly( new File( config.getGatewayDeploymentDir() ) );
-    FileUtils.deleteQuietly( new File( config.getGatewayDataDir() ) );
-    FileUtils.deleteQuietly( new File( config.getGatewayServicesDir() ) );
+    if ( gateway != null ) {
+      gateway.stop();
+    }
+    if ( config != null ) {
+      FileUtils.deleteQuietly( new File( config.getGatewayTopologyDir() ) );
+      FileUtils.deleteQuietly( new File( config.getGatewayConfDir() ) );
+      FileUtils.deleteQuietly( new File( config.getGatewaySecurityDir() ) );
+      FileUtils.deleteQuietly( new File( config.getGatewayDeploymentDir() ) );
+      FileUtils.deleteQuietly( new File( config.getGatewayDataDir() ) );
+      FileUtils.deleteQuietly( new File( config.getGatewayServicesDir() ) );
+    }
 
     for( Service service : services.values() ) {
       service.server.stop();

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayAdminFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayAdminFuncTest.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayAdminFuncTest.java
index 8c73b57..ea4c779 100644
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayAdminFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayAdminFuncTest.java
@@ -19,9 +19,7 @@ package org.apache.hadoop.gateway;
 
 import com.mycila.xmltool.XMLDoc;
 import com.mycila.xmltool.XMLTag;
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
 import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer;
 import org.apache.hadoop.gateway.services.DefaultGatewayServices;
 import org.apache.hadoop.gateway.services.ServiceLifecycleException;
 import org.apache.hadoop.test.TestUtils;
@@ -40,10 +38,7 @@ import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import java.net.ServerSocket;
 import java.net.URL;
-import java.nio.file.FileSystems;
-import java.nio.file.Path;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.UUID;
@@ -62,14 +57,13 @@ public class GatewayAdminFuncTest {
   public static GatewayServer gateway;
   public static String gatewayUrl;
   public static String clusterUrl;
-  public static SimpleLdapDirectoryServer ldap;
-  public static TcpTransport ldapTransport;
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   @BeforeClass
   public static void setupSuite() throws Exception {
     TestUtils.LOG_ENTER();
     //appenders = NoOpAppender.setUp();
-    setupLdap();
+    driver.setupLdap(0);
     setupGateway();
     TestUtils.LOG_EXIT();
   }
@@ -78,24 +72,12 @@ public class GatewayAdminFuncTest {
   public static void cleanupSuite() throws Exception {
     TestUtils.LOG_ENTER();
     gateway.stop();
-    ldap.stop( true );
+    driver.cleanup();
     //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
     //NoOpAppender.tearDown( appenders );
     TestUtils.LOG_EXIT();
   }
 
-  public static void setupLdap() throws Exception {
-    String basedir = System.getProperty("basedir");
-    if (basedir == null) {
-      basedir = new File(".").getCanonicalPath();
-    }
-    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-    ldap.start();
-    LOG.info( "LDAP port = " + ldapTransport.getPort() );
-  }
-
   public static void setupGateway() throws Exception {
 
     File targetDir = new File( System.getProperty( "user.dir" ), "target" );
@@ -151,7 +133,7 @@ public class GatewayAdminFuncTest {
         .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" ).gotoParent()
         .addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
-        .addTag( "value" ).addText( "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() ).gotoParent()
+        .addTag( "value" ).addText( driver.getLdapUrl() ).gotoParent()
         .addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.authenticationMechanism" )
         .addTag( "value" ).addText( "simple" ).gotoParent()

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayAdminTopologyFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayAdminTopologyFuncTest.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayAdminTopologyFuncTest.java
index 204879e..9c8a38d 100644
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayAdminTopologyFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayAdminTopologyFuncTest.java
@@ -25,8 +25,6 @@ import java.io.StringReader;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.net.URL;
-import java.nio.file.FileSystems;
-import java.nio.file.Path;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Map;
@@ -36,9 +34,7 @@ import javax.ws.rs.core.MediaType;
 import com.jayway.restassured.http.ContentType;
 import com.mycila.xmltool.XMLDoc;
 import com.mycila.xmltool.XMLTag;
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
 import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer;
 import org.apache.hadoop.gateway.services.DefaultGatewayServices;
 import org.apache.hadoop.gateway.services.GatewayServices;
 import org.apache.hadoop.gateway.services.ServiceLifecycleException;
@@ -84,37 +80,23 @@ public class GatewayAdminTopologyFuncTest {
   public static GatewayServer gateway;
   public static String gatewayUrl;
   public static String clusterUrl;
-  public static SimpleLdapDirectoryServer ldap;
-  public static TcpTransport ldapTransport;
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   @BeforeClass
   public static void setupSuite() throws Exception {
     //appenders = NoOpAppender.setUp();
-    setupLdap();
+    driver.setupLdap(0);
     setupGateway(new GatewayTestConfig());
   }
 
   @AfterClass
   public static void cleanupSuite() throws Exception {
     gateway.stop();
-    ldap.stop( true );
+    driver.cleanup();
     //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
     //NoOpAppender.tearDown( appenders );
   }
 
-  public static void setupLdap() throws Exception {
-    String basedir = System.getProperty("basedir");
-    if (basedir == null) {
-      basedir = new File(".").getCanonicalPath();
-    }
-    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
-
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-    ldap.start();
-    LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-  }
-
   public static void setupGateway(GatewayTestConfig testConfig) throws Exception {
 
     File targetDir = new File( System.getProperty( "user.dir" ), "target" );
@@ -182,7 +164,7 @@ public class GatewayAdminTopologyFuncTest {
         .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" ).gotoParent()
         .addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
-        .addTag( "value" ).addText( "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() ).gotoParent()
+        .addTag( "value" ).addText( driver.getLdapUrl() ).gotoParent()
         .addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.authenticationMechanism" )
         .addTag( "value" ).addText( "simple" ).gotoParent()
@@ -225,7 +207,7 @@ public class GatewayAdminTopologyFuncTest {
         .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" ).gotoParent()
         .addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
-        .addTag( "value" ).addText( "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() ).gotoParent()
+        .addTag( "value" ).addText( driver.getLdapUrl() ).gotoParent()
         .addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.authenticationMechanism" )
         .addTag( "value" ).addText( "simple" ).gotoParent()
@@ -474,7 +456,7 @@ public class GatewayAdminTopologyFuncTest {
 
     Param ldapURL = new Param();
     ldapURL.setName("main.ldapRealm.contextFactory.url");
-    ldapURL.setValue("ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort());
+    ldapURL.setValue(driver.getLdapUrl());
 
     Param ldapUserTemplate = new Param();
     ldapUserTemplate.setName("main.ldapRealm.userDnTemplate");

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayAppFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayAppFuncTest.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayAppFuncTest.java
index 2cd3ac7..3007dfa 100644
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayAppFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayAppFuncTest.java
@@ -20,8 +20,6 @@ package org.apache.hadoop.gateway;
 import java.io.File;
 import java.net.URL;
 import java.nio.charset.Charset;
-import java.nio.file.FileSystems;
-import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Enumeration;
@@ -32,8 +30,6 @@ import java.util.Properties;
 import java.util.UUID;
 
 import org.apache.commons.io.FileUtils;
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
-import org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer;
 import org.apache.hadoop.gateway.services.DefaultGatewayServices;
 import org.apache.hadoop.gateway.services.GatewayServices;
 import org.apache.hadoop.gateway.services.ServiceLifecycleException;
@@ -76,18 +72,16 @@ public class GatewayAppFuncTest {
   private static int gatewayPort;
   private static String gatewayUrl;
   private static String clusterUrl;
-  private static SimpleLdapDirectoryServer ldap;
-  private static TcpTransport ldapTransport;
-  private static int ldapPort;
   private static Properties params;
   private static TopologyService topos;
   private static MockServer mockWebHdfs;
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   @BeforeClass
   public static void setupSuite() throws Exception {
     LOG_ENTER();
     //appenders = NoOpAppender.setUp();
-    setupLdap();
+    driver.setupLdap(0);
     setupGateway();
     LOG_EXIT();
   }
@@ -96,7 +90,7 @@ public class GatewayAppFuncTest {
   public static void cleanupSuite() throws Exception {
     LOG_ENTER();
     gateway.stop();
-    ldap.stop( true );
+    driver.cleanup();
     FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
     //NoOpAppender.tearDown( appenders );
     LOG_EXIT();
@@ -108,20 +102,6 @@ public class GatewayAppFuncTest {
     FileUtils.cleanDirectory( new File( config.getGatewayDeploymentDir() ) );
   }
 
-  public static void setupLdap() throws Exception {
-    String basedir = System.getProperty("basedir");
-    if (basedir == null) {
-      basedir = new File(".").getCanonicalPath();
-    }
-    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
-
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-    ldap.start();
-    ldapPort = ldapTransport.getAcceptor().getLocalAddress().getPort();
-    LOG.info( "LDAP port = " + ldapPort );
-  }
-
   public static void setupGateway() throws Exception {
 
     File targetDir = new File( System.getProperty( "user.dir" ), "target" );
@@ -178,7 +158,7 @@ public class GatewayAppFuncTest {
     LOG.info( "Gateway port = " + gateway.getAddresses()[ 0 ].getPort() );
 
     params = new Properties();
-    params.put( "LDAP_URL", "ldap://localhost:" + ldapPort );
+    params.put( "LDAP_URL", driver.getLdapUrl() );
     params.put( "WEBHDFS_URL", "http://localhost:" + mockWebHdfs.getPort() );
   }
 

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayBasicFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayBasicFuncTest.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayBasicFuncTest.java
index d8f1352..bbb801b 100644
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayBasicFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayBasicFuncTest.java
@@ -35,7 +35,6 @@ import java.util.Map;
 import java.util.Map.Entry;
 import javax.ws.rs.core.MediaType;
 
-import com.jayway.restassured.RestAssured;
 import com.jayway.restassured.http.ContentType;
 import com.jayway.restassured.path.json.JsonPath;
 import com.jayway.restassured.response.Cookie;
@@ -113,7 +112,7 @@ public class GatewayBasicFuncTest {
 
   private static Logger log = LoggerFactory.getLogger( GatewayBasicFuncTest.class );
 
-  public static GatewayTestDriver driver = new GatewayTestDriver();
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   // Controls the host name to which the gateway dispatch requests.  This may be the name of a sandbox VM
   // or an EC2 instance.  Currently only a single host is supported.
@@ -147,7 +146,6 @@ public class GatewayBasicFuncTest {
     //Log.setLog( new NoOpLogger() );
     LOG_ENTER();
     GatewayTestConfig config = new GatewayTestConfig();
-    config.setGatewayPath( "gateway" );
     driver.setResourceBase(GatewayBasicFuncTest.class);
     driver.setupLdap(0);
     driver.setupService("WEBHDFS", "http://" + TEST_HOST + ":50070/webhdfs", "/cluster/webhdfs", USE_MOCK_SERVICES);

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayDeployFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayDeployFuncTest.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayDeployFuncTest.java
index a37181c..296f480 100644
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayDeployFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayDeployFuncTest.java
@@ -21,9 +21,7 @@ import com.jayway.restassured.response.Response;
 import com.mycila.xmltool.XMLDoc;
 import com.mycila.xmltool.XMLTag;
 import org.apache.commons.io.FileUtils;
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
 import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer;
 import org.apache.hadoop.gateway.services.DefaultGatewayServices;
 import org.apache.hadoop.gateway.services.ServiceLifecycleException;
 import org.apache.hadoop.test.TestUtils;
@@ -46,10 +44,7 @@ import java.io.FileOutputStream;
 import java.io.FilenameFilter;
 import java.io.IOException;
 import java.io.InputStream;
-import java.net.ServerSocket;
 import java.net.URL;
-import java.nio.file.FileSystems;
-import java.nio.file.Path;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Map;
@@ -77,39 +72,25 @@ public class GatewayDeployFuncTest {
   public static File gatewayHome;
   public static String gatewayUrl;
   public static String clusterUrl;
-  public static SimpleLdapDirectoryServer ldap;
-  public static TcpTransport ldapTransport;
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   @BeforeClass
   public static void setupSuite() throws Exception {
     LOG_ENTER();
     //appenders = NoOpAppender.setUp();
-    setupLdap();
+    driver.setupLdap(0);
     LOG_EXIT();
   }
 
   @AfterClass
   public static void cleanupSuite() throws Exception {
     LOG_ENTER();
-    ldap.stop( true );
+    driver.cleanup();
     //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
     //NoOpAppender.tearDown( appenders );
     LOG_EXIT();
   }
 
-  public static void setupLdap() throws Exception {
-    String basedir = System.getProperty("basedir");
-    if (basedir == null) {
-      basedir = new File(".").getCanonicalPath();
-    }
-    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
-
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-    ldap.start();
-    LOG.info( "LDAP port = " + ldapTransport.getPort() );
-  }
-
   @Before
   public void setupGateway() throws Exception {
 
@@ -169,7 +150,7 @@ public class GatewayDeployFuncTest {
         .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" ).gotoParent()
         .addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
-        .addTag( "value" ).addText( "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() ).gotoParent()
+        .addTag( "value" ).addText( driver.getLdapUrl() ).gotoParent()
         .addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.authenticationMechanism" )
         .addTag( "value" ).addText( "simple" ).gotoParent()

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLdapDynamicGroupFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLdapDynamicGroupFuncTest.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLdapDynamicGroupFuncTest.java
index e04c73a..174eb58 100755
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLdapDynamicGroupFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLdapDynamicGroupFuncTest.java
@@ -30,8 +30,6 @@ import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.PrintStream;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
 import java.net.URL;
 import java.nio.file.FileSystems;
 import java.nio.file.Path;
@@ -40,10 +38,8 @@ import java.util.HashMap;
 import java.util.Map;
 import java.util.UUID;
 
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
 import org.apache.hadoop.gateway.config.GatewayConfig;
 import org.apache.hadoop.gateway.config.impl.GatewayConfigImpl;
-import org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer;
 import org.apache.hadoop.gateway.services.DefaultGatewayServices;
 import org.apache.hadoop.gateway.services.GatewayServices;
 import org.apache.hadoop.gateway.services.ServiceLifecycleException;
@@ -80,16 +76,19 @@ public class GatewayLdapDynamicGroupFuncTest {
   public static String gatewayUrl;
   public static String clusterUrl;
   public static String serviceUrl;
-  public static SimpleLdapDirectoryServer ldap;
-  public static TcpTransport ldapTransport;
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   @BeforeClass
   public static void setupSuite() throws Exception {
     LOG_ENTER();
     //appenders = NoOpAppender.setUp();
-    int port = setupLdap();
-    setupGateway(port);
-    TestUtils.awaitPortOpen( new InetSocketAddress( "localhost", port ), 10000, 100 );
+    String basedir = System.getProperty("basedir");
+    if (basedir == null) {
+      basedir = new File(".").getCanonicalPath();
+    }
+    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users-dynamic.ldif");
+    driver.setupLdap( 0, path.toFile() );
+    setupGateway();
     TestUtils.awaitNon404HttpStatus( new URL( serviceUrl ), 10000, 100 );
     LOG_EXIT();
   }
@@ -98,27 +97,13 @@ public class GatewayLdapDynamicGroupFuncTest {
   public static void cleanupSuite() throws Exception {
     LOG_ENTER();
     gateway.stop();
-    ldap.stop( true );
+    driver.cleanup();
     //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
     //NoOpAppender.tearDown( appenders );
     LOG_EXIT();
   }
 
-  public static int setupLdap() throws Exception {
-    String basedir = System.getProperty("basedir");
-    if (basedir == null) {
-      basedir = new File(".").getCanonicalPath();
-    }
-    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users-dynamic.ldif");
-
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-    ldap.start();
-    LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-    return ldapTransport.getAcceptor().getLocalAddress().getPort();
-  }
-
-  public static void setupGateway(int ldapPort) throws IOException, Exception {
+  public static void setupGateway() throws IOException, Exception {
 
     File targetDir = new File( System.getProperty( "user.dir" ), "target" );
     File gatewayDir = new File( targetDir, "gateway-home-" + UUID.randomUUID() );
@@ -184,12 +169,12 @@ public class GatewayLdapDynamicGroupFuncTest {
 
     File descriptor = new File( topoDir, "testdg-cluster.xml" );
     FileOutputStream stream = new FileOutputStream( descriptor );
-    createTopology(ldapPort).toStream( stream );
+    createTopology().toStream( stream );
     stream.close();
 
   }
 
-  private static XMLTag createTopology(int ldapPort) {
+  private static XMLTag createTopology() {
     XMLTag xml = XMLDoc.newDocument( true )
         .addRoot( "topology" )
         .addTag( "gateway" )
@@ -212,7 +197,7 @@ public class GatewayLdapDynamicGroupFuncTest {
         .addTag( "value" ).addText( "simple" )
         .gotoParent().addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
-        .addTag( "value" ).addText( "ldap://localhost:"  + ldapPort)
+        .addTag( "value" ).addText( driver.getLdapUrl())
         .gotoParent().addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.userDnTemplate" )
         .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" )
@@ -325,5 +310,5 @@ public class GatewayLdapDynamicGroupFuncTest {
         .when().get( serviceUrl );
     LOG_EXIT();
   }
-  
+
 }

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLdapGroupFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLdapGroupFuncTest.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLdapGroupFuncTest.java
index 3945679..d34decc 100644
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLdapGroupFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLdapGroupFuncTest.java
@@ -30,20 +30,14 @@ import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.PrintStream;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
 import java.net.URL;
-import java.nio.file.FileSystems;
-import java.nio.file.Path;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.UUID;
 
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
 import org.apache.hadoop.gateway.config.GatewayConfig;
 import org.apache.hadoop.gateway.config.impl.GatewayConfigImpl;
-import org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer;
 import org.apache.hadoop.gateway.services.DefaultGatewayServices;
 import org.apache.hadoop.gateway.services.GatewayServices;
 import org.apache.hadoop.gateway.services.ServiceLifecycleException;
@@ -80,16 +74,14 @@ public class GatewayLdapGroupFuncTest {
   public static String gatewayUrl;
   public static String clusterUrl;
   public static String serviceUrl;
-  public static SimpleLdapDirectoryServer ldap;
-  public static TcpTransport ldapTransport;
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   @BeforeClass
   public static void setupSuite() throws Exception {
     LOG_ENTER();
     //appenders = NoOpAppender.setUp();
-    int port = setupLdap();
-    setupGateway(port);
-    TestUtils.awaitPortOpen( new InetSocketAddress( "localhost", port ), 10000, 100 );
+    driver.setupLdap(0);
+    setupGateway();
     TestUtils.awaitNon404HttpStatus( new URL( serviceUrl ), 10000, 100 );
     LOG_EXIT();
   }
@@ -98,27 +90,13 @@ public class GatewayLdapGroupFuncTest {
   public static void cleanupSuite() throws Exception {
     LOG_ENTER();
     gateway.stop();
-    ldap.stop( true );
+    driver.cleanup();
     //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
     //NoOpAppender.tearDown( appenders );
     LOG_EXIT();
   }
 
-  public static int setupLdap() throws Exception {
-    String basedir = System.getProperty("basedir");
-    if (basedir == null) {
-      basedir = new File(".").getCanonicalPath();
-    }
-    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
-
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-    ldap.start();
-    LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-    return ldapTransport.getAcceptor().getLocalAddress().getPort();
-  }
-
-  public static void setupGateway(int ldapPort) throws Exception {
+  public static void setupGateway() throws Exception {
 
     File targetDir = new File( System.getProperty( "user.dir" ), "target" );
     File gatewayDir = new File( targetDir, "gateway-home-" + UUID.randomUUID() );
@@ -185,11 +163,11 @@ public class GatewayLdapGroupFuncTest {
 
     File descriptor = new File( topoDir, "test-cluster.xml" );
     FileOutputStream stream = new FileOutputStream( descriptor );
-    createTopology(ldapPort).toStream( stream );
+    createTopology().toStream( stream );
     stream.close();
   }
 
-  private static XMLTag createTopology(int ldapPort) {
+  private static XMLTag createTopology() {
     XMLTag xml = XMLDoc.newDocument( true )
         .addRoot( "topology" )
         .addTag( "gateway" )
@@ -212,7 +190,7 @@ public class GatewayLdapGroupFuncTest {
         .addTag( "value" ).addText( "simple" )
         .gotoParent().addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
-        .addTag( "value" ).addText( "ldap://localhost:"  + ldapPort)
+        .addTag( "value" ).addText( driver.getLdapUrl())
         .gotoParent().addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.userDnTemplate" )
         .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" )

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLdapPosixGroupFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLdapPosixGroupFuncTest.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLdapPosixGroupFuncTest.java
index 586383d..4581623 100644
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLdapPosixGroupFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLdapPosixGroupFuncTest.java
@@ -19,9 +19,7 @@ package org.apache.hadoop.gateway;
 
 import com.mycila.xmltool.XMLDoc;
 import com.mycila.xmltool.XMLTag;
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
 import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer;
 import org.apache.hadoop.gateway.services.DefaultGatewayServices;
 import org.apache.hadoop.gateway.services.GatewayServices;
 import org.apache.hadoop.gateway.services.ServiceLifecycleException;
@@ -45,8 +43,6 @@ import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
 import java.net.URL;
 import java.util.Enumeration;
 import java.util.HashMap;
@@ -62,7 +58,7 @@ import static org.junit.Assert.assertThat;
 import static org.junit.Assert.fail;
 
 /**
- * Functional test to verify : looking up ldap groups from directory 
+ * Functional test to verify : looking up ldap groups from directory
  * and using them in acl authorization checks
  *
  */
@@ -78,16 +74,15 @@ public class GatewayLdapPosixGroupFuncTest {
   public static String gatewayUrl;
   public static String clusterUrl;
   public static String serviceUrl;
-  public static SimpleLdapDirectoryServer ldap;
-  public static TcpTransport ldapTransport;
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   @BeforeClass
   public static void setupSuite() throws Exception {
     LOG_ENTER();
     //appenders = NoOpAppender.setUp();
-    int port = setupLdap();
-    setupGateway(port);
-    TestUtils.awaitPortOpen( new InetSocketAddress( "localhost", port ), 10000, 100 );
+    URL usersUrl = getResourceUrl( "users.ldif" );
+    driver.setupLdap( 0, new File( usersUrl.toURI() ) );
+    setupGateway();
     TestUtils.awaitNon404HttpStatus( new URL( serviceUrl ), 10000, 100 );
     LOG_EXIT();
   }
@@ -96,22 +91,13 @@ public class GatewayLdapPosixGroupFuncTest {
   public static void cleanupSuite() throws Exception {
     LOG_ENTER();
     gateway.stop();
-    ldap.stop( true );
+    driver.cleanup();
     //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
     //NoOpAppender.tearDown( appenders );
     LOG_EXIT();
   }
 
-  public static int setupLdap() throws Exception {
-    URL usersUrl = getResourceUrl( "users.ldif" );
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", new File( usersUrl.toURI() ), ldapTransport );
-    ldap.start();
-    LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-    return ldapTransport.getAcceptor().getLocalAddress().getPort();
-  }
-
-  public static void setupGateway(int ldapPort) throws Exception {
+  public static void setupGateway() throws Exception {
 
     File targetDir = new File( System.getProperty( "user.dir" ), "target" );
     File gatewayDir = new File( targetDir, "gateway-home-" + UUID.randomUUID() );
@@ -155,12 +141,12 @@ public class GatewayLdapPosixGroupFuncTest {
 
     File descriptor = new File( topoDir, "test-cluster.xml" );
     OutputStream stream = new FileOutputStream( descriptor );
-    createTopology(ldapPort).toStream( stream );
+    createTopology().toStream( stream );
     stream.close();
 
   }
 
-  private static XMLTag createTopology(int ldapPort) {
+  private static XMLTag createTopology() {
     XMLTag xml = XMLDoc.newDocument( true )
         .addRoot( "topology" )
         .addTag( "gateway" )
@@ -183,7 +169,7 @@ public class GatewayLdapPosixGroupFuncTest {
         .addTag( "value" ).addText( "simple" )
         .gotoParent().addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
-        .addTag( "value" ).addText( "ldap://localhost:" + ldapPort )
+        .addTag( "value" ).addText( driver.getLdapUrl() )
         .gotoParent().addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.userDnTemplate" )
         .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" )

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLocalServiceFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLocalServiceFuncTest.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLocalServiceFuncTest.java
index fd88f6d..57e3bd5 100644
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLocalServiceFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayLocalServiceFuncTest.java
@@ -20,9 +20,7 @@ package org.apache.hadoop.gateway;
 import com.mycila.xmltool.XMLDoc;
 import com.mycila.xmltool.XMLTag;
 import org.apache.commons.io.FileUtils;
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
 import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer;
 import org.apache.hadoop.gateway.services.DefaultGatewayServices;
 import org.apache.hadoop.gateway.services.ServiceLifecycleException;
 import org.apache.hadoop.test.TestUtils;
@@ -41,10 +39,7 @@ import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import java.net.ServerSocket;
 import java.net.URL;
-import java.nio.file.FileSystems;
-import java.nio.file.Path;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Map;
@@ -67,14 +62,13 @@ public class GatewayLocalServiceFuncTest {
   public static GatewayServer gateway;
   public static String gatewayUrl;
   public static String clusterUrl;
-  public static SimpleLdapDirectoryServer ldap;
-  public static TcpTransport ldapTransport;
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   @BeforeClass
   public static void setupSuite() throws Exception {
     LOG_ENTER();
     appenders = NoOpAppender.setUp();
-    setupLdap();
+    driver.setupLdap(0);
     setupGateway();
     LOG_EXIT();
   }
@@ -83,26 +77,13 @@ public class GatewayLocalServiceFuncTest {
   public static void cleanupSuite() throws Exception {
     LOG_ENTER();
     gateway.stop();
-    ldap.stop( true );
+    driver.cleanup();
     FileUtils.deleteQuietly( new File( config.getGatewayConfDir() ) );
     FileUtils.deleteQuietly( new File( config.getGatewayDataDir() ) );
     NoOpAppender.tearDown( appenders );
     LOG_EXIT();
   }
 
-  public static void setupLdap() throws Exception {
-    String basedir = System.getProperty("basedir");
-    if (basedir == null) {
-      basedir = new File(".").getCanonicalPath();
-    }
-    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
-
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-    ldap.start();
-    LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-  }
-
   public static void setupGateway() throws Exception {
 
     File targetDir = new File( System.getProperty( "user.dir" ), "target" );
@@ -158,7 +139,7 @@ public class GatewayLocalServiceFuncTest {
         .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" ).gotoParent()
         .addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
-        .addTag( "value" ).addText( "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() ).gotoParent()
+        .addTag( "value" ).addText( driver.getLdapUrl() ).gotoParent()
         .addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.authenticationMechanism" )
         .addTag( "value" ).addText( "simple" ).gotoParent()

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayMultiFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayMultiFuncTest.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayMultiFuncTest.java
index 3901c34..47a8388 100644
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayMultiFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewayMultiFuncTest.java
@@ -20,8 +20,6 @@ package org.apache.hadoop.gateway;
 import java.io.File;
 import java.net.URL;
 import java.nio.charset.Charset;
-import java.nio.file.FileSystems;
-import java.nio.file.Path;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Map;
@@ -31,7 +29,6 @@ import java.util.UUID;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.IOUtils;
 import org.apache.directory.server.protocol.shared.transport.TcpTransport;
-import org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer;
 import org.apache.hadoop.gateway.services.DefaultGatewayServices;
 import org.apache.hadoop.gateway.services.GatewayServices;
 import org.apache.hadoop.gateway.services.ServiceLifecycleException;
@@ -86,16 +83,16 @@ public class GatewayMultiFuncTest {
   private static GatewayServer gateway;
   private static int gatewayPort;
   private static String gatewayUrl;
-  private static SimpleLdapDirectoryServer ldap;
   private static TcpTransport ldapTransport;
   private static Properties params;
   private static TopologyService topos;
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   @BeforeClass
   public static void setupSuite() throws Exception {
     LOG_ENTER();
     //appenders = NoOpAppender.setUp();
-    setupLdap();
+    driver.setupLdap(0);
     setupGateway();
     LOG_EXIT();
   }
@@ -104,25 +101,12 @@ public class GatewayMultiFuncTest {
   public static void cleanupSuite() throws Exception {
     LOG_ENTER();
     gateway.stop();
-    ldap.stop( true );
+    driver.cleanup();
     FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
     //NoOpAppender.tearDown( appenders );
     LOG_EXIT();
   }
 
-  public static void setupLdap() throws Exception {
-    String basedir = System.getProperty("basedir");
-    if (basedir == null) {
-      basedir = new File(".").getCanonicalPath();
-    }
-    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
-
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-    ldap.start();
-    LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-  }
-
   public static void setupGateway() throws Exception {
 
     File targetDir = new File( System.getProperty( "user.dir" ), "target" );
@@ -172,7 +156,7 @@ public class GatewayMultiFuncTest {
     LOG.info( "Gateway port = " + gateway.getAddresses()[ 0 ].getPort() );
 
     params = new Properties();
-    params.put( "LDAP_URL", "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() );
+    params.put( "LDAP_URL", driver.getLdapUrl() );
   }
 
   @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
@@ -182,7 +166,7 @@ public class GatewayMultiFuncTest {
     MockServer mock = new MockServer( "REPEAT", true );
 
     params = new Properties();
-    params.put( "LDAP_URL", "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() );
+    params.put( "LDAP_URL", driver.getLdapUrl() );
     params.put( "MOCK_SERVER_PORT", mock.getPort() );
 
     String topoStr = TestUtils.merge( DAT, "topologies/test-knox678-utf8-chars-topology.xml", params );
@@ -233,7 +217,7 @@ public class GatewayMultiFuncTest {
 
     params = new Properties();
     params.put( "MOCK_SERVER_PORT", mock.getPort() );
-    params.put( "LDAP_URL", "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() );
+    params.put( "LDAP_URL", driver.getLdapUrl() );
 
     String topoStr = TestUtils.merge( DAT, "topologies/test-knox678-utf8-chars-topology.xml", params );
     File topoFile = new File( config.getGatewayTopologyDir(), "knox681.xml" );
@@ -324,7 +308,7 @@ public class GatewayMultiFuncTest {
     String invalidPword = "invalid-guest-password";
 
     params = new Properties();
-    params.put( "LDAP_URL", "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() );
+    params.put( "LDAP_URL", driver.getLdapUrl() );
     params.put( "LDAP_SYSTEM_USERNAME", adminUName );
     params.put( "LDAP_SYSTEM_PASSWORD", adminPWord );
 

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewaySampleFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewaySampleFuncTest.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewaySampleFuncTest.java
index b1b37c8..dc84cbd 100644
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewaySampleFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewaySampleFuncTest.java
@@ -19,9 +19,7 @@ package org.apache.hadoop.gateway;
 
 import com.mycila.xmltool.XMLDoc;
 import com.mycila.xmltool.XMLTag;
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
 import org.apache.hadoop.gateway.config.GatewayConfig;
-import org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer;
 import org.apache.hadoop.gateway.services.DefaultGatewayServices;
 import org.apache.hadoop.gateway.services.ServiceLifecycleException;
 import org.apache.hadoop.test.TestUtils;
@@ -41,8 +39,6 @@ import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.URL;
-import java.nio.file.FileSystems;
-import java.nio.file.Path;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Map;
@@ -65,14 +61,13 @@ public class GatewaySampleFuncTest {
   public static GatewayServer gateway;
   public static String gatewayUrl;
   public static String clusterUrl;
-  public static SimpleLdapDirectoryServer ldap;
-  public static TcpTransport ldapTransport;
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   @BeforeClass
   public static void setupSuite() throws Exception {
     LOG_ENTER();
     //appenders = NoOpAppender.setUp();
-    setupLdap();
+    driver.setupLdap(0);
     setupGateway();
     LOG_EXIT();
   }
@@ -81,25 +76,12 @@ public class GatewaySampleFuncTest {
   public static void cleanupSuite() throws Exception {
     LOG_ENTER();
     gateway.stop();
-    ldap.stop( true );
+    driver.cleanup();
     //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
     //NoOpAppender.tearDown( appenders );
     LOG_EXIT();
   }
 
-  public static void setupLdap() throws Exception {
-    String basedir = System.getProperty("basedir");
-    if (basedir == null) {
-      basedir = new File(".").getCanonicalPath();
-    }
-    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
-
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-    ldap.start();
-    LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-  }
-
   public static void setupGateway() throws Exception {
 
     File targetDir = new File( System.getProperty( "user.dir" ), "target" );
@@ -156,7 +138,7 @@ public class GatewaySampleFuncTest {
         .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" ).gotoParent()
         .addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
-        .addTag( "value" ).addText( "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() ).gotoParent()
+        .addTag( "value" ).addText( driver.getLdapUrl() ).gotoParent()
         .addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.authenticationMechanism" )
         .addTag( "value" ).addText( "simple" ).gotoParent()

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewaySslFuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewaySslFuncTest.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewaySslFuncTest.java
index ed80f29..d2c2bf8 100644
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewaySslFuncTest.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/GatewaySslFuncTest.java
@@ -18,9 +18,6 @@
 package org.apache.hadoop.gateway;
 
 import java.io.File;
-import java.net.URL;
-import java.nio.file.FileSystems;
-import java.nio.file.Path;
 import java.security.KeyManagementException;
 import java.security.NoSuchAlgorithmException;
 import java.security.SecureRandom;
@@ -43,8 +40,6 @@ import javax.net.ssl.X509TrustManager;
 import javax.xml.transform.stream.StreamSource;
 
 import org.apache.commons.io.FileUtils;
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
-import org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer;
 import org.apache.hadoop.gateway.services.DefaultGatewayServices;
 import org.apache.hadoop.gateway.services.GatewayServices;
 import org.apache.hadoop.gateway.services.ServiceLifecycleException;
@@ -97,18 +92,16 @@ public class GatewaySslFuncTest {
   private static String gatewayScheme;
   private static int gatewayPort;
   private static String gatewayUrl;
-  private static SimpleLdapDirectoryServer ldap;
-  private static TcpTransport ldapTransport;
-  private static int ldapPort;
   private static Properties params;
   private static TopologyService topos;
   private static MockServer mockWebHdfs;
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   @BeforeClass
   public static void setupSuite() throws Exception {
     LOG_ENTER();
     //appenders = NoOpAppender.setUp();
-    setupLdap();
+    driver.setupLdap(0);
     setupGateway();
     LOG_EXIT();
   }
@@ -117,7 +110,7 @@ public class GatewaySslFuncTest {
   public static void cleanupSuite() throws Exception {
     LOG_ENTER();
     gateway.stop();
-    ldap.stop( true );
+    driver.cleanup();
     FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
     //NoOpAppender.tearDown( appenders );
     LOG_EXIT();
@@ -129,19 +122,6 @@ public class GatewaySslFuncTest {
     FileUtils.cleanDirectory( new File( config.getGatewayDeploymentDir() ) );
   }
 
-  public static void setupLdap() throws Exception {
-    String basedir = System.getProperty("basedir");
-    if (basedir == null) {
-      basedir = new File(".").getCanonicalPath();
-    }
-    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
-
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-    ldap.start();
-    LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-  }
-
   public static void setupGateway() throws Exception {
 
     File targetDir = new File( System.getProperty( "user.dir" ), "target" );
@@ -202,7 +182,7 @@ public class GatewaySslFuncTest {
     LOG.info( "Gateway port = " + gateway.getAddresses()[ 0 ].getPort() );
 
     params = new Properties();
-    params.put( "LDAP_URL", "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort() );
+    params.put( "LDAP_URL", driver.getLdapUrl() );
     params.put( "WEBHDFS_URL", "http://localhost:" + mockWebHdfs.getPort() );
   }
 

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/Knox242FuncTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/Knox242FuncTest.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/Knox242FuncTest.java
index 22278f2..1910d96 100755
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/Knox242FuncTest.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/Knox242FuncTest.java
@@ -24,14 +24,10 @@ import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.CoreMatchers.notNullValue;
 import static org.junit.Assert.assertThat;
 
-import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import java.io.PrintStream;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
 import java.net.URL;
 import java.nio.file.FileSystems;
 import java.nio.file.Path;
@@ -40,10 +36,8 @@ import java.util.HashMap;
 import java.util.Map;
 import java.util.UUID;
 
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
 import org.apache.hadoop.gateway.config.GatewayConfig;
 import org.apache.hadoop.gateway.config.impl.GatewayConfigImpl;
-import org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer;
 import org.apache.hadoop.gateway.services.DefaultGatewayServices;
 import org.apache.hadoop.gateway.services.GatewayServices;
 import org.apache.hadoop.gateway.services.ServiceLifecycleException;
@@ -81,16 +75,19 @@ public class Knox242FuncTest {
   public static String gatewayUrl;
   public static String clusterUrl;
   public static String serviceUrl;
-  public static SimpleLdapDirectoryServer ldap;
-  public static TcpTransport ldapTransport;
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   @BeforeClass
   public static void setupSuite() throws Exception {
     LOG_ENTER();
     //appenders = NoOpAppender.setUp();
-    int port = setupLdap();
-    setupGateway(port);
-    TestUtils.awaitPortOpen( new InetSocketAddress( "localhost", port ), 10000, 100 );
+    String basedir = System.getProperty("basedir");
+    if (basedir == null) {
+      basedir = new File(".").getCanonicalPath();
+    }
+    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users-dynamic.ldif");
+    driver.setupLdap( 0 , path.toFile() );
+    setupGateway();
     TestUtils.awaitNon404HttpStatus( new URL( serviceUrl ), 10000, 100 );
     LOG_EXIT();
   }
@@ -99,27 +96,13 @@ public class Knox242FuncTest {
   public static void cleanupSuite() throws Exception {
     LOG_ENTER();
     gateway.stop();
-    ldap.stop( true );
+    driver.cleanup();
     //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
     //NoOpAppender.tearDown( appenders );
     LOG_EXIT();
   }
 
-  public static int setupLdap() throws Exception {
-    String basedir = System.getProperty("basedir");
-    if (basedir == null) {
-      basedir = new File(".").getCanonicalPath();
-    }
-    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users-dynamic.ldif");
-
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-    ldap.start();
-    LOG.info( "LDAP port = " + ldapTransport.getPort() );
-    return ldapTransport.getAcceptor().getLocalAddress().getPort();
-  }
-
-  public static void setupGateway(int ldapPort) throws IOException, Exception {
+  public static void setupGateway() throws IOException, Exception {
 
     File targetDir = new File( System.getProperty( "user.dir" ), "target" );
     File gatewayDir = new File( targetDir, "gateway-home-" + UUID.randomUUID() );
@@ -163,11 +146,11 @@ public class Knox242FuncTest {
 
     File descriptor = new File( topoDir, "testdg-cluster.xml" );
     FileOutputStream stream = new FileOutputStream( descriptor );
-    createTopology(ldapPort).toStream( stream );
+    createTopology().toStream( stream );
     stream.close();
   }
 
-  private static XMLTag createTopology(int ldapPort) {
+  private static XMLTag createTopology() {
     XMLTag xml = XMLDoc.newDocument( true )
         .addRoot( "topology" )
         .addTag( "gateway" )
@@ -190,7 +173,7 @@ public class Knox242FuncTest {
         .addTag( "value" ).addText( "simple" )
         .gotoParent().addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.contextFactory.url" )
-        .addTag( "value" ).addText( "ldap://localhost:"  + ldapPort)
+        .addTag( "value" ).addText( driver.getLdapUrl())
         .gotoParent().addTag( "param" )
         .addTag( "name" ).addText( "main.ldapRealm.userDnTemplate" )
         .addTag( "value" ).addText( "uid={0},ou=people,dc=hadoop,dc=apache,dc=org" )
@@ -319,5 +302,5 @@ public class Knox242FuncTest {
         .when().get( serviceUrl );
     LOG_EXIT();
   }
-  
+
 }

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/KnoxCliLdapFuncTestNegative.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/KnoxCliLdapFuncTestNegative.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/KnoxCliLdapFuncTestNegative.java
index f1225b2..9cf171d 100644
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/KnoxCliLdapFuncTestNegative.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/KnoxCliLdapFuncTestNegative.java
@@ -20,8 +20,6 @@ package org.apache.hadoop.gateway;
 import com.mycila.xmltool.XMLDoc;
 import com.mycila.xmltool.XMLTag;
 import org.apache.commons.logging.impl.NoOpLog;
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
-import org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer;
 import org.apache.hadoop.gateway.services.DefaultGatewayServices;
 import org.apache.hadoop.gateway.services.ServiceLifecycleException;
 import org.apache.hadoop.gateway.util.KnoxCLI;
@@ -42,10 +40,7 @@ import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.ByteArrayOutputStream;
-import java.net.ServerSocket;
 import java.net.URL;
-import java.nio.file.FileSystems;
-import java.nio.file.Path;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Map;
@@ -67,8 +62,7 @@ public class KnoxCliLdapFuncTestNegative {
   public static GatewayServer gateway;
   public static String gatewayUrl;
   public static String clusterUrl;
-  public static SimpleLdapDirectoryServer ldap;
-  public static TcpTransport ldapTransport;
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   private static final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
   private static final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
@@ -79,7 +73,7 @@ public class KnoxCliLdapFuncTestNegative {
     LOG_ENTER();
     System.setOut(new PrintStream(outContent));
     System.setErr(new PrintStream(errContent));
-    setupLdap();
+    driver.setupLdap(0);
     setupGateway();
     LOG_EXIT();
   }
@@ -87,26 +81,13 @@ public class KnoxCliLdapFuncTestNegative {
   @AfterClass
   public static void cleanupSuite() throws Exception {
     LOG_ENTER();
-    ldap.stop( true );
+    driver.cleanup();
 
     //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
     //NoOpAppender.tearDown( appenders );
     LOG_EXIT();
   }
 
-  public static void setupLdap( ) throws Exception {
-    String basedir = System.getProperty("basedir");
-    if (basedir == null) {
-      basedir = new File(".").getCanonicalPath();
-    }
-    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
-
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-    ldap.start();
-    LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-  }
-
   public static void setupGateway() throws Exception {
 
     File targetDir = new File( System.getProperty( "user.dir" ), "target" );
@@ -189,7 +170,7 @@ public class KnoxCliLdapFuncTestNegative {
         .addTag("value").addText("uid={0},ou=people,dc=hadoop,dc=apache,dc=org").gotoParent()
         .addTag("param")
         .addTag( "name" ).addText("main.ldapRealm.contextFactory.url")
-        .addTag("value").addText("ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort()).gotoParent()
+        .addTag("value").addText(driver.getLdapUrl()).gotoParent()
         .addTag("param")
         .addTag("name").addText("main.ldapRealm.contextFactory.systemUsername")
         .addTag("value").addText("uid=guest,ou=people,dc=hadoop,dc=apache,dc=org").gotoParent()
@@ -256,7 +237,7 @@ public class KnoxCliLdapFuncTestNegative {
         .addTag("value").addText("uid={0},ou=people,dc=hadoop,dc=apache,dc=org").gotoParent()
         .addTag("param")
         .addTag("name").addText("main.ldapRealm.contextFactory.url")
-        .addTag("value").addText("ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort()).gotoParent()
+        .addTag("value").addText(driver.getLdapUrl()).gotoParent()
         .addTag("param")
         .addTag("name").addText("main.ldapRealm.contextFactory.authenticationMechanism")
         .addTag("value").addText("simple").gotoParent()

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/KnoxCliLdapFuncTestPositive.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/KnoxCliLdapFuncTestPositive.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/KnoxCliLdapFuncTestPositive.java
index 0402eb1..db2b2f6 100644
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/KnoxCliLdapFuncTestPositive.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/KnoxCliLdapFuncTestPositive.java
@@ -19,8 +19,6 @@ package org.apache.hadoop.gateway;
 
 import com.mycila.xmltool.XMLDoc;
 import com.mycila.xmltool.XMLTag;
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
-import org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer;
 import org.apache.hadoop.gateway.services.DefaultGatewayServices;
 import org.apache.hadoop.gateway.services.ServiceLifecycleException;
 import org.apache.hadoop.gateway.util.KnoxCLI;
@@ -40,10 +38,7 @@ import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.ByteArrayOutputStream;
-import java.net.ServerSocket;
 import java.net.URL;
-import java.nio.file.FileSystems;
-import java.nio.file.Path;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Map;
@@ -65,8 +60,7 @@ public class KnoxCliLdapFuncTestPositive {
   public static GatewayServer gateway;
   public static String gatewayUrl;
   public static String clusterUrl;
-  public static SimpleLdapDirectoryServer ldap;
-  public static TcpTransport ldapTransport;
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   private static final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
   private static final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
@@ -77,7 +71,7 @@ public class KnoxCliLdapFuncTestPositive {
     LOG_ENTER();
     System.setOut(new PrintStream(outContent));
     System.setErr(new PrintStream(errContent));
-    setupLdap();
+    driver.setupLdap(0);
     setupGateway();
     LOG_EXIT();
   }
@@ -85,26 +79,13 @@ public class KnoxCliLdapFuncTestPositive {
   @AfterClass
   public static void cleanupSuite() throws Exception {
     LOG_ENTER();
-    ldap.stop( true );
+    driver.cleanup();
 
     //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
     //NoOpAppender.tearDown( appenders );
     LOG_EXIT();
   }
 
-  public static void setupLdap( ) throws Exception {
-    String basedir = System.getProperty("basedir");
-    if (basedir == null) {
-      basedir = new File(".").getCanonicalPath();
-    }
-    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
-
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-    ldap.start();
-    LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-  }
-
   public static void setupGateway() throws Exception {
 
     File targetDir = new File( System.getProperty( "user.dir" ), "target" );
@@ -187,7 +168,7 @@ public class KnoxCliLdapFuncTestPositive {
         .addTag("value").addText("uid={0},ou=people,dc=hadoop,dc=apache,dc=org").gotoParent()
         .addTag( "param" )
         .addTag("name").addText("main.ldapRealm.contextFactory.url")
-        .addTag("value").addText("ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort()).gotoParent()
+        .addTag("value").addText(driver.getLdapUrl()).gotoParent()
         .addTag( "param" )
         .addTag("name").addText("main.ldapRealm.contextFactory.authenticationMechanism")
         .addTag("value").addText("simple").gotoParent()
@@ -250,7 +231,7 @@ public class KnoxCliLdapFuncTestPositive {
         .addTag("value").addText("uid={0},ou=people,dc=hadoop,dc=apache,dc=org").gotoParent()
         .addTag("param")
         .addTag("name").addText("main.ldapRealm.contextFactory.url")
-        .addTag("value").addText("ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort()).gotoParent()
+        .addTag("value").addText(driver.getLdapUrl()).gotoParent()
         .addTag("param")
         .addTag("name").addText("main.ldapRealm.contextFactory.authenticationMechanism")
         .addTag("value").addText("simple").gotoParent()

http://git-wip-us.apache.org/repos/asf/knox/blob/6657f2fd/gateway-test/src/test/java/org/apache/hadoop/gateway/KnoxCliSysBindTest.java
----------------------------------------------------------------------
diff --git a/gateway-test/src/test/java/org/apache/hadoop/gateway/KnoxCliSysBindTest.java b/gateway-test/src/test/java/org/apache/hadoop/gateway/KnoxCliSysBindTest.java
index bda5347..c9b94e7 100644
--- a/gateway-test/src/test/java/org/apache/hadoop/gateway/KnoxCliSysBindTest.java
+++ b/gateway-test/src/test/java/org/apache/hadoop/gateway/KnoxCliSysBindTest.java
@@ -19,8 +19,6 @@ package org.apache.hadoop.gateway;
 
 import com.mycila.xmltool.XMLDoc;
 import com.mycila.xmltool.XMLTag;
-import org.apache.directory.server.protocol.shared.transport.TcpTransport;
-import org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer;
 import org.apache.hadoop.gateway.services.DefaultGatewayServices;
 import org.apache.hadoop.gateway.services.ServiceLifecycleException;
 import org.apache.hadoop.gateway.util.KnoxCLI;
@@ -40,10 +38,7 @@ import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import java.net.ServerSocket;
 import java.net.URL;
-import java.nio.file.FileSystems;
-import java.nio.file.Path;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Map;
@@ -64,8 +59,7 @@ public class KnoxCliSysBindTest {
   public static GatewayServer gateway;
   public static String gatewayUrl;
   public static String clusterUrl;
-  public static SimpleLdapDirectoryServer ldap;
-  public static TcpTransport ldapTransport;
+  private static GatewayTestDriver driver = new GatewayTestDriver();
 
   private static final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
   private static final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
@@ -76,7 +70,7 @@ public class KnoxCliSysBindTest {
     LOG_ENTER();
     System.setOut(new PrintStream(outContent));
     System.setErr(new PrintStream(errContent));
-    setupLdap();
+    driver.setupLdap(0);
     setupGateway();
     LOG_EXIT();
   }
@@ -84,26 +78,13 @@ public class KnoxCliSysBindTest {
   @AfterClass
   public static void cleanupSuite() throws Exception {
     LOG_ENTER();
-    ldap.stop( true );
+    driver.cleanup();
 
     //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
     //NoOpAppender.tearDown( appenders );
     LOG_EXIT();
   }
 
-  public static void setupLdap( ) throws Exception {
-    String basedir = System.getProperty("basedir");
-    if (basedir == null) {
-      basedir = new File(".").getCanonicalPath();
-    }
-    Path path = FileSystems.getDefault().getPath(basedir, "/src/test/resources/users.ldif");
-
-    ldapTransport = new TcpTransport( 0 );
-    ldap = new SimpleLdapDirectoryServer( "dc=hadoop,dc=apache,dc=org", path.toFile(), ldapTransport );
-    ldap.start();
-    LOG.info( "LDAP port = " + ldapTransport.getAcceptor().getLocalAddress().getPort() );
-  }
-
   public static void setupGateway() throws Exception {
 
     File targetDir = new File( System.getProperty( "user.dir" ), "target" );
@@ -191,7 +172,7 @@ public class KnoxCliSysBindTest {
         .addTag("value").addText("uid={0},ou=people,dc=hadoop,dc=apache,dc=org").gotoParent()
         .addTag( "param" )
         .addTag("name").addText("main.ldapRealm.contextFactory.url")
-        .addTag("value").addText("ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort()).gotoParent()
+        .addTag("value").addText(driver.getLdapUrl()).gotoParent()
         .addTag( "param" )
         .addTag("name").addText("main.ldapRealm.contextFactory.authenticationMechanism")
         .addTag("value").addText("simple").gotoParent()
@@ -254,7 +235,7 @@ public class KnoxCliSysBindTest {
         .addTag("value").addText("uid={0},ou=people,dc=hadoop,dc=apache,dc=org").gotoParent()
         .addTag("param")
         .addTag("name").addText("main.ldapRealm.contextFactory.url")
-        .addTag("value").addText("ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort()).gotoParent()
+        .addTag("value").addText(driver.getLdapUrl()).gotoParent()
         .addTag("param")
         .addTag("name").addText("main.ldapRealm.contextFactory.authenticationMechanism")
         .addTag("value").addText("simple").gotoParent()


[13/64] [partial] knox git commit: KNOX-998 - Refactoring save 1

Posted by mo...@apache.org.
http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authc-anon/src/test/java/org/apache/knox/gateway/deploy/AnonymousAuthDeploymentContributorTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authc-anon/src/test/java/org/apache/knox/gateway/deploy/AnonymousAuthDeploymentContributorTest.java b/gateway-provider-security-authc-anon/src/test/java/org/apache/knox/gateway/deploy/AnonymousAuthDeploymentContributorTest.java
new file mode 100644
index 0000000..c1d8fcb
--- /dev/null
+++ b/gateway-provider-security-authc-anon/src/test/java/org/apache/knox/gateway/deploy/AnonymousAuthDeploymentContributorTest.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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.deploy;
+
+import org.junit.Test;
+
+import java.util.Iterator;
+import java.util.ServiceLoader;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.fail;
+
+public class AnonymousAuthDeploymentContributorTest {
+
+  @Test
+  public void testServiceLoader() throws Exception {
+    ServiceLoader loader = ServiceLoader.load( ProviderDeploymentContributor.class );
+    Iterator iterator = loader.iterator();
+    assertThat( "Service iterator empty.", iterator.hasNext() );
+    while( iterator.hasNext() ) {
+      Object object = iterator.next();
+      if( object instanceof AnonymousAuthDeploymentContributor ) {
+        return;
+      }
+    }
+    fail( "Failed to find " + AnonymousAuthDeploymentContributor.class.getName() + " via service loader." );
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/deploy/impl/AclsAuthzDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/deploy/impl/AclsAuthzDeploymentContributor.java b/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/deploy/impl/AclsAuthzDeploymentContributor.java
deleted file mode 100644
index 2c150e3..0000000
--- a/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/deploy/impl/AclsAuthzDeploymentContributor.java
+++ /dev/null
@@ -1,75 +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.hadoop.gateway.deploy.impl;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.services.security.KeystoreService;
-import org.apache.hadoop.gateway.services.security.KeystoreServiceException;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-public class AclsAuthzDeploymentContributor extends ProviderDeploymentContributorBase {
-
-  private static final String FILTER_CLASSNAME = "org.apache.hadoop.gateway.filter.AclsAuthorizationFilter";
-
-  @Override
-  public String getRole() {
-    return "authorization";
-  }
-
-  @Override
-  public String getName() {
-    return "AclsAuthz";
-  }
-
-  @Override
-  public void initializeContribution(DeploymentContext context) {
-    super.initializeContribution(context);
-  }
-
-  @Override
-  public void contributeProvider( DeploymentContext context, Provider provider ) {
-  }
-
-  @Override
-  public void contributeFilter( DeploymentContext context, Provider provider, Service service, 
-      ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
-    if (params == null) {
-      params = new ArrayList<FilterParamDescriptor>();
-    }
-    // add resource role to params so that we can determine the acls to enforce at runtime
-    params.add( resource.createFilterParam().name( "resource.role" ).value(resource.role() ) );
-
-    // blindly add all the provider params as filter init params
-    // this will include any {resource.role}-ACLS parameters to be enforced - such as NAMENODE-ACLS
-    Map<String, String> providerParams = provider.getParams();
-    for(Entry<String, String> entry : providerParams.entrySet()) {
-      params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
-    }
-
-    resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclParser.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclParser.java b/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclParser.java
deleted file mode 100644
index 13499c3..0000000
--- a/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclParser.java
+++ /dev/null
@@ -1,85 +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.hadoop.gateway.filter;
-
-import java.util.ArrayList;
-import java.util.Collections;
-
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.util.IpAddressValidator;
-
-/**
- */
-public class AclParser {
-  private static AclsAuthorizationMessages log = MessagesFactory.get( AclsAuthorizationMessages.class );
-
-  public String resourceRole;
-  public ArrayList<String> users;
-  public ArrayList<String> groups;
-  public boolean anyUser = true;
-  public boolean anyGroup = true;
-  public IpAddressValidator ipv;
-
-
-  public AclParser() {
-  }
-  
-  public void parseAcls(String resourceRole, String acls) throws InvalidACLException {
-    if (acls != null) {
-      String[] parts = acls.split(";");
-      if (parts.length != 3) {
-        log.invalidAclsFoundForResource(resourceRole);
-        throw new InvalidACLException("Invalid ACLs specified for requested resource: " + resourceRole);
-      }
-      else {
-        log.aclsFoundForResource(resourceRole);
-      }
-      parseUserAcls(parts);
-      
-      parseGroupAcls(parts);
-
-      parseIpAddressAcls(parts);
-    }
-    else {
-      log.noAclsFoundForResource(resourceRole);
-      users = new ArrayList<String>();
-      groups = new ArrayList<String>();
-      ipv = new IpAddressValidator(null);
-    }
-  }
-
-  private void parseUserAcls(String[] parts) {
-    users = new ArrayList<String>();
-    Collections.addAll(users, parts[0].split(","));
-    if (!users.contains("*")) {
-      anyUser = false;
-    }
-  }
-
-  private void parseGroupAcls(String[] parts) {
-    groups = new ArrayList<String>();
-    Collections.addAll(groups, parts[1].split(","));
-    if (!groups.contains("*")) {
-      anyGroup = false;
-    }
-  }
-
-  private void parseIpAddressAcls(String[] parts) {
-    ipv = new IpAddressValidator(parts[2]);
-  }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclsAuthorizationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclsAuthorizationFilter.java b/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclsAuthorizationFilter.java
deleted file mode 100644
index 343d87f..0000000
--- a/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclsAuthorizationFilter.java
+++ /dev/null
@@ -1,216 +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.hadoop.gateway.filter;
-
-import javax.security.auth.Subject;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.hadoop.gateway.audit.api.Action;
-import org.apache.hadoop.gateway.audit.api.ActionOutcome;
-import org.apache.hadoop.gateway.audit.api.AuditServiceFactory;
-import org.apache.hadoop.gateway.audit.api.Auditor;
-import org.apache.hadoop.gateway.audit.api.ResourceType;
-import org.apache.hadoop.gateway.audit.log4j.audit.AuditConstants;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.security.GroupPrincipal;
-import org.apache.hadoop.gateway.security.ImpersonatedPrincipal;
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.apache.hadoop.gateway.util.IpAddressValidator;
-import org.apache.hadoop.gateway.util.urltemplate.Template;
-
-import java.io.IOException;
-import java.security.AccessController;
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.Collections;
-
-public class AclsAuthorizationFilter implements Filter {
-  private static AclsAuthorizationMessages log = MessagesFactory.get( AclsAuthorizationMessages.class );
-  private static Auditor auditor = AuditServiceFactory.getAuditService().getAuditor( AuditConstants.DEFAULT_AUDITOR_NAME,
-          AuditConstants.KNOX_SERVICE_NAME, AuditConstants.KNOX_COMPONENT_NAME );
-
-  private String resourceRole = null;
-  private String aclProcessingMode = null;
-  private AclParser parser = new AclParser();
-
-  
-  @Override
-  public void init(FilterConfig filterConfig) throws ServletException {
-    resourceRole = getInitParameter(filterConfig, "resource.role");
-    log.initializingForResourceRole(resourceRole);
-    aclProcessingMode = getInitParameter(filterConfig, resourceRole + ".acl.mode");
-    if (aclProcessingMode == null) {
-      aclProcessingMode = getInitParameter(filterConfig, "acl.mode");
-      if (aclProcessingMode == null) {
-        aclProcessingMode = "AND";
-      }
-    }
-    log.aclProcessingMode(aclProcessingMode);
-    String acls = getInitParameter(filterConfig, resourceRole + ".acl");
-    parser.parseAcls(resourceRole, acls);
-  }
-
-  private String getInitParameter(FilterConfig filterConfig, String paramName) {
-    return filterConfig.getInitParameter(paramName.toLowerCase());
-  }
-
-  public void destroy() {
-  }
-
-  public void doFilter(ServletRequest request, ServletResponse response,
-      FilterChain chain) throws IOException, ServletException {
-    boolean accessGranted = enforceAclAuthorizationPolicy(request, response, chain);
-    log.accessGranted(accessGranted);
-    String sourceUrl = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
-    if (accessGranted) {
-      auditor.audit( Action.AUTHORIZATION, sourceUrl, ResourceType.URI, ActionOutcome.SUCCESS );
-      chain.doFilter(request, response);
-    }
-    else {
-      auditor.audit( Action.AUTHORIZATION, sourceUrl, ResourceType.URI, ActionOutcome.FAILURE );
-      sendForbidden((HttpServletResponse) response);
-    }
-  }
-
-  private boolean enforceAclAuthorizationPolicy(ServletRequest request,
-      ServletResponse response, FilterChain chain) {
-    HttpServletRequest req = (HttpServletRequest) request;
-    
-    // before enforcing acls check whether there are no acls defined 
-    // which would mean that there are no restrictions
-    if (parser.users.size() == 0 && parser.groups.size() == 0 && parser.ipv.getIPAddresses().size() == 0) {
-      return true;
-    }
-
-    boolean userAccess = false;
-    boolean groupAccess = false;
-    boolean ipAddrAccess = false;
-    
-    Subject subject = Subject.getSubject(AccessController.getContext());
-    Principal primaryPrincipal = (Principal)subject.getPrincipals(PrimaryPrincipal.class).toArray()[0];
-    log.primaryPrincipal(primaryPrincipal.getName());
-    Object[] impersonations = subject.getPrincipals(ImpersonatedPrincipal.class).toArray();
-    if (impersonations.length > 0) {
-      log.impersonatedPrincipal(((Principal)impersonations[0]).getName());
-      userAccess = checkUserAcls((Principal)impersonations[0]);
-      log.impersonatedPrincipalHasAccess(userAccess);
-    }
-    else {
-      userAccess = checkUserAcls(primaryPrincipal);
-      log.primaryPrincipalHasAccess(userAccess);
-    }
-    Object[] groups = subject.getPrincipals(GroupPrincipal.class).toArray();
-    if (groups.length > 0) {
-//      System.out.println("GroupPrincipal: " + ((Principal)groups[0]).getName());
-      groupAccess = checkGroupAcls(groups);
-      log.groupPrincipalHasAccess(groupAccess);
-    }
-    else {
-      // if we have no groups in the subject then make
-      // it true if there is an anyGroup acl
-      // for AND mode and acls like *;*;127.0.0.* we need to
-      // make it pass
-      if (parser.anyGroup && aclProcessingMode.equals("AND")) {
-        groupAccess = true;
-      }
-    }
-    log.remoteIPAddress(req.getRemoteAddr());
-    ipAddrAccess = checkRemoteIpAcls(req.getRemoteAddr());
-    log.remoteIPAddressHasAccess(ipAddrAccess);
-    
-    if (aclProcessingMode.equals("OR")) {
-      // need to interpret '*' as excluded for OR semantics
-      // to make sense and not grant access to everyone by mistake.
-      // exclusion in OR is equivalent to denied
-      // so, let's set each one that contains '*' to false.
-      if (parser.anyUser) userAccess = false;
-      if (parser.anyGroup) groupAccess = false;
-      if (parser.ipv.allowsAnyIP()) ipAddrAccess = false;
-      
-      return (userAccess || groupAccess || ipAddrAccess);
-    }
-    else if (aclProcessingMode.equals("AND")) {
-      return (userAccess && groupAccess && ipAddrAccess);
-    }
-    return false;
-  }
-
-  private boolean checkRemoteIpAcls(String remoteAddr) {
-    boolean allowed = false;
-    if (remoteAddr == null) {
-      return false;
-    }
-    allowed = parser.ipv.validateIpAddress(remoteAddr);
-    return allowed;
-  }
-
-  private boolean checkUserAcls(Principal user) {
-    boolean allowed = false;
-    if (user == null) {
-      return false;
-    }
-    if (parser.anyUser) {
-      allowed = true;
-    }
-    else {
-      if (parser.users.contains(user.getName())) {
-        allowed = true;
-      }
-    }
-    return allowed;
-  }
-
-  private boolean checkGroupAcls(Object[] userGroups) {
-    boolean allowed = false;
-    if (userGroups == null) {
-      return false;
-    }
-    if (parser.anyGroup) {
-      allowed = true;
-    }
-    else {
-      for (int i = 0; i < userGroups.length; i++) {
-        if (parser.groups.contains(((Principal)userGroups[i]).getName())) {
-          allowed = true;
-          break;
-        }
-      }
-    }
-    return allowed;
-  }
-
-  private void sendForbidden(HttpServletResponse res) {
-    sendErrorCode(res, 403);
-  }
-
-  private void sendErrorCode(HttpServletResponse res, int code) {
-    try {
-      res.sendError(code);
-    } catch (IOException e) {
-      // TODO: log appropriately
-      e.printStackTrace();
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclsAuthorizationMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclsAuthorizationMessages.java b/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclsAuthorizationMessages.java
deleted file mode 100644
index 071375d..0000000
--- a/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclsAuthorizationMessages.java
+++ /dev/null
@@ -1,66 +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.hadoop.gateway.filter;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-import org.apache.hadoop.gateway.i18n.messages.StackTrace;
-
-@Messages(logger="org.apache.hadoop.gateway")
-public interface AclsAuthorizationMessages {
-
-  @Message( level = MessageLevel.INFO, text = "Initializing AclsAuthz Provider for: {0}" )
-  void initializingForResourceRole(String resourceRole);
-
-  @Message( level = MessageLevel.DEBUG, text = "ACL Processing Mode is: {0}" )
-  void aclProcessingMode(String aclProcessingMode);
-
-  @Message( level = MessageLevel.WARN, text = "Invalid ACLs found for: {0}" )
-  void invalidAclsFoundForResource(String resourceRole);
-
-  @Message( level = MessageLevel.INFO, text = "ACLs found for: {0}" )
-  void aclsFoundForResource(String resourceRole);
-
-  @Message( level = MessageLevel.DEBUG, text = "No ACLs found for: {0}" )
-  void noAclsFoundForResource(String resourceRole);
-
-  @Message( level = MessageLevel.INFO, text = "Access Granted: {0}" )
-  void accessGranted(boolean accessGranted);
-
-  @Message( level = MessageLevel.DEBUG, text = "PrimaryPrincipal: {0}" )
-  void primaryPrincipal(String name);
-
-  @Message( level = MessageLevel.DEBUG, text = "ImpersonatedPrincipal: {0}" )
-  void impersonatedPrincipal(String name);
-
-  @Message( level = MessageLevel.DEBUG, text = "ImpersonatedPrincipal has access: {0}" )
-  void impersonatedPrincipalHasAccess(boolean userAccess);
-
-  @Message( level = MessageLevel.DEBUG, text = "PrimaryPrincipal has access: {0}" )
-  void primaryPrincipalHasAccess(boolean userAccess);
-
-  @Message( level = MessageLevel.DEBUG, text = "GroupPrincipal has access: {0}" )
-  void groupPrincipalHasAccess(boolean groupAccess);
-
-  @Message( level = MessageLevel.DEBUG, text = "Remote IP Address: {0}" )
-  void remoteIPAddress(String remoteAddr);
-
-  @Message( level = MessageLevel.DEBUG, text = "Remote IP Address has access: {0}" )
-  void remoteIPAddressHasAccess(boolean remoteIpAccess);
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclsAuthorizationResources.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclsAuthorizationResources.java b/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclsAuthorizationResources.java
deleted file mode 100644
index 370336b..0000000
--- a/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/AclsAuthorizationResources.java
+++ /dev/null
@@ -1,27 +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.hadoop.gateway.filter;
-
-import org.apache.hadoop.gateway.i18n.resources.Resource;
-import org.apache.hadoop.gateway.i18n.resources.Resources;
-
-@Resources
-public interface AclsAuthorizationResources {
-  @Resource( text = "Response status: {0}" )
-  String responseStatus( int status );
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/InvalidACLException.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/InvalidACLException.java b/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/InvalidACLException.java
deleted file mode 100644
index 34a4ba1..0000000
--- a/gateway-provider-security-authz-acls/src/main/java/org/apache/hadoop/gateway/filter/InvalidACLException.java
+++ /dev/null
@@ -1,31 +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.hadoop.gateway.filter;
-
-/**
- * invalid ACL configuration item
- */
-public class InvalidACLException extends RuntimeException {
-
-  private static final long serialVersionUID = -4284269372393774095L;
-
-  public InvalidACLException(String message) {
-    super(message);
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/deploy/impl/AclsAuthzDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/deploy/impl/AclsAuthzDeploymentContributor.java b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/deploy/impl/AclsAuthzDeploymentContributor.java
new file mode 100644
index 0000000..fc5e549
--- /dev/null
+++ b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/deploy/impl/AclsAuthzDeploymentContributor.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.knox.gateway.deploy.impl;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+public class AclsAuthzDeploymentContributor extends ProviderDeploymentContributorBase {
+
+  private static final String FILTER_CLASSNAME = "AclsAuthorizationFilter";
+
+  @Override
+  public String getRole() {
+    return "authorization";
+  }
+
+  @Override
+  public String getName() {
+    return "AclsAuthz";
+  }
+
+  @Override
+  public void initializeContribution(DeploymentContext context) {
+    super.initializeContribution(context);
+  }
+
+  @Override
+  public void contributeProvider( DeploymentContext context, Provider provider ) {
+  }
+
+  @Override
+  public void contributeFilter( DeploymentContext context, Provider provider, Service service, 
+      ResourceDescriptor resource, List<FilterParamDescriptor> params ) {
+    if (params == null) {
+      params = new ArrayList<FilterParamDescriptor>();
+    }
+    // add resource role to params so that we can determine the acls to enforce at runtime
+    params.add( resource.createFilterParam().name( "resource.role" ).value(resource.role() ) );
+
+    // blindly add all the provider params as filter init params
+    // this will include any {resource.role}-ACLS parameters to be enforced - such as NAMENODE-ACLS
+    Map<String, String> providerParams = provider.getParams();
+    for(Entry<String, String> entry : providerParams.entrySet()) {
+      params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
+    }
+
+    resource.addFilter().name( getName() ).role( getRole() ).impl( FILTER_CLASSNAME ).params( params );
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclParser.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclParser.java b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclParser.java
new file mode 100644
index 0000000..ceac18e
--- /dev/null
+++ b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclParser.java
@@ -0,0 +1,85 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter;
+
+import java.util.ArrayList;
+import java.util.Collections;
+
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.util.IpAddressValidator;
+
+/**
+ */
+public class AclParser {
+  private static AclsAuthorizationMessages log = MessagesFactory.get( AclsAuthorizationMessages.class );
+
+  public String resourceRole;
+  public ArrayList<String> users;
+  public ArrayList<String> groups;
+  public boolean anyUser = true;
+  public boolean anyGroup = true;
+  public IpAddressValidator ipv;
+
+
+  public AclParser() {
+  }
+  
+  public void parseAcls(String resourceRole, String acls) throws InvalidACLException {
+    if (acls != null) {
+      String[] parts = acls.split(";");
+      if (parts.length != 3) {
+        log.invalidAclsFoundForResource(resourceRole);
+        throw new InvalidACLException("Invalid ACLs specified for requested resource: " + resourceRole);
+      }
+      else {
+        log.aclsFoundForResource(resourceRole);
+      }
+      parseUserAcls(parts);
+      
+      parseGroupAcls(parts);
+
+      parseIpAddressAcls(parts);
+    }
+    else {
+      log.noAclsFoundForResource(resourceRole);
+      users = new ArrayList<String>();
+      groups = new ArrayList<String>();
+      ipv = new IpAddressValidator(null);
+    }
+  }
+
+  private void parseUserAcls(String[] parts) {
+    users = new ArrayList<String>();
+    Collections.addAll(users, parts[0].split(","));
+    if (!users.contains("*")) {
+      anyUser = false;
+    }
+  }
+
+  private void parseGroupAcls(String[] parts) {
+    groups = new ArrayList<String>();
+    Collections.addAll(groups, parts[1].split(","));
+    if (!groups.contains("*")) {
+      anyGroup = false;
+    }
+  }
+
+  private void parseIpAddressAcls(String[] parts) {
+    ipv = new IpAddressValidator(parts[2]);
+  }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationFilter.java b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationFilter.java
new file mode 100644
index 0000000..0002974
--- /dev/null
+++ b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationFilter.java
@@ -0,0 +1,212 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter;
+
+import javax.security.auth.Subject;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.knox.gateway.audit.api.Action;
+import org.apache.knox.gateway.audit.api.ActionOutcome;
+import org.apache.knox.gateway.audit.api.AuditServiceFactory;
+import org.apache.knox.gateway.audit.api.Auditor;
+import org.apache.knox.gateway.audit.api.ResourceType;
+import org.apache.knox.gateway.audit.log4j.audit.AuditConstants;
+import org.apache.knox.gateway.i18n.messages.MessagesFactory;
+import org.apache.knox.gateway.security.GroupPrincipal;
+import org.apache.knox.gateway.security.ImpersonatedPrincipal;
+import org.apache.knox.gateway.security.PrimaryPrincipal;
+
+import java.io.IOException;
+import java.security.AccessController;
+import java.security.Principal;
+
+public class AclsAuthorizationFilter implements Filter {
+  private static AclsAuthorizationMessages log = MessagesFactory.get( AclsAuthorizationMessages.class );
+  private static Auditor auditor = AuditServiceFactory.getAuditService().getAuditor( AuditConstants.DEFAULT_AUDITOR_NAME,
+          AuditConstants.KNOX_SERVICE_NAME, AuditConstants.KNOX_COMPONENT_NAME );
+
+  private String resourceRole = null;
+  private String aclProcessingMode = null;
+  private AclParser parser = new AclParser();
+
+  
+  @Override
+  public void init(FilterConfig filterConfig) throws ServletException {
+    resourceRole = getInitParameter(filterConfig, "resource.role");
+    log.initializingForResourceRole(resourceRole);
+    aclProcessingMode = getInitParameter(filterConfig, resourceRole + ".acl.mode");
+    if (aclProcessingMode == null) {
+      aclProcessingMode = getInitParameter(filterConfig, "acl.mode");
+      if (aclProcessingMode == null) {
+        aclProcessingMode = "AND";
+      }
+    }
+    log.aclProcessingMode(aclProcessingMode);
+    String acls = getInitParameter(filterConfig, resourceRole + ".acl");
+    parser.parseAcls(resourceRole, acls);
+  }
+
+  private String getInitParameter(FilterConfig filterConfig, String paramName) {
+    return filterConfig.getInitParameter(paramName.toLowerCase());
+  }
+
+  public void destroy() {
+  }
+
+  public void doFilter(ServletRequest request, ServletResponse response,
+      FilterChain chain) throws IOException, ServletException {
+    boolean accessGranted = enforceAclAuthorizationPolicy(request, response, chain);
+    log.accessGranted(accessGranted);
+    String sourceUrl = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
+    if (accessGranted) {
+      auditor.audit( Action.AUTHORIZATION, sourceUrl, ResourceType.URI, ActionOutcome.SUCCESS );
+      chain.doFilter(request, response);
+    }
+    else {
+      auditor.audit( Action.AUTHORIZATION, sourceUrl, ResourceType.URI, ActionOutcome.FAILURE );
+      sendForbidden((HttpServletResponse) response);
+    }
+  }
+
+  private boolean enforceAclAuthorizationPolicy(ServletRequest request,
+      ServletResponse response, FilterChain chain) {
+    HttpServletRequest req = (HttpServletRequest) request;
+    
+    // before enforcing acls check whether there are no acls defined 
+    // which would mean that there are no restrictions
+    if (parser.users.size() == 0 && parser.groups.size() == 0 && parser.ipv.getIPAddresses().size() == 0) {
+      return true;
+    }
+
+    boolean userAccess = false;
+    boolean groupAccess = false;
+    boolean ipAddrAccess = false;
+    
+    Subject subject = Subject.getSubject(AccessController.getContext());
+    Principal primaryPrincipal = (Principal)subject.getPrincipals(PrimaryPrincipal.class).toArray()[0];
+    log.primaryPrincipal(primaryPrincipal.getName());
+    Object[] impersonations = subject.getPrincipals(ImpersonatedPrincipal.class).toArray();
+    if (impersonations.length > 0) {
+      log.impersonatedPrincipal(((Principal)impersonations[0]).getName());
+      userAccess = checkUserAcls((Principal)impersonations[0]);
+      log.impersonatedPrincipalHasAccess(userAccess);
+    }
+    else {
+      userAccess = checkUserAcls(primaryPrincipal);
+      log.primaryPrincipalHasAccess(userAccess);
+    }
+    Object[] groups = subject.getPrincipals(GroupPrincipal.class).toArray();
+    if (groups.length > 0) {
+//      System.out.println("GroupPrincipal: " + ((Principal)groups[0]).getName());
+      groupAccess = checkGroupAcls(groups);
+      log.groupPrincipalHasAccess(groupAccess);
+    }
+    else {
+      // if we have no groups in the subject then make
+      // it true if there is an anyGroup acl
+      // for AND mode and acls like *;*;127.0.0.* we need to
+      // make it pass
+      if (parser.anyGroup && aclProcessingMode.equals("AND")) {
+        groupAccess = true;
+      }
+    }
+    log.remoteIPAddress(req.getRemoteAddr());
+    ipAddrAccess = checkRemoteIpAcls(req.getRemoteAddr());
+    log.remoteIPAddressHasAccess(ipAddrAccess);
+    
+    if (aclProcessingMode.equals("OR")) {
+      // need to interpret '*' as excluded for OR semantics
+      // to make sense and not grant access to everyone by mistake.
+      // exclusion in OR is equivalent to denied
+      // so, let's set each one that contains '*' to false.
+      if (parser.anyUser) userAccess = false;
+      if (parser.anyGroup) groupAccess = false;
+      if (parser.ipv.allowsAnyIP()) ipAddrAccess = false;
+      
+      return (userAccess || groupAccess || ipAddrAccess);
+    }
+    else if (aclProcessingMode.equals("AND")) {
+      return (userAccess && groupAccess && ipAddrAccess);
+    }
+    return false;
+  }
+
+  private boolean checkRemoteIpAcls(String remoteAddr) {
+    boolean allowed = false;
+    if (remoteAddr == null) {
+      return false;
+    }
+    allowed = parser.ipv.validateIpAddress(remoteAddr);
+    return allowed;
+  }
+
+  private boolean checkUserAcls(Principal user) {
+    boolean allowed = false;
+    if (user == null) {
+      return false;
+    }
+    if (parser.anyUser) {
+      allowed = true;
+    }
+    else {
+      if (parser.users.contains(user.getName())) {
+        allowed = true;
+      }
+    }
+    return allowed;
+  }
+
+  private boolean checkGroupAcls(Object[] userGroups) {
+    boolean allowed = false;
+    if (userGroups == null) {
+      return false;
+    }
+    if (parser.anyGroup) {
+      allowed = true;
+    }
+    else {
+      for (int i = 0; i < userGroups.length; i++) {
+        if (parser.groups.contains(((Principal)userGroups[i]).getName())) {
+          allowed = true;
+          break;
+        }
+      }
+    }
+    return allowed;
+  }
+
+  private void sendForbidden(HttpServletResponse res) {
+    sendErrorCode(res, 403);
+  }
+
+  private void sendErrorCode(HttpServletResponse res, int code) {
+    try {
+      res.sendError(code);
+    } catch (IOException e) {
+      // TODO: log appropriately
+      e.printStackTrace();
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationMessages.java b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationMessages.java
new file mode 100644
index 0000000..206348d
--- /dev/null
+++ b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationMessages.java
@@ -0,0 +1,65 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter;
+
+import org.apache.knox.gateway.i18n.messages.Message;
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.Messages;
+
+@Messages(logger="org.apache.hadoop.gateway")
+public interface AclsAuthorizationMessages {
+
+  @Message( level = MessageLevel.INFO, text = "Initializing AclsAuthz Provider for: {0}" )
+  void initializingForResourceRole(String resourceRole);
+
+  @Message( level = MessageLevel.DEBUG, text = "ACL Processing Mode is: {0}" )
+  void aclProcessingMode(String aclProcessingMode);
+
+  @Message( level = MessageLevel.WARN, text = "Invalid ACLs found for: {0}" )
+  void invalidAclsFoundForResource(String resourceRole);
+
+  @Message( level = MessageLevel.INFO, text = "ACLs found for: {0}" )
+  void aclsFoundForResource(String resourceRole);
+
+  @Message( level = MessageLevel.DEBUG, text = "No ACLs found for: {0}" )
+  void noAclsFoundForResource(String resourceRole);
+
+  @Message( level = MessageLevel.INFO, text = "Access Granted: {0}" )
+  void accessGranted(boolean accessGranted);
+
+  @Message( level = MessageLevel.DEBUG, text = "PrimaryPrincipal: {0}" )
+  void primaryPrincipal(String name);
+
+  @Message( level = MessageLevel.DEBUG, text = "ImpersonatedPrincipal: {0}" )
+  void impersonatedPrincipal(String name);
+
+  @Message( level = MessageLevel.DEBUG, text = "ImpersonatedPrincipal has access: {0}" )
+  void impersonatedPrincipalHasAccess(boolean userAccess);
+
+  @Message( level = MessageLevel.DEBUG, text = "PrimaryPrincipal has access: {0}" )
+  void primaryPrincipalHasAccess(boolean userAccess);
+
+  @Message( level = MessageLevel.DEBUG, text = "GroupPrincipal has access: {0}" )
+  void groupPrincipalHasAccess(boolean groupAccess);
+
+  @Message( level = MessageLevel.DEBUG, text = "Remote IP Address: {0}" )
+  void remoteIPAddress(String remoteAddr);
+
+  @Message( level = MessageLevel.DEBUG, text = "Remote IP Address has access: {0}" )
+  void remoteIPAddressHasAccess(boolean remoteIpAccess);
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationResources.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationResources.java b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationResources.java
new file mode 100644
index 0000000..fcacd11
--- /dev/null
+++ b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationResources.java
@@ -0,0 +1,27 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter;
+
+import org.apache.knox.gateway.i18n.resources.Resource;
+import org.apache.knox.gateway.i18n.resources.Resources;
+
+@Resources
+public interface AclsAuthorizationResources {
+  @Resource( text = "Response status: {0}" )
+  String responseStatus( int status );
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/InvalidACLException.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/InvalidACLException.java b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/InvalidACLException.java
new file mode 100644
index 0000000..d9d38dc
--- /dev/null
+++ b/gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/InvalidACLException.java
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter;
+
+/**
+ * invalid ACL configuration item
+ */
+public class InvalidACLException extends RuntimeException {
+
+  private static final long serialVersionUID = -4284269372393774095L;
+
+  public InvalidACLException(String message) {
+    super(message);
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-authz-acls/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
deleted file mode 100644
index 11e2f6f..0000000
--- a/gateway-provider-security-authz-acls/src/main/resources/META-INF/services/org.apache.hadoop.gateway.deploy.ProviderDeploymentContributor
+++ /dev/null
@@ -1,18 +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.
-##########################################################################
-org.apache.hadoop.gateway.deploy.impl.AclsAuthzDeploymentContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor b/gateway-provider-security-authz-acls/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
new file mode 100644
index 0000000..5bb3f5f
--- /dev/null
+++ b/gateway-provider-security-authz-acls/src/main/resources/META-INF/services/org.apache.knox.gateway.deploy.ProviderDeploymentContributor
@@ -0,0 +1,18 @@
+##########################################################################
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##########################################################################
+org.apache.knox.gateway.deploy.impl.AclsAuthzDeploymentContributor

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/test/java/org/apache/hadoop/gateway/filter/AclParserTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/test/java/org/apache/hadoop/gateway/filter/AclParserTest.java b/gateway-provider-security-authz-acls/src/test/java/org/apache/hadoop/gateway/filter/AclParserTest.java
deleted file mode 100644
index 3a2e746..0000000
--- a/gateway-provider-security-authz-acls/src/test/java/org/apache/hadoop/gateway/filter/AclParserTest.java
+++ /dev/null
@@ -1,212 +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.hadoop.gateway.filter;
-
-import static org.junit.Assert.*;
-
-import org.junit.Test;
-
-/**
- * @author larry
- *
- */
-public class AclParserTest {
-  @Test
-  public void testValidAcls() throws Exception {
-    AclParser p = new AclParser();
-    p.parseAcls("test", "guest;*;*");
-    assertTrue(p.users.contains("guest"));
-    assertTrue(p.anyGroup);
-    assertTrue(p.ipv.allowsAnyIP());
-
-    p = new AclParser();
-    p.parseAcls("test", "*;admins;*");
-    assertFalse(p.users.contains("guest"));
-    assertTrue(p.anyUser);
-    assertFalse(p.anyGroup);
-    assertTrue(p.groups.contains("admins"));
-    assertTrue(p.ipv.allowsAnyIP());
-
-    p = new AclParser();
-    p.parseAcls("test", "*;*;127.0.0.1");
-    assertFalse(p.users.contains("guest"));
-    assertTrue(p.anyUser);
-    assertTrue(p.anyGroup);
-    assertFalse(p.groups.contains("admins"));
-    assertFalse(p.ipv.allowsAnyIP());
-    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
-
-    p = new AclParser();
-    p.parseAcls("test", "*;admins;127.0.0.1");
-    assertFalse(p.users.contains("guest"));
-    assertTrue(p.anyUser);
-    assertFalse(p.anyGroup);
-    assertTrue(p.groups.contains("admins"));
-    assertFalse(p.ipv.allowsAnyIP());
-    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
-
-    p = new AclParser();
-    p.parseAcls("test", "guest;admins;127.0.0.1");
-    assertTrue(p.users.contains("guest"));
-    assertFalse(p.anyUser);
-    assertFalse(p.anyGroup);
-    assertTrue(p.groups.contains("admins"));
-    assertFalse(p.ipv.allowsAnyIP());
-    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
-
-    p = new AclParser();
-    p.parseAcls("test", "guest;*;127.0.0.1");
-    assertTrue(p.users.contains("guest"));
-    assertFalse(p.anyUser);
-    assertTrue(p.anyGroup);
-    assertFalse(p.groups.contains("admins"));
-    assertFalse(p.ipv.allowsAnyIP());
-    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
-
-    p = new AclParser();
-    p.parseAcls("test", "*;admins;127.0.0.1");
-    assertFalse(p.users.contains("guest"));
-    assertTrue(p.anyUser);
-    assertFalse(p.anyGroup);
-    assertTrue(p.groups.contains("admins"));
-    assertFalse(p.ipv.allowsAnyIP());
-    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
-  }
-    
-
-  @Test
-  public void testValidMultiValuedAcls() throws Exception {
-    AclParser p = new AclParser();
-    p.parseAcls("test", "*;admins;127.0.0.1,127.0.0.2");
-    assertFalse(p.users.contains("guest"));
-    assertTrue(p.anyUser);
-    assertFalse(p.anyGroup);
-    assertTrue(p.groups.contains("admins"));
-    assertFalse(p.ipv.allowsAnyIP());
-    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
-    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.2"));
-    assertFalse(p.ipv.getIPAddresses().contains("127.0.0.3"));
-
-    p = new AclParser();
-    p.parseAcls("test", "*;admins,users;127.0.0.1,127.0.0.2");
-    assertFalse(p.users.contains("guest"));
-    assertTrue(p.anyUser);
-    assertFalse(p.anyGroup);
-    assertTrue(p.groups.contains("admins"));
-    assertTrue(p.groups.contains("users"));
-    assertFalse(p.groups.contains("hackers"));
-    assertFalse(p.ipv.allowsAnyIP());
-    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
-    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.2"));
-    assertFalse(p.ipv.getIPAddresses().contains("127.0.0.3"));
-
-    p = new AclParser();
-    p.parseAcls("test", "guest,visitor;admins,users;127.0.0.1,127.0.0.2");
-    assertTrue(p.users.contains("guest"));
-    assertTrue(p.users.contains("visitor"));
-    assertFalse(p.users.contains("missing-guy"));
-    assertFalse(p.anyUser);
-    assertFalse(p.anyGroup);
-    assertTrue(p.groups.contains("admins"));
-    assertTrue(p.groups.contains("users"));
-    assertFalse(p.groups.contains("hackers"));
-    assertFalse(p.ipv.allowsAnyIP());
-    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
-    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.2"));
-    assertFalse(p.ipv.getIPAddresses().contains("127.0.0.3"));  
-  }
-  
-  @Test 
-  public void testNullACL() throws Exception {
-    AclParser p = new AclParser();
-    try {
-      p.parseAcls("test", null);
-    }
-    catch (InvalidACLException sle) {
-      // expected
-      fail("NULL acl should NOT have thrown InvalidACLException.");
-    }
-  }
-  
-  @Test
-  public void testInvalidAcls() throws Exception {
-    AclParser p = new AclParser();
-    try {
-      p.parseAcls("test", "guest");
-      fail("Invalid acl should have thrown InvalidACLException.");
-    }
-    catch (InvalidACLException sle) {
-      // expected
-    }
-
-    p = new AclParser();
-    try {
-      p.parseAcls("test", "guest;;");
-      fail("Invalid acl should have thrown InvalidACLException.");
-    }
-    catch (InvalidACLException sle) {
-      // expected
-    }
-  
-    p = new AclParser();
-    try {
-      p.parseAcls("test", ";;");
-      fail("Invalid acl should have thrown InvalidACLException.");
-    }
-    catch (InvalidACLException sle) {
-      // expected
-    }
-
-    p = new AclParser();
-    try {
-      p.parseAcls("test", ";");
-      fail("Invalid acl should have thrown InvalidACLException.");
-    }
-    catch (InvalidACLException sle) {
-      // expected
-    }
-
-    p = new AclParser();
-    try {
-      p.parseAcls("test", "guest;");
-      fail("Invalid acl should have thrown InvalidACLException.");
-    }
-    catch (InvalidACLException sle) {
-      // expected
-    }
-
-    p = new AclParser();
-    try {
-      p.parseAcls("test", ";admins");
-      fail("Invalid acl should have thrown InvalidACLException.");
-    }
-    catch (InvalidACLException sle) {
-      // expected
-    }
-
-    p = new AclParser();
-    try {
-      p.parseAcls("test", "");
-      fail("Invalid acl should have thrown InvalidACLException.");
-    }
-    catch (InvalidACLException sle) {
-      // expected
-    }
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-authz-acls/src/test/java/org/apache/knox/gateway/filter/AclParserTest.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-authz-acls/src/test/java/org/apache/knox/gateway/filter/AclParserTest.java b/gateway-provider-security-authz-acls/src/test/java/org/apache/knox/gateway/filter/AclParserTest.java
new file mode 100644
index 0000000..c377a89
--- /dev/null
+++ b/gateway-provider-security-authz-acls/src/test/java/org/apache/knox/gateway/filter/AclParserTest.java
@@ -0,0 +1,212 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT 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.knox.gateway.filter;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+/**
+ * @author larry
+ *
+ */
+public class AclParserTest {
+  @Test
+  public void testValidAcls() throws Exception {
+    AclParser p = new AclParser();
+    p.parseAcls("test", "guest;*;*");
+    assertTrue(p.users.contains("guest"));
+    assertTrue(p.anyGroup);
+    assertTrue(p.ipv.allowsAnyIP());
+
+    p = new AclParser();
+    p.parseAcls("test", "*;admins;*");
+    assertFalse(p.users.contains("guest"));
+    assertTrue(p.anyUser);
+    assertFalse(p.anyGroup);
+    assertTrue(p.groups.contains("admins"));
+    assertTrue(p.ipv.allowsAnyIP());
+
+    p = new AclParser();
+    p.parseAcls("test", "*;*;127.0.0.1");
+    assertFalse(p.users.contains("guest"));
+    assertTrue(p.anyUser);
+    assertTrue(p.anyGroup);
+    assertFalse(p.groups.contains("admins"));
+    assertFalse(p.ipv.allowsAnyIP());
+    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
+
+    p = new AclParser();
+    p.parseAcls("test", "*;admins;127.0.0.1");
+    assertFalse(p.users.contains("guest"));
+    assertTrue(p.anyUser);
+    assertFalse(p.anyGroup);
+    assertTrue(p.groups.contains("admins"));
+    assertFalse(p.ipv.allowsAnyIP());
+    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
+
+    p = new AclParser();
+    p.parseAcls("test", "guest;admins;127.0.0.1");
+    assertTrue(p.users.contains("guest"));
+    assertFalse(p.anyUser);
+    assertFalse(p.anyGroup);
+    assertTrue(p.groups.contains("admins"));
+    assertFalse(p.ipv.allowsAnyIP());
+    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
+
+    p = new AclParser();
+    p.parseAcls("test", "guest;*;127.0.0.1");
+    assertTrue(p.users.contains("guest"));
+    assertFalse(p.anyUser);
+    assertTrue(p.anyGroup);
+    assertFalse(p.groups.contains("admins"));
+    assertFalse(p.ipv.allowsAnyIP());
+    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
+
+    p = new AclParser();
+    p.parseAcls("test", "*;admins;127.0.0.1");
+    assertFalse(p.users.contains("guest"));
+    assertTrue(p.anyUser);
+    assertFalse(p.anyGroup);
+    assertTrue(p.groups.contains("admins"));
+    assertFalse(p.ipv.allowsAnyIP());
+    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
+  }
+    
+
+  @Test
+  public void testValidMultiValuedAcls() throws Exception {
+    AclParser p = new AclParser();
+    p.parseAcls("test", "*;admins;127.0.0.1,127.0.0.2");
+    assertFalse(p.users.contains("guest"));
+    assertTrue(p.anyUser);
+    assertFalse(p.anyGroup);
+    assertTrue(p.groups.contains("admins"));
+    assertFalse(p.ipv.allowsAnyIP());
+    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
+    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.2"));
+    assertFalse(p.ipv.getIPAddresses().contains("127.0.0.3"));
+
+    p = new AclParser();
+    p.parseAcls("test", "*;admins,users;127.0.0.1,127.0.0.2");
+    assertFalse(p.users.contains("guest"));
+    assertTrue(p.anyUser);
+    assertFalse(p.anyGroup);
+    assertTrue(p.groups.contains("admins"));
+    assertTrue(p.groups.contains("users"));
+    assertFalse(p.groups.contains("hackers"));
+    assertFalse(p.ipv.allowsAnyIP());
+    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
+    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.2"));
+    assertFalse(p.ipv.getIPAddresses().contains("127.0.0.3"));
+
+    p = new AclParser();
+    p.parseAcls("test", "guest,visitor;admins,users;127.0.0.1,127.0.0.2");
+    assertTrue(p.users.contains("guest"));
+    assertTrue(p.users.contains("visitor"));
+    assertFalse(p.users.contains("missing-guy"));
+    assertFalse(p.anyUser);
+    assertFalse(p.anyGroup);
+    assertTrue(p.groups.contains("admins"));
+    assertTrue(p.groups.contains("users"));
+    assertFalse(p.groups.contains("hackers"));
+    assertFalse(p.ipv.allowsAnyIP());
+    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.1"));
+    assertTrue(p.ipv.getIPAddresses().contains("127.0.0.2"));
+    assertFalse(p.ipv.getIPAddresses().contains("127.0.0.3"));  
+  }
+  
+  @Test 
+  public void testNullACL() throws Exception {
+    AclParser p = new AclParser();
+    try {
+      p.parseAcls("test", null);
+    }
+    catch (InvalidACLException sle) {
+      // expected
+      fail("NULL acl should NOT have thrown InvalidACLException.");
+    }
+  }
+  
+  @Test
+  public void testInvalidAcls() throws Exception {
+    AclParser p = new AclParser();
+    try {
+      p.parseAcls("test", "guest");
+      fail("Invalid acl should have thrown InvalidACLException.");
+    }
+    catch (InvalidACLException sle) {
+      // expected
+    }
+
+    p = new AclParser();
+    try {
+      p.parseAcls("test", "guest;;");
+      fail("Invalid acl should have thrown InvalidACLException.");
+    }
+    catch (InvalidACLException sle) {
+      // expected
+    }
+  
+    p = new AclParser();
+    try {
+      p.parseAcls("test", ";;");
+      fail("Invalid acl should have thrown InvalidACLException.");
+    }
+    catch (InvalidACLException sle) {
+      // expected
+    }
+
+    p = new AclParser();
+    try {
+      p.parseAcls("test", ";");
+      fail("Invalid acl should have thrown InvalidACLException.");
+    }
+    catch (InvalidACLException sle) {
+      // expected
+    }
+
+    p = new AclParser();
+    try {
+      p.parseAcls("test", "guest;");
+      fail("Invalid acl should have thrown InvalidACLException.");
+    }
+    catch (InvalidACLException sle) {
+      // expected
+    }
+
+    p = new AclParser();
+    try {
+      p.parseAcls("test", ";admins");
+      fail("Invalid acl should have thrown InvalidACLException.");
+    }
+    catch (InvalidACLException sle) {
+      // expected
+    }
+
+    p = new AclParser();
+    try {
+      p.parseAcls("test", "");
+      fail("Invalid acl should have thrown InvalidACLException.");
+    }
+    catch (InvalidACLException sle) {
+      // expected
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/HadoopAuthMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/HadoopAuthMessages.java b/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/HadoopAuthMessages.java
deleted file mode 100755
index b7609c8..0000000
--- a/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/HadoopAuthMessages.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.hadoop.gateway.hadoopauth;
-
-import org.apache.hadoop.gateway.i18n.messages.Message;
-import org.apache.hadoop.gateway.i18n.messages.MessageLevel;
-import org.apache.hadoop.gateway.i18n.messages.Messages;
-
-@Messages(logger="org.apache.hadoop.gateway.provider.global.hadoopauth")
-public interface HadoopAuthMessages {
-  
-  @Message( level = MessageLevel.INFO, text = "Initializing Hadoop Auth Property, name: {0},  value: {1}" )
-  void initializingHadoopAuthProperty(String name, String value);
-  
-  @Message( level = MessageLevel.DEBUG, text = "Hadoop Authentication Asserted Principal: {0}" )
-  void hadoopAuthAssertedPrincipal(String name);
-  
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/deploy/HadoopAuthDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/deploy/HadoopAuthDeploymentContributor.java b/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/deploy/HadoopAuthDeploymentContributor.java
deleted file mode 100755
index 8404853..0000000
--- a/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/deploy/HadoopAuthDeploymentContributor.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.hadoop.gateway.hadoopauth.deploy;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.hadoop.gateway.deploy.DeploymentContext;
-import org.apache.hadoop.gateway.deploy.ProviderDeploymentContributorBase;
-import org.apache.hadoop.gateway.descriptor.FilterParamDescriptor;
-import org.apache.hadoop.gateway.descriptor.ResourceDescriptor;
-import org.apache.hadoop.gateway.topology.Provider;
-import org.apache.hadoop.gateway.topology.Service;
-
-public class HadoopAuthDeploymentContributor extends
-    ProviderDeploymentContributorBase {
-
-  private static final String ROLE = "authentication";
-  private static final String NAME = "HadoopAuth";
-
-  private static final String HADOOPAUTH_FILTER_CLASSNAME = "org.apache.hadoop.gateway.hadoopauth.filter.HadoopAuthFilter";
-  private static final String HADOOPAUTH_POSTFILTER_CLASSNAME = "org.apache.hadoop.gateway.hadoopauth.filter.HadoopAuthPostFilter";
-
-  @Override
-  public String getRole() {
-    return ROLE;
-  }
-
-  @Override
-  public String getName() {
-    return NAME;
-  }
-
-  @Override
-  public void initializeContribution(DeploymentContext context) {
-    super.initializeContribution(context);
-  }
-
-  @Override
-  public void contributeFilter(DeploymentContext context, Provider provider, Service service, 
-      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
-    // blindly add all the provider params as filter init params
-    if (params == null) {
-      params = new ArrayList<FilterParamDescriptor>();
-    }
-    Map<String, String> providerParams = provider.getParams();
-    for(Entry<String, String> entry : providerParams.entrySet()) {
-      params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
-    }
-    resource.addFilter().name( getName() ).role( getRole() ).impl( HADOOPAUTH_FILTER_CLASSNAME ).params( params );
-    resource.addFilter().name( "Post" + getName() ).role( getRole() ).impl( HADOOPAUTH_POSTFILTER_CLASSNAME ).params( params );
-  }
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/filter/HadoopAuthFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/filter/HadoopAuthFilter.java b/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/filter/HadoopAuthFilter.java
deleted file mode 100755
index 649601f..0000000
--- a/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/filter/HadoopAuthFilter.java
+++ /dev/null
@@ -1,68 +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.hadoop.gateway.hadoopauth.filter;
-
-import java.util.Enumeration;
-import java.util.Properties;
-
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-
-import org.apache.hadoop.gateway.hadoopauth.HadoopAuthMessages;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-
-/*
- * see http://hadoop.apache.org/docs/current/hadoop-auth/Configuration.html
- *
- * CONFIG_PREFIX = "config.prefix
- * AUTH_TYPE = "type", AUTH_TOKEN_VALIDITY = "token.validity"
- * COOKIE_DOMAIN = "cookie.domain", COOKIE_PATH = "cookie.path"
- * SIGNATURE_SECRET = "signature.secret
- * TYPE = "kerberos", PRINCIPAL = TYPE + ".principal", KEYTAB = TYPE + ".keytab"
-
- * config.prefix=hadoop.auth.config (default: null)
- * hadoop.auth.config.signature.secret=SECRET (default: a simple random number)
- * hadoop.auth.config.type=simple|kerberos|CLASS (default: none, would throw exception)
- * hadoop.auth.config.token.validity=SECONDS (default: 3600 seconds)
- * hadoop.auth.config.cookie.domain=DOMAIN(default: null)
- * hadoop.auth.config.cookie.path=PATH (default: null)
- * hadoop.auth.config.kerberos.principal=HTTP/localhost@LOCALHOST (default: null)
- * hadoop.auth.config.kerberos.keytab=/etc/knox/conf/knox.service.keytab (default: null)
- */
-
-public class HadoopAuthFilter extends 
-    org.apache.hadoop.security.authentication.server.AuthenticationFilter {
-  
-  private static HadoopAuthMessages log = MessagesFactory.get( HadoopAuthMessages.class );
-  
-  @Override
-  protected Properties getConfiguration(String configPrefix, FilterConfig filterConfig) throws ServletException {
-    Properties props = new Properties();
-    Enumeration<?> names = filterConfig.getInitParameterNames();
-    while (names.hasMoreElements()) {
-      String name = (String) names.nextElement();
-      if (name.startsWith(configPrefix)) {
-        String value = filterConfig.getInitParameter(name);
-        log.initializingHadoopAuthProperty(name, value);
-        props.put(name.substring(configPrefix.length()), value);
-      }
-    }
-    return props;
-  }
-  
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/filter/HadoopAuthPostFilter.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/filter/HadoopAuthPostFilter.java b/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/filter/HadoopAuthPostFilter.java
deleted file mode 100755
index 70db96c..0000000
--- a/gateway-provider-security-hadoopauth/src/main/java/org/apache/hadoop/gateway/hadoopauth/filter/HadoopAuthPostFilter.java
+++ /dev/null
@@ -1,108 +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.hadoop.gateway.hadoopauth.filter;
-
-import java.io.IOException;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-
-import javax.security.auth.Subject;
-import javax.servlet.Filter;
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.hadoop.gateway.security.PrimaryPrincipal;
-import org.apache.hadoop.gateway.i18n.messages.MessagesFactory;
-import org.apache.hadoop.gateway.audit.api.Action;
-import org.apache.hadoop.gateway.audit.api.ActionOutcome;
-import org.apache.hadoop.gateway.audit.api.AuditService;
-import org.apache.hadoop.gateway.audit.api.AuditServiceFactory;
-import org.apache.hadoop.gateway.audit.api.Auditor;
-import org.apache.hadoop.gateway.audit.api.ResourceType;
-import org.apache.hadoop.gateway.audit.log4j.audit.AuditConstants;
-import org.apache.hadoop.gateway.filter.AbstractGatewayFilter;
-import org.apache.hadoop.gateway.hadoopauth.HadoopAuthMessages;
-
-public class HadoopAuthPostFilter implements Filter {
-
-  private static HadoopAuthMessages log = MessagesFactory.get( HadoopAuthMessages.class );
-  private static AuditService auditService = AuditServiceFactory.getAuditService();
-  private static Auditor auditor = auditService.getAuditor(
-      AuditConstants.DEFAULT_AUDITOR_NAME, AuditConstants.KNOX_SERVICE_NAME,
-      AuditConstants.KNOX_COMPONENT_NAME );
-
-  @Override
-  public void init( FilterConfig filterConfig ) throws ServletException {
-  }
-
-  @Override
-  public void destroy() {
-  }
-  
-  @Override
-  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
-      throws IOException, ServletException {
-    HttpServletRequest httpRequest = (HttpServletRequest)request;
-    String principal = httpRequest.getRemoteUser();
-    if (principal != null) {
-        Subject subject = new Subject();
-        subject.getPrincipals().add(new PrimaryPrincipal(principal));
-        log.hadoopAuthAssertedPrincipal(principal);
-        auditService.getContext().setUsername( principal ); //KM: Audit Fix
-        String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
-        auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
-        doAs(httpRequest, response, chain, subject);
-    } 
-    else {
-      ((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN, "User not authenticated");
-    }
-  }
-
-  private void doAs(final ServletRequest request, final ServletResponse response, final FilterChain chain, Subject subject)
-      throws IOException, ServletException {
-      try {
-        Subject.doAs(
-            subject,
-            new PrivilegedExceptionAction<Object>() {
-              public Object run() throws Exception {
-                chain.doFilter(request, response);
-                return null;
-              }
-            }
-            );
-      }
-      catch (PrivilegedActionException e) {
-        Throwable t = e.getCause();
-        if (t instanceof IOException) {
-          throw (IOException) t;
-        }
-        else if (t instanceof ServletException) {
-          throw (ServletException) t;
-        }
-        else {
-          throw new ServletException(t);
-        }
-      }
-    }
-  
-}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/HadoopAuthMessages.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/HadoopAuthMessages.java b/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/HadoopAuthMessages.java
new file mode 100755
index 0000000..6141686
--- /dev/null
+++ b/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/HadoopAuthMessages.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.knox.gateway.hadoopauth;
+
+import org.apache.knox.gateway.i18n.messages.Message;
+import org.apache.knox.gateway.i18n.messages.MessageLevel;
+import org.apache.knox.gateway.i18n.messages.Messages;
+
+@Messages(logger="org.apache.hadoop.gateway.provider.global.hadoopauth")
+public interface HadoopAuthMessages {
+  
+  @Message( level = MessageLevel.INFO, text = "Initializing Hadoop Auth Property, name: {0},  value: {1}" )
+  void initializingHadoopAuthProperty(String name, String value);
+  
+  @Message( level = MessageLevel.DEBUG, text = "Hadoop Authentication Asserted Principal: {0}" )
+  void hadoopAuthAssertedPrincipal(String name);
+  
+}

http://git-wip-us.apache.org/repos/asf/knox/blob/af9b0c3d/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/deploy/HadoopAuthDeploymentContributor.java
----------------------------------------------------------------------
diff --git a/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/deploy/HadoopAuthDeploymentContributor.java b/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/deploy/HadoopAuthDeploymentContributor.java
new file mode 100755
index 0000000..5dc1c0c
--- /dev/null
+++ b/gateway-provider-security-hadoopauth/src/main/java/org/apache/knox/gateway/hadoopauth/deploy/HadoopAuthDeploymentContributor.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.knox.gateway.hadoopauth.deploy;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.knox.gateway.deploy.DeploymentContext;
+import org.apache.knox.gateway.deploy.ProviderDeploymentContributorBase;
+import org.apache.knox.gateway.descriptor.FilterParamDescriptor;
+import org.apache.knox.gateway.descriptor.ResourceDescriptor;
+import org.apache.knox.gateway.topology.Provider;
+import org.apache.knox.gateway.topology.Service;
+
+public class HadoopAuthDeploymentContributor extends
+    ProviderDeploymentContributorBase {
+
+  private static final String ROLE = "authentication";
+  private static final String NAME = "HadoopAuth";
+
+  private static final String HADOOPAUTH_FILTER_CLASSNAME = "HadoopAuthFilter";
+  private static final String HADOOPAUTH_POSTFILTER_CLASSNAME = "HadoopAuthPostFilter";
+
+  @Override
+  public String getRole() {
+    return ROLE;
+  }
+
+  @Override
+  public String getName() {
+    return NAME;
+  }
+
+  @Override
+  public void initializeContribution(DeploymentContext context) {
+    super.initializeContribution(context);
+  }
+
+  @Override
+  public void contributeFilter(DeploymentContext context, Provider provider, Service service,
+      ResourceDescriptor resource, List<FilterParamDescriptor> params) {
+    // blindly add all the provider params as filter init params
+    if (params == null) {
+      params = new ArrayList<FilterParamDescriptor>();
+    }
+    Map<String, String> providerParams = provider.getParams();
+    for(Entry<String, String> entry : providerParams.entrySet()) {
+      params.add( resource.createFilterParam().name( entry.getKey().toLowerCase() ).value( entry.getValue() ) );
+    }
+    resource.addFilter().name( getName() ).role( getRole() ).impl( HADOOPAUTH_FILTER_CLASSNAME ).params( params );
+    resource.addFilter().name( "Post" + getName() ).role( getRole() ).impl( HADOOPAUTH_POSTFILTER_CLASSNAME ).params( params );
+  }
+}