http://git-wip-us.apache.org/repos/asf/knox/blob/50f46e9e/gateway-test/src/test/java/org/apache/knox/gateway/KnoxCliSysBindTest.java ---------------------------------------------------------------------- diff --cc gateway-test/src/test/java/org/apache/knox/gateway/KnoxCliSysBindTest.java index c04d87c,0000000..73336c7 mode 100644,000000..100644 --- a/gateway-test/src/test/java/org/apache/knox/gateway/KnoxCliSysBindTest.java +++ b/gateway-test/src/test/java/org/apache/knox/gateway/KnoxCliSysBindTest.java @@@ -1,316 -1,0 +1,289 @@@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.security.ldap.SimpleLdapDirectoryServer; +import org.apache.knox.gateway.services.DefaultGatewayServices; +import org.apache.knox.gateway.services.ServiceLifecycleException; +import org.apache.knox.gateway.util.KnoxCLI; +import org.apache.hadoop.test.TestUtils; +import org.apache.hadoop.test.log.NoOpAppender; +import org.apache.log4j.Appender; - 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.ByteArrayOutputStream; +import java.io.PrintStream; +import java.io.File; +import java.io.FileOutputStream; - import java.io.IOException; - import java.io.InputStream; - import java.net.URL; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +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.junit.Assert.assertThat; + +public class KnoxCliSysBindTest { + - private static Class RESOURCE_BASE_CLASS = KnoxCliSysBindTest.class; - private static Logger LOG = LoggerFactory.getLogger( KnoxCliSysBindTest.class ); - + public static Enumeration<Appender> appenders; + public static GatewayTestConfig config; + public static GatewayServer gateway; + public static String gatewayUrl; + public static String clusterUrl; + private static GatewayTestDriver driver = new GatewayTestDriver(); + + private static final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + private static final ByteArrayOutputStream errContent = new ByteArrayOutputStream(); + private static final String uuid = UUID.randomUUID().toString(); + + @BeforeClass + public static void setupSuite() throws Exception { + LOG_ENTER(); + System.setOut(new PrintStream(outContent)); + System.setErr(new PrintStream(errContent)); + driver.setupLdap(0); + setupGateway(); + LOG_EXIT(); + } + + @AfterClass + public static void cleanupSuite() throws Exception { + LOG_ENTER(); + driver.cleanup(); + + //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) ); + //NoOpAppender.tearDown( appenders ); + LOG_EXIT(); + } + + public static void setupGateway() throws Exception { + + File targetDir = new File( System.getProperty( "user.dir" ), "target" ); + File gatewayDir = new File( targetDir, "gateway-home-" + uuid ); + 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(); + + writeTopology(topoDir, "test-cluster-1.xml", "guest", "guest-password", true); + writeTopology(topoDir, "test-cluster-2.xml", "sam", "sam-password", true); + writeTopology(topoDir, "test-cluster-3.xml", "admin2", "admin-password", true); + writeTopology(topoDir, "test-cluster-4.xml", "", "", false); + + + 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. + } + } + + private static void writeTopology(File topoDir, String name, String user, String pass, boolean goodTopology) throws Exception { + File descriptor = new File(topoDir, name); + + if(descriptor.exists()){ + descriptor.delete(); + descriptor = new File(topoDir, name); + } + + FileOutputStream stream = new FileOutputStream( descriptor, false ); + + if(goodTopology) { + createTopology(user, pass).toStream( stream ); + } else { + createBadTopology().toStream( stream ); + } + + stream.close(); + + } + - 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( "\\.", "/" ) + "/"; - } - + private static XMLTag createBadTopology(){ + 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("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(driver.getLdapUrl()).gotoParent() + .addTag( "param" ) + .addTag("name").addText("main.ldapRealm.contextFactory.authenticationMechanism") + .addTag("value").addText("simple").gotoParent() + .addTag("param") + .addTag("name").addText("main.ldapRealm.authorizationEnabled") + .addTag("value").addText("true").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() + .gotoRoot() + .addTag( "service") + .addTag("role").addText( "KNOX" ) + .gotoRoot(); + // System.out.println( "GATEWAY=" + xml.toString() ); + return xml; + } + + private static XMLTag createTopology(String username, String password) { + + 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("org.apache.knox.gateway.shirorealm.KnoxLdapRealm").gotoParent() + .addTag("param" ) + .addTag("name").addText("main.ldapGroupContextFactory") + .addTag("value").addText("org.apache.knox.gateway.shirorealm.KnoxLdapContextFactory").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.memberAttributeValueTemplate") + .addTag("value").addText("uid={0},ou=people,dc=hadoop,dc=apache,dc=org").gotoParent() + .addTag("param" ) + .addTag("name").addText("main.ldapRealm.memberAttribute") + .addTag("value").addText("member").gotoParent() + .addTag("param") + .addTag("name").addText("main.ldapRealm.authorizationEnabled") + .addTag("value").addText("true").gotoParent() + .addTag("param") + .addTag("name").addText("main.ldapRealm.contextFactory.systemUsername") + .addTag("value").addText("uid=" + username + ",ou=people,dc=hadoop,dc=apache,dc=org").gotoParent() + .addTag("param") + .addTag("name").addText("main.ldapRealm.contextFactory.systemPassword") + .addTag( "value").addText(password).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() + .gotoRoot() + .addTag( "service" ) + .addTag( "role" ).addText( "test-service-role" ) + .gotoRoot(); + // System.out.println( "GATEWAY=" + xml.toString() ); + return xml; + } + + @Test( timeout = TestUtils.MEDIUM_TIMEOUT ) + public void testLDAPAuth() throws Exception { + LOG_ENTER(); + +// Test 1: Make sure authentication is successful + outContent.reset(); + String args[] = { "system-user-auth-test", "--master", "knox", "--cluster", "test-cluster-1", "--d" }; + KnoxCLI cli = new KnoxCLI(); + cli.setConf(config); + cli.run(args); + assertThat(outContent.toString(), containsString("System LDAP Bind successful")); + + // Test 2: Make sure authentication fails + outContent.reset(); + String args2[] = { "system-user-auth-test", "--master", "knox", "--cluster", "test-cluster-2", "--d" }; + cli = new KnoxCLI(); + cli.setConf(config); + cli.run(args2); + assertThat(outContent.toString(), containsString("System LDAP Bind successful")); + + + // Test 3: Make sure authentication is successful + outContent.reset(); + String args3[] = { "system-user-auth-test", "--master", "knox", "--cluster", "test-cluster-3", "--d" }; + cli = new KnoxCLI(); + cli.setConf(config); + Enumeration<Appender> before = NoOpAppender.setUp(); + try { + cli.run( args3 ); + } finally { + NoOpAppender.tearDown( before ); + } + assertThat(outContent.toString(), containsString("LDAP authentication failed")); + assertThat(outContent.toString(), containsString("Unable to successfully bind to LDAP server with topology credentials")); + + // Test 4: Assert that we get a username/password not present error is printed + outContent.reset(); + String args4[] = { "system-user-auth-test", "--master", "knox", "--cluster", "test-cluster-4" }; + cli = new KnoxCLI(); + cli.setConf(config); + cli.run(args4); + assertThat(outContent.toString(), containsString("Warn: main.ldapRealm.contextFactory.systemUsername is not present")); + assertThat(outContent.toString(), containsString("Warn: main.ldapRealm.contextFactory.systemPassword is not present")); + + + // Test 5: Assert that we get a username/password not present error is printed + outContent.reset(); + String args5[] = { "system-user-auth-test", "--master", "knox", "--cluster", "not-a-cluster" }; + cli = new KnoxCLI(); + cli.setConf(config); + cli.run(args5); + assertThat(outContent.toString(), containsString("Topology not-a-cluster does not exist")); + + LOG_EXIT(); + } + + +}
http://git-wip-us.apache.org/repos/asf/knox/blob/50f46e9e/gateway-test/src/test/java/org/apache/knox/gateway/deploy/DeploymentFactoryFuncTest.java ---------------------------------------------------------------------- diff --cc gateway-test/src/test/java/org/apache/knox/gateway/deploy/DeploymentFactoryFuncTest.java index 267de1b,0000000..25ad1c3 mode 100644,000000..100644 --- a/gateway-test/src/test/java/org/apache/knox/gateway/deploy/DeploymentFactoryFuncTest.java +++ b/gateway-test/src/test/java/org/apache/knox/gateway/deploy/DeploymentFactoryFuncTest.java @@@ -1,683 -1,0 +1,658 @@@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.apache.commons.io.FileUtils; +import org.apache.knox.gateway.GatewayTestConfig; +import org.apache.knox.gateway.config.GatewayConfig; +import org.apache.knox.gateway.filter.XForwardedHeaderFilter; +import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletFilter; +import org.apache.knox.gateway.services.DefaultGatewayServices; +import org.apache.knox.gateway.services.ServiceLifecycleException; +import org.apache.knox.gateway.topology.Application; +import org.apache.knox.gateway.topology.Param; +import org.apache.knox.gateway.topology.Provider; +import org.apache.knox.gateway.topology.Service; +import org.apache.knox.gateway.topology.Topology; +import org.apache.knox.gateway.util.XmlUtils; +import org.apache.hadoop.test.TestUtils; +import org.apache.hadoop.test.log.NoOpAppender; +import org.apache.log4j.Appender; +import org.jboss.shrinkwrap.api.Archive; +import org.jboss.shrinkwrap.api.ArchivePath; +import org.jboss.shrinkwrap.api.spec.EnterpriseArchive; +import org.jboss.shrinkwrap.api.spec.WebArchive; +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.xml.sax.SAXException; + +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.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.xml.HasXPath.hasXPath; +import static org.junit.Assert.fail; + +public class DeploymentFactoryFuncTest { + + private static final long SHORT_TIMEOUT = 1000L; + private static final long MEDIUM_TIMEOUT = 5 * SHORT_TIMEOUT; + private static final long LONG_TIMEOUT = 10 * MEDIUM_TIMEOUT; + + @Test( timeout = MEDIUM_TIMEOUT ) + public void testGenericProviderDeploymentContributor() throws ParserConfigurationException, SAXException, IOException, TransformerException { + LOG_ENTER(); + GatewayConfig config = new GatewayTestConfig(); + File targetDir = new File( System.getProperty( "user.dir" ), "target" ); + File gatewayDir = new File( targetDir, "gateway-home-" + UUID.randomUUID() ); + gatewayDir.mkdirs(); + + ((GatewayTestConfig) config).setGatewayHomeDir( gatewayDir.getAbsolutePath() ); + + File deployDir = new File( config.getGatewayDeploymentDir() ); + deployDir.mkdirs(); + + // ((GatewayTestConfig) config).setDeploymentDir( "clusters" ); + - addStacksDir(config, targetDir); + DefaultGatewayServices srvcs = new DefaultGatewayServices(); + Map<String,String> options = new HashMap<>(); + options.put("persist-master", "false"); + options.put("master", "password"); + try { + DeploymentFactory.setGatewayServices(srvcs); + srvcs.init(config, options); + } catch (ServiceLifecycleException e) { + e.printStackTrace(); // I18N not required. + } + + Topology topology = new Topology(); + topology.setName( "test-cluster" ); + Service service = new Service(); + service.setRole( "WEBHDFS" ); + service.addUrl( "http://localhost:50070/test-service-url" ); + topology.addService( service ); + + Provider provider = new Provider(); + provider.setRole( "federation" ); + provider.setName( "HeaderPreAuth" ); + provider.setEnabled( true ); + Param param = new Param(); + param.setName( "filter" ); + param.setValue( "org.opensource.ExistingFilter" ); + provider.addParam( param ); + param = new Param(); + param.setName( "test-param-name" ); + param.setValue( "test-param-value" ); + provider.addParam( param ); + topology.addProvider( provider ); + + EnterpriseArchive war = DeploymentFactory.createDeployment( config, topology ); + + Document gateway = XmlUtils.readXml( war.get( "%2F/WEB-INF/gateway.xml" ).getAsset().openStream() ); + //dump( gateway ); + + //by default the first filter will be the X-Forwarded header filter + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[1]/role", equalTo( "xforwardedheaders" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[1]/name", equalTo( "XForwardedHeaderFilter" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[1]/class", equalTo( "org.apache.knox.gateway.filter.XForwardedHeaderFilter" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[2]/role", equalTo( "federation" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[2]/name", equalTo( "HeaderPreAuth" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[2]/class", equalTo( "org.apache.knox.gateway.preauth.filter.HeaderPreAuthFederationFilter" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[2]/param[1]/name", equalTo( "filter" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[2]/param[1]/value", equalTo( "org.opensource.ExistingFilter" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[2]/param[2]/name", equalTo( "test-param-name" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[2]/param[2]/value", equalTo( "test-param-value" ) ) ); + LOG_EXIT(); + } + + @Test( timeout = LONG_TIMEOUT ) + public void testInvalidGenericProviderDeploymentContributor() throws ParserConfigurationException, SAXException, IOException, TransformerException { + LOG_ENTER(); + GatewayConfig config = new GatewayTestConfig(); + File targetDir = new File( System.getProperty( "user.dir" ), "target" ); + File gatewayDir = new File( targetDir, "gateway-home-" + UUID.randomUUID() ); + gatewayDir.mkdirs(); + ((GatewayTestConfig) config).setGatewayHomeDir( gatewayDir.getAbsolutePath() ); + File deployDir = new File( config.getGatewayDeploymentDir() ); + deployDir.mkdirs(); - addStacksDir(config, targetDir); + + DefaultGatewayServices srvcs = new DefaultGatewayServices(); + Map<String,String> options = new HashMap<>(); + options.put("persist-master", "false"); + options.put("master", "password"); + try { + DeploymentFactory.setGatewayServices(srvcs); + srvcs.init(config, options); + } catch (ServiceLifecycleException e) { + e.printStackTrace(); // I18N not required. + } + + Topology topology = new Topology(); + topology.setName( "test-cluster" ); + Service service = new Service(); + service.setRole( "WEBHDFS" ); + service.addUrl( "http://localhost:50070/test-service-url" ); + topology.addService( service ); + + Provider provider = new Provider(); + provider.setRole( "authentication" ); + provider.setName( "generic" ); + provider.setEnabled( true ); + Param param; // = new ProviderParam(); + // Missing filter param. + //param.setName( "filter" ); + //param.setValue( "org.opensource.ExistingFilter" ); + //provider.addParam( param ); + param = new Param(); + param.setName( "test-param-name" ); + param.setValue( "test-param-value" ); + provider.addParam( param ); + topology.addProvider( provider ); + + Enumeration<Appender> appenders = NoOpAppender.setUp(); + try { + DeploymentFactory.createDeployment( config, topology ); + fail( "Should have throws IllegalArgumentException" ); + } catch ( DeploymentException e ) { + // Expected. + } finally { + NoOpAppender.tearDown( appenders ); + } + LOG_EXIT(); + } + + @Test( timeout = MEDIUM_TIMEOUT ) + public void testSimpleTopology() throws IOException, SAXException, ParserConfigurationException, URISyntaxException, TransformerException { + LOG_ENTER(); + GatewayConfig config = new GatewayTestConfig(); + //Testing without x-forwarded headers filter + ((GatewayTestConfig)config).setXForwardedEnabled(false); + File targetDir = new File( System.getProperty( "user.dir" ), "target" ); + File gatewayDir = new File( targetDir, "gateway-home-" + UUID.randomUUID() ); + gatewayDir.mkdirs(); + ((GatewayTestConfig) config).setGatewayHomeDir( gatewayDir.getAbsolutePath() ); + File deployDir = new File( config.getGatewayDeploymentDir() ); + deployDir.mkdirs(); - addStacksDir(config, targetDir); + + DefaultGatewayServices srvcs = new DefaultGatewayServices(); + Map<String,String> options = new HashMap<>(); + options.put("persist-master", "false"); + options.put("master", "password"); + try { + DeploymentFactory.setGatewayServices(srvcs); + srvcs.init(config, options); + } catch (ServiceLifecycleException e) { + e.printStackTrace(); // I18N not required. + } + + Topology topology = new Topology(); + topology.setName( "test-cluster" ); + Service service = new Service(); + service.setRole( "WEBHDFS" ); + service.addUrl( "http://localhost:50070/webhdfs" ); + topology.addService( service ); + Provider provider = new Provider(); + provider.setRole( "authentication" ); + provider.setName( "ShiroProvider" ); + provider.setEnabled( true ); + Param param = new Param(); + param.setName( "contextConfigLocation" ); + param.setValue( "classpath:app-context-security.xml" ); + provider.addParam( param ); + topology.addProvider( provider ); + Provider asserter = new Provider(); + asserter.setRole( "identity-assertion" ); + asserter.setName("Default"); + asserter.setEnabled( true ); + topology.addProvider( asserter ); + Provider authorizer = new Provider(); + authorizer.setRole( "authorization" ); + authorizer.setName("AclsAuthz"); + authorizer.setEnabled( true ); + topology.addProvider( authorizer ); + + EnterpriseArchive war = DeploymentFactory.createDeployment( config, topology ); + // File dir = new File( System.getProperty( "user.dir" ) ); + // File file = war.as( ExplodedExporter.class ).exportExploded( dir, "test-cluster.war" ); + + Document web = XmlUtils.readXml( war.get( "%2F/WEB-INF/web.xml" ).getAsset().openStream() ); + assertThat( web, hasXPath( "/web-app" ) ); + assertThat( web, hasXPath( "/web-app/servlet" ) ); + assertThat( web, hasXPath( "/web-app/servlet/servlet-name" ) ); + assertThat( web, hasXPath( "/web-app/servlet/servlet-name", equalTo( "test-cluster-knox-gateway-servlet" ) ) ); + assertThat( web, hasXPath( "/web-app/servlet/servlet-class", equalTo( "org.apache.knox.gateway.GatewayServlet" ) ) ); + assertThat( web, hasXPath( "/web-app/servlet/init-param/param-name", equalTo( "gatewayDescriptorLocation" ) ) ); + assertThat( web, hasXPath( "/web-app/servlet/init-param/param-value", equalTo( "/WEB-INF/gateway.xml" ) ) ); + assertThat( web, hasXPath( "/web-app/servlet-mapping/servlet-name", equalTo( "test-cluster-knox-gateway-servlet" ) ) ); + assertThat( web, hasXPath( "/web-app/servlet-mapping/url-pattern", equalTo( "/*" ) ) ); + + Document gateway = XmlUtils.readXml( war.get( "%2F/WEB-INF/gateway.xml" ).getAsset().openStream() ); + + assertThat( gateway, hasXPath( "/gateway/resource[1]/pattern", equalTo( "/webhdfs/v1/?**" ) ) ); + //assertThat( gateway, hasXPath( "/gateway/resource[1]/target", equalTo( "http://localhost:50070/webhdfs/v1/?{**}" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[1]/role", equalTo( "authentication" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[1]/class", equalTo( "org.apache.knox.gateway.filter.ResponseCookieFilter" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[2]/role", equalTo( "authentication" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[2]/class", equalTo( "org.apache.shiro.web.servlet.ShiroFilter" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[3]/role", equalTo( "authentication" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[3]/class", equalTo( "org.apache.knox.gateway.filter.ShiroSubjectIdentityAdapter" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[4]/role", equalTo( "rewrite" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[4]/class", equalTo( "org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletFilter" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[5]/role", equalTo( "identity-assertion" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[5]/class", equalTo( "org.apache.knox.gateway.identityasserter.filter.IdentityAsserterFilter" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[6]/role", equalTo( "authorization" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[6]/name", equalTo( "AclsAuthz" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[6]/class", equalTo( "org.apache.knox.gateway.filter.AclsAuthorizationFilter" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[7]/role", equalTo( "dispatch" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[7]/name", equalTo( "webhdfs" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[7]/class", equalTo( "org.apache.knox.gateway.dispatch.GatewayDispatchFilter" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[2]/pattern", equalTo( "/webhdfs/v1/**?**" ) ) ); + //assertThat( gateway, hasXPath( "/gateway/resource[2]/target", equalTo( "http://localhost:50070/webhdfs/v1/{path=**}?{**}" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[2]/filter[1]/role", equalTo( "authentication" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[2]/filter[1]/class", equalTo( "org.apache.knox.gateway.filter.ResponseCookieFilter" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[2]/filter[2]/role", equalTo( "authentication" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[2]/filter[2]/class", equalTo( "org.apache.shiro.web.servlet.ShiroFilter" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[2]/filter[3]/role", equalTo( "authentication" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[2]/filter[3]/class", equalTo( "org.apache.knox.gateway.filter.ShiroSubjectIdentityAdapter" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[2]/filter[4]/role", equalTo( "rewrite" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[2]/filter[4]/class", equalTo( "org.apache.knox.gateway.filter.rewrite.api.UrlRewriteServletFilter" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[2]/filter[5]/role", equalTo( "identity-assertion" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[2]/filter[5]/class", equalTo( "org.apache.knox.gateway.identityasserter.filter.IdentityAsserterFilter" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[6]/role", equalTo( "authorization" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[6]/name", equalTo( "AclsAuthz" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[1]/filter[6]/class", equalTo( "org.apache.knox.gateway.filter.AclsAuthorizationFilter" ) ) ); + + assertThat( gateway, hasXPath( "/gateway/resource[2]/filter[7]/role", equalTo( "dispatch" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[2]/filter[7]/name", equalTo( "webhdfs" ) ) ); + assertThat( gateway, hasXPath( "/gateway/resource[2]/filter[7]/class", equalTo( "org.apache.knox.gateway.dispatch.GatewayDispatchFilter" ) ) ); + + LOG_EXIT(); + } + + + @Test( timeout = LONG_TIMEOUT ) + public void testWebXmlGeneration() throws IOException, SAXException, ParserConfigurationException, URISyntaxException { + LOG_ENTER(); + GatewayConfig config = new GatewayTestConfig(); + File targetDir = new File(System.getProperty("user.dir"), "target"); + File gatewayDir = new File(targetDir, "gateway-home-" + UUID.randomUUID()); + gatewayDir.mkdirs(); + ((GatewayTestConfig) config).setGatewayHomeDir(gatewayDir.getAbsolutePath()); + File deployDir = new File(config.getGatewayDeploymentDir()); + deployDir.mkdirs(); + + DefaultGatewayServices srvcs = new DefaultGatewayServices(); + Map<String, String> options = new HashMap<>(); + options.put("persist-master", "false"); + options.put("master", "password"); + try { + DeploymentFactory.setGatewayServices(srvcs); + srvcs.init(config, options); + } catch (ServiceLifecycleException e) { + e.printStackTrace(); // I18N not required. + } + + Topology topology = new Topology(); + topology.setName("test-cluster"); + Service service = new Service(); + service.setRole("WEBHDFS"); + service.addUrl("http://localhost:50070/webhdfs"); + topology.addService(service); + Provider provider = new Provider(); + provider.setRole("authentication"); + provider.setName("ShiroProvider"); + provider.setEnabled(true); + Param param = new Param(); + param.setName("contextConfigLocation"); + param.setValue("classpath:app-context-security.xml"); + provider.addParam(param); + topology.addProvider(provider); + Provider asserter = new Provider(); + asserter.setRole("identity-assertion"); + asserter.setName("Default"); + asserter.setEnabled(true); + topology.addProvider(asserter); + Provider authorizer = new Provider(); + authorizer.setRole("authorization"); + authorizer.setName("AclsAuthz"); + authorizer.setEnabled(true); + topology.addProvider(authorizer); + Provider ha = new Provider(); + ha.setRole("ha"); + ha.setName("HaProvider"); + ha.setEnabled(true); + topology.addProvider(ha); + + for (int i = 0; i < 10; i++) { + createAndTestDeployment(config, topology); + } + LOG_EXIT(); + } + + private void createAndTestDeployment(GatewayConfig config, Topology topology) throws IOException, SAXException, ParserConfigurationException { + + EnterpriseArchive war = DeploymentFactory.createDeployment(config, topology); + // File dir = new File( System.getProperty( "user.dir" ) ); + // File file = war.as( ExplodedExporter.class ).exportExploded( dir, "test-cluster.war" ); + + Document web = XmlUtils.readXml(war.get("%2F/WEB-INF/web.xml").getAsset().openStream()); + assertThat(web, hasXPath("/web-app/servlet/servlet-class", equalTo("org.apache.knox.gateway.GatewayServlet"))); + assertThat(web, hasXPath("/web-app/servlet/init-param/param-name", equalTo("gatewayDescriptorLocation"))); + assertThat(web, hasXPath("/web-app/servlet/init-param/param-value", equalTo("/WEB-INF/gateway.xml"))); + assertThat(web, hasXPath("/web-app/servlet-mapping/servlet-name", equalTo("test-cluster-knox-gateway-servlet"))); + assertThat(web, hasXPath("/web-app/servlet-mapping/url-pattern", equalTo("/*"))); + //testing the order of listener classes generated + assertThat(web, hasXPath("/web-app/listener[2]/listener-class", equalTo("org.apache.knox.gateway.services.GatewayServicesContextListener"))); + assertThat(web, hasXPath("/web-app/listener[3]/listener-class", equalTo("org.apache.knox.gateway.services.GatewayMetricsServletContextListener"))); + assertThat(web, hasXPath("/web-app/listener[4]/listener-class", equalTo("org.apache.knox.gateway.ha.provider" + + ".HaServletContextListener"))); + assertThat(web, hasXPath("/web-app/listener[5]/listener-class", equalTo("org.apache.knox.gateway.filter" + + ".rewrite.api.UrlRewriteServletContextListener"))); + } + + @Test( timeout = LONG_TIMEOUT ) + public void testDeploymentWithServiceParams() throws Exception { + LOG_ENTER(); + GatewayConfig config = new GatewayTestConfig(); + File targetDir = new File(System.getProperty("user.dir"), "target"); + File gatewayDir = new File(targetDir, "gateway-home-" + UUID.randomUUID()); + gatewayDir.mkdirs(); + ((GatewayTestConfig) config).setGatewayHomeDir(gatewayDir.getAbsolutePath()); + File deployDir = new File(config.getGatewayDeploymentDir()); + deployDir.mkdirs(); - addStacksDir(config, targetDir); + + DefaultGatewayServices srvcs = new DefaultGatewayServices(); + Map<String, String> options = new HashMap<>(); + options.put("persist-master", "false"); + options.put("master", "password"); + try { + DeploymentFactory.setGatewayServices(srvcs); + srvcs.init(config, options); + } catch (ServiceLifecycleException e) { + e.printStackTrace(); // I18N not required. + } + + Service service; + Param param; + Topology topology = new Topology(); + topology.setName( "test-cluster" ); + + service = new Service(); + service.setRole( "HIVE" ); + service.setUrls( Arrays.asList( new String[]{ "http://hive-host:50001/" } ) ); + param = new Param(); + param.setName( "someparam" ); + param.setValue( "somevalue" ); + service.addParam( param ); + topology.addService( service ); + + service = new Service(); + service.setRole( "WEBHBASE" ); + service.setUrls( Arrays.asList( new String[]{ "http://hbase-host:50002/" } ) ); + param = new Param(); + param.setName( "replayBufferSize" ); + param.setValue( "33" ); + service.addParam( param ); + topology.addService( service ); + + service = new Service(); + service.setRole( "OOZIE" ); + service.setUrls( Arrays.asList( new String[]{ "http://hbase-host:50003/" } ) ); + param = new Param(); + param.setName( "otherparam" ); + param.setValue( "65" ); + service.addParam( param ); + topology.addService( service ); + + EnterpriseArchive war = DeploymentFactory.createDeployment( config, topology ); + Document doc = XmlUtils.readXml( war.get( "%2F/WEB-INF/gateway.xml" ).getAsset().openStream() ); + // dump( doc ); + + Node resourceNode, filterNode, paramNode; + String value; + + resourceNode = node( doc, "gateway/resource[role/text()='HIVE']" ); + assertThat( resourceNode, is(not(nullValue()))); + filterNode = node( resourceNode, "filter[role/text()='dispatch']" ); + assertThat( filterNode, is(not(nullValue()))); + paramNode = node( filterNode, "param[name/text()='someparam']" ); + value = value( paramNode, "value/text()" ); + assertThat( value, is( "somevalue" ) ) ; + + resourceNode = node( doc, "gateway/resource[role/text()='WEBHBASE']" ); + assertThat( resourceNode, is(not(nullValue()))); + filterNode = node( resourceNode, "filter[role/text()='dispatch']" ); + assertThat( filterNode, is(not(nullValue()))); + paramNode = node( filterNode, "param[name/text()='replayBufferSize']" ); + value = value( paramNode, "value/text()" ); + assertThat( value, is( "33" ) ) ; + + resourceNode = node( doc, "gateway/resource[role/text()='OOZIE']" ); + assertThat( resourceNode, is(not(nullValue()))); + filterNode = node( resourceNode, "filter[role/text()='dispatch']" ); + assertThat( filterNode, is(not(nullValue()))); + paramNode = node( filterNode, "param[name/text()='otherparam']" ); + value = value( paramNode, "value/text()" ); + assertThat( value, is( "65" ) ) ; + + FileUtils.deleteQuietly( deployDir ); + + LOG_EXIT(); + } + + @Test( timeout = MEDIUM_TIMEOUT ) + public void testDeploymentWithApplication() throws Exception { + LOG_ENTER(); + GatewayConfig config = new GatewayTestConfig(); + File targetDir = new File(System.getProperty("user.dir"), "target"); + File gatewayDir = new File(targetDir, "gateway-home-" + UUID.randomUUID()); + gatewayDir.mkdirs(); + ((GatewayTestConfig) config).setGatewayHomeDir(gatewayDir.getAbsolutePath()); + File deployDir = new File(config.getGatewayDeploymentDir()); + deployDir.mkdirs(); - addStacksDir(config, targetDir); + URL serviceUrl = TestUtils.getResourceUrl( DeploymentFactoryFuncTest.class, "test-apps/minimal-test-app/service.xml" ); + File serviceFile = new File( serviceUrl.toURI() ); + File appsDir = serviceFile.getParentFile().getParentFile(); + ((GatewayTestConfig)config).setGatewayApplicationsDir(appsDir.getAbsolutePath()); + + DefaultGatewayServices srvcs = new DefaultGatewayServices(); + Map<String, String> options = new HashMap<>(); + options.put("persist-master", "false"); + options.put("master", "password"); + try { + DeploymentFactory.setGatewayServices(srvcs); + srvcs.init(config, options); + } catch (ServiceLifecycleException e) { + e.printStackTrace(); // I18N not required. + } + + Topology topology = new Topology(); + topology.setName( "test-topology" ); + + Application app; + + app = new Application(); + app.setName( "minimal-test-app" ); + app.addUrl( "/minimal-test-app-path" ); + topology.addApplication( app ); + + EnterpriseArchive archive = DeploymentFactory.createDeployment( config, topology ); + assertThat( archive, notNullValue() ); + + Document doc; + + doc = XmlUtils.readXml( archive.get( "META-INF/topology.xml" ).getAsset().openStream() ); + assertThat( doc, notNullValue() ); + + doc = XmlUtils.readXml( archive.get( "%2Fminimal-test-app-path/WEB-INF/gateway.xml" ).getAsset().openStream() ); + assertThat( doc, notNullValue() ); + //dump( doc ); + assertThat( doc, hasXPath("/gateway/resource/pattern", equalTo("/**?**"))); + assertThat( doc, hasXPath("/gateway/resource/filter[1]/role", equalTo("xforwardedheaders"))); + assertThat( doc, hasXPath("/gateway/resource/filter[1]/name", equalTo("XForwardedHeaderFilter"))); + assertThat( doc, hasXPath("/gateway/resource/filter[1]/class", equalTo(XForwardedHeaderFilter.class.getName()))); + assertThat( doc, hasXPath("/gateway/resource/filter[2]/role", equalTo("rewrite"))); + assertThat( doc, hasXPath("/gateway/resource/filter[2]/name", equalTo("url-rewrite"))); + assertThat( doc, hasXPath("/gateway/resource/filter[2]/class", equalTo(UrlRewriteServletFilter.class.getName()))); + + LOG_EXIT(); + } + + @Test( timeout = MEDIUM_TIMEOUT ) + public void testDeploymentWithServicesAndApplications() throws Exception { + LOG_ENTER(); + GatewayConfig config = new GatewayTestConfig(); + File targetDir = new File(System.getProperty("user.dir"), "target"); + File gatewayDir = new File(targetDir, "gateway-home-" + UUID.randomUUID()); + gatewayDir.mkdirs(); + ((GatewayTestConfig) config).setGatewayHomeDir(gatewayDir.getAbsolutePath()); + File deployDir = new File(config.getGatewayDeploymentDir()); + deployDir.mkdirs(); - addStacksDir(config, targetDir); + URL serviceUrl = TestUtils.getResourceUrl( DeploymentFactoryFuncTest.class, "test-apps/minimal-test-app/service.xml" ); + File serviceFile = new File( serviceUrl.toURI() ); + File appsDir = serviceFile.getParentFile().getParentFile(); + ((GatewayTestConfig)config).setGatewayApplicationsDir(appsDir.getAbsolutePath()); + + DefaultGatewayServices srvcs = new DefaultGatewayServices(); + Map<String, String> options = new HashMap<>(); + options.put("persist-master", "false"); + options.put("master", "password"); + try { + DeploymentFactory.setGatewayServices(srvcs); + srvcs.init(config, options); + } catch (ServiceLifecycleException e) { + e.printStackTrace(); // I18N not required. + } + + Topology topology = new Topology(); + topology.setName( "test-topology" ); + + Application app; + + topology.setName( "test-cluster" ); + Service service = new Service(); + service.setRole( "WEBHDFS" ); + service.addUrl( "http://localhost:50070/test-service-url" ); + topology.addService( service ); + + app = new Application(); + app.setName( "minimal-test-app" ); + app.addUrl( "/minimal-test-app-path-one" ); + topology.addApplication( app ); + + app.setName( "minimal-test-app" ); + app.addUrl( "/minimal-test-app-path-two" ); + topology.addApplication( app ); + + EnterpriseArchive archive = DeploymentFactory.createDeployment( config, topology ); + assertThat( archive, notNullValue() ); + + Document doc; + org.jboss.shrinkwrap.api.Node node; + + node = archive.get( "META-INF/topology.xml" ); + assertThat( "Find META-INF/topology.xml", node, notNullValue() ); + doc = XmlUtils.readXml( node.getAsset().openStream() ); + assertThat( "Parse META-INF/topology.xml", doc, notNullValue() ); + + node = archive.get( "%2F" ); + assertThat( "Find %2F", node, notNullValue() ); + node = archive.get( "%2F/WEB-INF/gateway.xml" ); + assertThat( "Find %2F/WEB-INF/gateway.xml", node, notNullValue() ); + doc = XmlUtils.readXml( node.getAsset().openStream() ); + assertThat( "Parse %2F/WEB-INF/gateway.xml", doc, notNullValue() ); + + WebArchive war = archive.getAsType( WebArchive.class, "%2Fminimal-test-app-path-one" ); + assertThat( "Find %2Fminimal-test-app-path-one", war, notNullValue() ); + node = war.get( "/WEB-INF/gateway.xml" ); + assertThat( "Find %2Fminimal-test-app-path-one/WEB-INF/gateway.xml", node, notNullValue() ); + doc = XmlUtils.readXml( node.getAsset().openStream() ); + assertThat( "Parse %2Fminimal-test-app-path-one/WEB-INF/gateway.xml", doc, notNullValue() ); + + war = archive.getAsType( WebArchive.class, "%2Fminimal-test-app-path-two" ); + assertThat( "Find %2Fminimal-test-app-path-two", war, notNullValue() ); + node = war.get( "/WEB-INF/gateway.xml" ); + assertThat( "Find %2Fminimal-test-app-path-two/WEB-INF/gateway.xml", node, notNullValue() ); + doc = XmlUtils.readXml( node.getAsset().openStream() ); + assertThat( "Parse %2Fminimal-test-app-path-two/WEB-INF/gateway.xml", doc, notNullValue() ); + + LOG_EXIT(); + } + - private void addStacksDir(GatewayConfig config, File targetDir) { - File stacksDir = new File( config.getGatewayServicesDir() ); - stacksDir.mkdirs(); - //TODO: [sumit] This is a hack for now, need to find a better way to locate the source resources for 'stacks' to be tested - String pathToStacksSource = "gateway-service-definitions/src/main/resources/services"; - File stacksSourceDir = new File( targetDir.getParent(), pathToStacksSource); - if (!stacksSourceDir.exists()) { - stacksSourceDir = new File( targetDir.getParentFile().getParent(), pathToStacksSource); - } - if (stacksSourceDir.exists()) { - try { - FileUtils.copyDirectoryToDirectory(stacksSourceDir, stacksDir); - } catch ( IOException e) { - fail(e.getMessage()); - } - } - - } - + private Node node( Node scope, String expression ) throws XPathExpressionException { + return (Node)XPathFactory.newInstance().newXPath().compile( expression ).evaluate( scope, XPathConstants.NODE ); + } + + private String value( Node scope, String expression ) throws XPathExpressionException { + return XPathFactory.newInstance().newXPath().compile( expression ).evaluate( scope ); + } + + private static void dump( org.jboss.shrinkwrap.api.Node node, String prefix ) { + System.out.println( prefix + ": " + node.getPath() ); + Set<org.jboss.shrinkwrap.api.Node> children = node.getChildren(); + if( children != null && !children.isEmpty() ) { + for( org.jboss.shrinkwrap.api.Node child : children ) { + dump( child, prefix + " " ); + } + } + } + + private static void dump( Archive archive ) { + Map<ArchivePath,org.jboss.shrinkwrap.api.Node> content = archive.getContent(); + for( Map.Entry<ArchivePath,org.jboss.shrinkwrap.api.Node> entry : content.entrySet() ) { + dump( entry.getValue(), " " ); + } + } + +} http://git-wip-us.apache.org/repos/asf/knox/blob/50f46e9e/gateway-util-common/src/main/java/org/apache/knox/gateway/util/IpAddressValidator.java ---------------------------------------------------------------------- diff --cc gateway-util-common/src/main/java/org/apache/knox/gateway/util/IpAddressValidator.java index 158f63a,0000000..94ec9be mode 100644,000000..100644 --- a/gateway-util-common/src/main/java/org/apache/knox/gateway/util/IpAddressValidator.java +++ b/gateway-util-common/src/main/java/org/apache/knox/gateway/util/IpAddressValidator.java @@@ -1,116 -1,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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.knox.gateway.util; + +import java.util.ArrayList; +import java.util.Collections; + +/** + * Validate a given IP Address against a list of comma separated list of addresses. + */ +public class IpAddressValidator { + + /** + * The parsed list of ip addresses + */ + private ArrayList<String> ipaddr = new ArrayList<String>(); + + /** + * IP addresses from the ipaddr list that contain a wildcard character '*' + */ + private ArrayList<String> wildCardIPs = new ArrayList<String>(); + + /** + * Optimization based on empty IP address list or an explicit '*' wildcard + */ + private boolean anyIP = true; + + /** + * ctor - initialize an instance with the given ip address list + */ + public IpAddressValidator(String commaSeparatedIpAddresses) { + if (commaSeparatedIpAddresses == null) { + anyIP = true; + return; + } + + parseIpAddesses(commaSeparatedIpAddresses); + } + + /** + * @param commaSeparatedIpAddresses + */ + private void parseIpAddesses(String commaSeparatedIpAddresses) { + String[] ips = commaSeparatedIpAddresses.split(","); + ipaddr = new ArrayList<String>(); + wildCardIPs = new ArrayList<String>(); + Collections.addAll(ipaddr, ips); + if (!ipaddr.contains("*")) { + anyIP = false; + // check whether there are any wildcarded ip's - example: 192.* or 192.168.* or 192.168.1.* + for (String addr : ipaddr) { + if (addr.contains("*")) { + wildCardIPs.add(addr.substring(0, addr.lastIndexOf('*'))); + } + } + } + } + + public boolean validateIpAddress(String addr) { + boolean valid = false; + if (addr == null) { + // LJM TODO: log as possible programming error + return false; + } + + if (anyIP) { + valid = true; + } + else { + if (ipaddr.contains(addr)) { + valid = true; + } + else { + // check for wildcards if there are wildcardIP acls configured - if (wildCardIPs.size() > 0) { ++ if (!wildCardIPs.isEmpty()) { + for (String ip : wildCardIPs) { + if (addr.startsWith(ip)) { + valid = true; + break; + } + } + } + } + } + return valid; + } + + /** + * @return + */ + public boolean allowsAnyIP() { + return anyIP; + } + + /** + * @return + */ + public ArrayList<String> getIPAddresses() { + return ipaddr; + } +} http://git-wip-us.apache.org/repos/asf/knox/blob/50f46e9e/gateway-util-common/src/test/java/org/apache/knox/gateway/util/IpAddressValidatorTest.java ---------------------------------------------------------------------- diff --cc gateway-util-common/src/test/java/org/apache/knox/gateway/util/IpAddressValidatorTest.java index fbf4196,0000000..531decf mode 100644,000000..100644 --- a/gateway-util-common/src/test/java/org/apache/knox/gateway/util/IpAddressValidatorTest.java +++ b/gateway-util-common/src/test/java/org/apache/knox/gateway/util/IpAddressValidatorTest.java @@@ -1,78 -1,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.util; + +import org.junit.Test; + - import junit.framework.TestCase; + - public class IpAddressValidatorTest extends TestCase { ++public class IpAddressValidatorTest extends org.junit.Assert { + String test = "127.0.0.1,193.*,192.168.1.*,0:0:0:0:0:0:0:1,0:0:0:0:0:0:*"; + String testWeirdConfig = ",127.0.0.1,,193.*,192.168.1.*,29*"; + String testNullConfig = null; + + @Test + public void testExplicitIpAddress() throws Exception { + IpAddressValidator ipv = new IpAddressValidator(test); + + assertTrue("Should have validated 127.0.0.1", ipv.validateIpAddress("127.0.0.1")); + assertFalse("Should not have validated 127.0.0.2", ipv.validateIpAddress("127.0.0.2")); + + assertTrue("Should have validated 0:0:0:0:0:0:0:1", ipv.validateIpAddress("0:0:0:0:0:0:0:1")); + assertFalse("Should not have validated 1:0:0:0:0:0:0:1", ipv.validateIpAddress("1:0:0:0:0:0:0:1")); + + ipv = new IpAddressValidator(testWeirdConfig); + + assertTrue("Should have validated 127.0.0.1", ipv.validateIpAddress("127.0.0.1")); + assertFalse("Should not have validated 127.0.0.2", ipv.validateIpAddress("127.0.0.2")); + } + + @Test + public void testNullConfig() throws Exception { + IpAddressValidator ipv = new IpAddressValidator(testNullConfig); + + // null config indicatest that all IPs are accepted + assertTrue("Should have validated 127.0.0.1", ipv.validateIpAddress("127.0.0.1")); + } + + @Test + public void testNullRemoteIP() throws Exception { + IpAddressValidator ipv = new IpAddressValidator(testNullConfig); + + assertFalse("Should not have validated null", ipv.validateIpAddress(null)); + } + + @Test + public void testWildcardIpAddress() throws Exception { + IpAddressValidator ipv = new IpAddressValidator(test); + + assertTrue("Should have validated 192.168.1.1", ipv.validateIpAddress("192.168.1.1")); + assertFalse("Should not have validated 192.168.2.1", ipv.validateIpAddress("192.168.2.1")); + + assertTrue("Should have validated 0:0:0:0:0:0:0:2", ipv.validateIpAddress("0:0:0:0:0:0:0:2")); + assertFalse("Should not have validated 0:0:0:0:0:0:2:2", ipv.validateIpAddress("0:0:0:0:0:2:2:2")); + + assertTrue("Should have validated 193.168.1.1", ipv.validateIpAddress("193.168.1.1")); + assertFalse("Should not have validated 194.168.2.1", ipv.validateIpAddress("194.168.2.1")); + + ipv = new IpAddressValidator(testWeirdConfig); + + assertTrue("Should have validated 293.168.1.1", ipv.validateIpAddress("293.168.1.1")); + } + +} http://git-wip-us.apache.org/repos/asf/knox/blob/50f46e9e/gateway-util-common/src/test/java/org/apache/knox/gateway/util/JsonUtilsTest.java ---------------------------------------------------------------------- diff --cc gateway-util-common/src/test/java/org/apache/knox/gateway/util/JsonUtilsTest.java index c42911a,0000000..7c2cdf6 mode 100644,000000..100644 --- a/gateway-util-common/src/test/java/org/apache/knox/gateway/util/JsonUtilsTest.java +++ b/gateway-util-common/src/test/java/org/apache/knox/gateway/util/JsonUtilsTest.java @@@ -1,57 -1,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.util; + +import java.util.HashMap; + +import org.junit.Test; + - import junit.framework.TestCase; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; + - public class JsonUtilsTest extends TestCase { ++public class JsonUtilsTest extends org.junit.Assert { + String expiresIn = "\"expires_in\":\"1364487943100\""; + String tokenType = "\"token_type\":\"Bearer\""; + String accessToken = "\"access_token\":\"ksdfh3489tyiodhfjk\""; + String test = '{' + expiresIn + "," + tokenType + "," + accessToken + '}'; + + @Test + public void testRenderAsJson() throws Exception { + HashMap map = new HashMap(); + map.put("access_token", "ksdfh3489tyiodhfjk"); + map.put("token_type", "Bearer"); + map.put( "expires_in", "1364487943100" ); + + String result = JsonUtils.renderAsJsonString(map); + + assertThat( result, containsString( expiresIn ) ); + assertThat( result, containsString( tokenType ) ); + assertThat( result, containsString( accessToken ) ); + } + + @Test + public void testGetMapFromString() throws Exception { + HashMap map = (HashMap) JsonUtils.getMapFromJsonString(test); + assertEquals("ksdfh3489tyiodhfjk", map.get("access_token")); + assertEquals("Bearer", map.get("token_type")); + assertEquals("1364487943100", map.get("expires_in")); + } + +} http://git-wip-us.apache.org/repos/asf/knox/blob/50f46e9e/gateway-util-common/src/test/java/org/apache/knox/gateway/util/UrlsTest.java ---------------------------------------------------------------------- diff --cc gateway-util-common/src/test/java/org/apache/knox/gateway/util/UrlsTest.java index 6354919,0000000..60d7c0c mode 100644,000000..100644 --- a/gateway-util-common/src/test/java/org/apache/knox/gateway/util/UrlsTest.java +++ b/gateway-util-common/src/test/java/org/apache/knox/gateway/util/UrlsTest.java @@@ -1,98 -1,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 + * <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.util; + ++import static org.junit.Assert.assertEquals; ++ +import org.junit.Assert; +import org.junit.Test; + - import static junit.framework.TestCase.assertEquals; - +public class UrlsTest { + + /** + * Domain name creation follows the following algorithm: + * 1. if the incoming request hostname endsWith a configured domain suffix return the suffix - with prefixed dot + * 2. if the request hostname is an ip address return null for default domain + * 3. if the request hostname has less than 3 dots return null for default domain + * 4. if request hostname has more than two dots strip the first element and return the remainder as domain + * @throws Exception + */ + @Test + public void testDomainNameCreation() throws Exception { + // determine parent domain and wildcard the cookie domain with a dot prefix + Assert.assertTrue(Urls.getDomainName("http://www.local.com", null).equals(".local.com")); + Assert.assertTrue(Urls.getDomainName("http://ljm.local.com", null).equals(".local.com")); + + // test scenarios that will leverage the default cookie domain + Assert.assertEquals(Urls.getDomainName("http://local.home", null), null); + Assert.assertEquals(Urls.getDomainName("http://localhost", null), null); // chrome may not allow this + + Assert.assertTrue(Urls.getDomainName("http://local.home.test.com", null).equals(".home.test.com")); + + // check the suffix config feature + Assert.assertTrue(Urls.getDomainName("http://local.home.test.com", ".test.com").equals(".test.com")); + Assert.assertEquals(".novalocal", Urls.getDomainName("http://34526yewt.novalocal", ".novalocal")); + + // make sure that even if the suffix doesn't start with a dot that the domain does + // if we are setting a domain suffix then we want a specific domain for SSO and that + // will require all hosts in the domain in order for it to work + Assert.assertEquals(".novalocal", Urls.getDomainName("http://34526yewt.novalocal", "novalocal")); + + // ip addresses can not be wildcarded - may be a completely different domain + Assert.assertEquals(Urls.getDomainName("http://127.0.0.1", null), null); + + /* Make sure we handle encoded characters properly here */ + Assert.assertTrue(Urls.getDomainName("https://www.local.com:8443/gateway/manager/admin-ui?limit=25&query=hive_table+where+name%3D%22table_1%22", null).equals(".local.com")); + /* Make sure we handle un-encoded characters safely */ + Assert.assertTrue(Urls.getDomainName("https://www.local.com:8443/gateway/manager/admin-ui/?limit=25&query=\"table_1\"", null).equals(".local.com")); + + } + + @Test + public void testTrimLeadingAndTrailingSlash() { + assertEquals( "", Urls.trimLeadingAndTrailingSlash( null ) ); + assertEquals( "", Urls.trimLeadingAndTrailingSlash( "" ) ); + assertEquals( "", Urls.trimLeadingAndTrailingSlash( "/" ) ); + assertEquals( "", Urls.trimLeadingAndTrailingSlash( "//" ) ); + assertEquals( "x", Urls.trimLeadingAndTrailingSlash( "x" ) ); + assertEquals( "x/x", Urls.trimLeadingAndTrailingSlash( "x/x" ) ); + assertEquals( "x", Urls.trimLeadingAndTrailingSlash( "/x/" ) ); + assertEquals( "x/x", Urls.trimLeadingAndTrailingSlash( "x/x" ) ); + } + + @Test + public void testTrimLeadingAndTrailingSlashJoin() throws Exception { + assertEquals( "", Urls.trimLeadingAndTrailingSlashJoin( null ) ); + assertEquals( "", Urls.trimLeadingAndTrailingSlashJoin( "" ) ); + assertEquals( "", Urls.trimLeadingAndTrailingSlashJoin( "", "" ) ); + assertEquals( "x", Urls.trimLeadingAndTrailingSlashJoin( "x" ) ); + assertEquals( "x", Urls.trimLeadingAndTrailingSlashJoin( "x", "" ) ); + assertEquals( "x", Urls.trimLeadingAndTrailingSlashJoin( "", "x", "" ) ); + assertEquals( "x/x", Urls.trimLeadingAndTrailingSlashJoin( "", "x", "", "", "x" ) ); + assertEquals( "x/x", Urls.trimLeadingAndTrailingSlashJoin( null, "x", null, null, "x" ) ); + assertEquals( "x/y/z", Urls.trimLeadingAndTrailingSlashJoin( "x", "y", "z" ) ); + } + + @Test + public void testURLEncoding() throws Exception { + assertEquals( "%26", Urls.encode( "&" ) ); + assertEquals( "&query=hive_table", Urls.decode( "%26query=hive_table" ) ); + assertEquals( "%3F", Urls.encode( "?" ) ); + } + +} http://git-wip-us.apache.org/repos/asf/knox/blob/50f46e9e/gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/AdapterSampleTest.java ---------------------------------------------------------------------- diff --cc gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/AdapterSampleTest.java index 562ed18,0000000..a97ccb8 mode 100755,000000..100755 --- a/gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/AdapterSampleTest.java +++ b/gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/AdapterSampleTest.java @@@ -1,57 -1,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.config; + +import org.junit.Test; + - import java.util.Hashtable; ++import java.util.Map; ++import java.util.concurrent.ConcurrentHashMap; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +public class AdapterSampleTest { + - public static class Target { ++ private static class Target { + @Configure + private String username = null; + } + - public static class Adapter implements ConfigurationAdapter { - private Hashtable config; - public Adapter( Hashtable config ) { ++ private static class Adapter implements ConfigurationAdapter { ++ private Map<String, Object> config; ++ public Adapter( Map<String, Object> config ) { + this.config = config; + } + @Override + public Object getConfigurationValue( String name ) throws ConfigurationException { + Object value = config.get( name.toUpperCase() ); + return value == null ? null : value.toString(); + } + } + - static Hashtable config = new Hashtable(); - static{ config.put( "USERNAME", "somebody" ); } ++ private static final Map<String, Object> CONFIG = new ConcurrentHashMap<>(); ++ static { ++ CONFIG.put( "USERNAME", "somebody" ); ++ } + + @Test + public void sample() { + Target target = new Target(); - Adapter adapter = new Adapter( config ); ++ Adapter adapter = new Adapter( CONFIG ); + ConfigurationInjectorBuilder.configuration().target( target ).source( adapter ).inject(); + assertThat( target.username, is( "somebody" ) ); + } + +} http://git-wip-us.apache.org/repos/asf/knox/blob/50f46e9e/gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/FuncTest.java ---------------------------------------------------------------------- diff --cc gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/FuncTest.java index 7c5df0c,0000000..d240506 mode 100755,000000..100755 --- a/gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/FuncTest.java +++ b/gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/FuncTest.java @@@ -1,378 -1,0 +1,378 @@@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.knox.gateway.config; + +import org.apache.knox.gateway.config.impl.MappedConfigurationBinding; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.core.AllOf.allOf; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.fail; + +public class FuncTest { + + public static class TestBean { + @Configure + String stringMember = "stringDefault"; + + @Configure + int intMember = 1; + + @Configure + Integer integerMember = Integer.valueOf( 1 ); + + @Configure + public void setStringProp( String s ) { + stringPropField = s; + } + protected String stringPropField = "stringDefault"; + + @Configure + @Alias("altStringProp") + public void setNamedStringProp( String s ) { + stringPropFieldAlt = s; + } + protected String stringPropFieldAlt = "stringDefault"; + + @Configure + public void setNamedArgMethod( @Configure @Alias("altArgStringProp") String s ) { + stringPropFieldAltArg = s; + } + protected String stringPropFieldAltArg = "stringDefault"; + + @Configure + public void setMultiArgs( + @Configure @Alias("multiArg1") String s, + @Configure @Alias("multiArg2") Integer i, + @Configure @Alias("multiArg3") int n ) { + multiArgStringField = s; + multiArgIntegerField = i; + multiArgIntField = n; + } + String multiArgStringField = "default"; + Integer multiArgIntegerField = 0; + int multiArgIntField = 0; + + } + + @Test + public void testMapOfStrings() { + + Map<String,String> testConfig = new HashMap<>(); + testConfig.put( "stringMember", "stringValue" ); + testConfig.put( "intMember", "2" ); + testConfig.put( "integerMember", "2" ); + testConfig.put( "stringProp", "stringValue" ); + testConfig.put( "altStringProp", "stringValue" ); + testConfig.put( "altArgStringProp", "stringValue" ); + testConfig.put( "multiArg1", "stringValue" ); + testConfig.put( "multiArg2", "42" ); + testConfig.put( "multiArg3", "42" ); + + TestBean testBean = new TestBean(); + + ConfigurationInjectorBuilder.configuration().target( testBean ).source( testConfig ).inject(); + + assertThat( testBean.stringMember, is( "stringValue" ) ); + assertThat( testBean.intMember, is( 2 ) ); - assertThat( testBean.integerMember, is( new Integer(2) ) ); ++ assertThat( testBean.integerMember, is( Integer.valueOf(2) ) ); + assertThat( testBean.stringPropField, is( "stringValue" ) ); + assertThat( testBean.stringPropFieldAlt, is( "stringValue" ) ); + assertThat( testBean.stringPropFieldAltArg, is( "stringValue" ) ); + assertThat( testBean.multiArgStringField, is( "stringValue" ) ); + assertThat( testBean.multiArgIntegerField, is( 42 ) ); + assertThat( testBean.multiArgIntField, is( 42 ) ); + } + + @Test + public void testProperties() { + + Properties testConfig = new Properties(); + testConfig.put( "stringMember", "stringValue" ); + testConfig.put( "intMember", "2" ); + testConfig.put( "integerMember", "2" ); + testConfig.put( "stringProp", "stringValue" ); + testConfig.put( "altStringProp", "stringValue" ); + testConfig.put( "altArgStringProp", "stringValue" ); + testConfig.put( "multiArg1", "stringValue" ); + testConfig.put( "multiArg2", "42" ); + testConfig.put( "multiArg3", "42" ); + + TestBean testBean = new TestBean(); + + ConfigurationInjectorBuilder.configuration().target( testBean ).source( testConfig ).inject(); + + assertThat( testBean.stringMember, is( "stringValue" ) ); + assertThat( testBean.intMember, is( 2 ) ); - assertThat( testBean.integerMember, is( new Integer(2) ) ); ++ assertThat( testBean.integerMember, is( Integer.valueOf(2) ) ); + assertThat( testBean.stringPropField, is( "stringValue" ) ); + assertThat( testBean.stringPropFieldAlt, is( "stringValue" ) ); + assertThat( testBean.stringPropFieldAltArg, is( "stringValue" ) ); + assertThat( testBean.multiArgStringField, is( "stringValue" ) ); + assertThat( testBean.multiArgIntegerField, is( 42 ) ); + assertThat( testBean.multiArgIntField, is( 42 ) ); + } + + public static class TestAdapter implements ConfigurationAdapter { + + private Map<String,String> config; + + public TestAdapter( Map<String,String> config ) { + this.config = config; + } + + @Override + public String getConfigurationValue( String name ) { + return config.get( name ); + } + + } + + @Test + public void testExplicitProvider() { + + Map<String,String> testConfig = new HashMap<>(); + testConfig.put( "stringMember", "stringValue" ); + testConfig.put( "intMember", "2" ); + testConfig.put( "integerMember", "2" ); + testConfig.put( "stringProp", "stringValue" ); + testConfig.put( "altStringProp", "stringValue" ); + testConfig.put( "altArgStringProp", "stringValue" ); + testConfig.put( "multiArg1", "stringValue" ); + testConfig.put( "multiArg2", "42" ); + testConfig.put( "multiArg3", "42" ); + + TestBean testBean = new TestBean(); + + ConfigurationInjectorBuilder.configuration().target( testBean ).source( new TestAdapter( testConfig ) ).inject(); + + assertThat( testBean.stringMember, is( "stringValue" ) ); + assertThat( testBean.intMember, is( 2 ) ); - assertThat( testBean.integerMember, is( new Integer(2) ) ); ++ assertThat( testBean.integerMember, is( Integer.valueOf(2) ) ); + assertThat( testBean.stringPropField, is( "stringValue" ) ); + assertThat( testBean.stringPropFieldAlt, is( "stringValue" ) ); + assertThat( testBean.stringPropFieldAltArg, is( "stringValue" ) ); + assertThat( testBean.multiArgStringField, is( "stringValue" ) ); + assertThat( testBean.multiArgIntegerField, is( 42 ) ); + assertThat( testBean.multiArgIntField, is( 42 ) ); + } + + @Test + public void testMapOfObjects() { + + Map<Object,Object> testConfig = new HashMap<>(); + testConfig.put( "stringMember", "stringValue" ); + testConfig.put( "intMember", 42 ); - testConfig.put( "integerMember", new Integer(42) ); ++ testConfig.put( "integerMember", Integer.valueOf(42) ); + testConfig.put( "stringProp", "stringValue" ); + testConfig.put( "altStringProp", "stringValue" ); + testConfig.put( "altArgStringProp", "stringValue" ); + testConfig.put( "multiArg1", "stringValue" ); - testConfig.put( "multiArg2", new Integer(42) ); ++ testConfig.put( "multiArg2", Integer.valueOf(42) ); + testConfig.put( "multiArg3", "42" ); + + TestBean testBean = new TestBean(); + + ConfigurationInjectorBuilder.configuration().target( testBean ).source( testConfig ).inject(); + + assertThat( testBean.stringMember, is( "stringValue" ) ); + assertThat( testBean.intMember, is( 42 ) ); - assertThat( testBean.integerMember, is( new Integer(42) ) ); ++ assertThat( testBean.integerMember, is( Integer.valueOf(42) ) ); + assertThat( testBean.stringPropField, is( "stringValue" ) ); + assertThat( testBean.stringPropFieldAlt, is( "stringValue" ) ); + assertThat( testBean.stringPropFieldAltArg, is( "stringValue" ) ); + assertThat( testBean.multiArgStringField, is( "stringValue" ) ); + assertThat( testBean.multiArgIntegerField, is( 42 ) ); + assertThat( testBean.multiArgIntField, is( 42 ) ); + } + + public class Target { + @Configure @Alias("user.name") + private String user; + } + + public class Adapter implements ConfigurationAdapter { + @Override + public Object getConfigurationValue( String name ) throws ConfigurationException { + return System.getProperty( name ); + } + } + + @Test + public void testFactoryConfigurationDirect() { + Target target = new Target(); + ConfigurationInjectorBuilder.configuration().target( target ).source( System.getProperties() ).inject(); + assertThat( target.user, is( System.getProperty( "user.name" ) ) ); + } + + @Test + public void testFactoryConfigurationAdapter() { + Target target = new Target(); + ConfigurationInjectorBuilder.configuration().target( target ).source( new Adapter() ).inject(); + assertThat( target.user, is( System.getProperty( "user.name" ) ) ); + } + + @Test + public void testMissingRequiredFieldConfiguration() { + class RequiredFieldTarget { + @Configure + private String required; + } + RequiredFieldTarget target = new RequiredFieldTarget(); + try { + ConfigurationInjectorBuilder.configuration().target( target ).source( System.getProperties() ).inject(); + fail( "Expected an exception because the configuration values could not be populated." ); + } catch ( ConfigurationException e ) { + assertThat( e.getMessage(), allOf(containsString("Failed"),containsString( "find" ),containsString( "required" )) ); + } + } + + @Test + public void testMissingOptionalFieldConfiguration() { + class OptionalFieldTarget { + @Configure + @Optional + private String optional = "default"; + } + OptionalFieldTarget target = new OptionalFieldTarget(); + ConfigurationInjectorBuilder.configuration().target( target ).source( System.getProperties() ).inject(); + assertThat( target.optional, is("default") ); + } + + @Test + public void testMissingRequiredConfigurationParameter() { + class Target { + private String field; + @Configure + public void setRequired(String value) { + field = value; + } + } + Target target = new Target(); + try { + ConfigurationInjectorBuilder.configuration().target( target ).source( System.getProperties() ).inject(); + fail( "Expected an exception because the configuration values could not be populated." ); + } catch ( ConfigurationException e ) { + assertThat( e.getMessage(), allOf(containsString("Failed"),containsString( "find" ),containsString( "required" )) ); + } + } + + @Test + public void testMissingRequiredConfigurationParameterWithDefault() { + class Target { + private String field; + @Configure + public void setRequired(@Default("default")String value) { + field = value; + } + } + Target target = new Target(); + ConfigurationInjectorBuilder.configuration().target( target ).source( System.getProperties() ).inject(); + assertThat( target.field, is( "default" ) ); + } + + @Test + public void testTwoMissingRequiredConfigurationParameterWithDefault() { + class Target { + private String field1; + private String field2; + @Configure + public void setRequired(@Default("default1")String value1, @Default("default2")String value2) { + field1 = value1; + field2 = value2; + } + } + Target target = new Target(); + ConfigurationInjectorBuilder.configuration().target( target ).source( System.getProperties() ).inject(); + assertThat( target.field1, is( "default1" ) ); + assertThat( target.field2, is("default2") ); + } + + @Test + public void testFieldBinding() { + class Target { + @Configure + private String user; + } + class Binding extends MappedConfigurationBinding { + Binding() { + bind("user","user.name"); + } + } + Target target = new Target(); + Properties source = System.getProperties(); + ConfigurationBinding binding = new Binding(); + ConfigurationInjectorBuilder.configuration().target( target ).source( source ).binding( binding ).inject(); + assertThat( target.user, is(System.getProperty("user.name"))); + + } + + @Test + public void testFieldBindingUsingBuilderBinding() { + class Target { + @Configure + private String user; + } + Target target = new Target(); + Properties source = System.getProperties(); + ConfigurationInjectorBuilder.configuration().target( target ).source( source ).bind( "user", "user.name" ).inject(); + assertThat( target.user, is(System.getProperty("user.name"))); + + } + + @Test + public void testFieldBindingUsingBuilderBindingFactory() { + class Target { + @Configure + private String user; + } + Target target = new Target(); + Properties source = System.getProperties(); + ConfigurationBinding binding = ConfigurationInjectorBuilder + .configuration().bind( "user", "user.name" ).binding(); + ConfigurationInjectorBuilder.configuration().target( target ).source( source ).binding( binding ).inject(); + assertThat( target.user, is( System.getProperty( "user.name" ) ) ); + + } + + public static class UserBean { + public String getPrincipal() { + return "test-user"; + } + } + + @Test + public void testBeanAdapter() { + Target target = new Target(); + UserBean bean = new UserBean(); + ConfigurationInjectorBuilder.configuration() + .target( target ) + .source( bean ) + .bind( "user.name", "principal" ) + .inject(); + assertThat( target.user, is( "test-user" ) ); + + } + +} http://git-wip-us.apache.org/repos/asf/knox/blob/50f46e9e/gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/impl/BeanConfigurationAdapterDescriptorTest.java ---------------------------------------------------------------------- diff --cc gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/impl/BeanConfigurationAdapterDescriptorTest.java index 1295914,0000000..1513eb4 mode 100755,000000..100755 --- a/gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/impl/BeanConfigurationAdapterDescriptorTest.java +++ b/gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/impl/BeanConfigurationAdapterDescriptorTest.java @@@ -1,57 -1,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.config.impl; + +import org.apache.knox.gateway.config.ConfigurationAdapter; +import org.apache.knox.gateway.config.spi.ConfigurationAdapterDescriptor; +import org.junit.Test; + +import java.util.Iterator; +import java.util.Map; +import java.util.ServiceLoader; + - import static junit.framework.TestCase.fail; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasKey; ++import static org.junit.Assert.fail; + +public class BeanConfigurationAdapterDescriptorTest { + + @Test + public void testServiceLoader() { + ServiceLoader<ConfigurationAdapterDescriptor> loader = ServiceLoader.load( ConfigurationAdapterDescriptor.class ); + Iterator<ConfigurationAdapterDescriptor> i = loader.iterator(); + while( i.hasNext() ) { + if( i.next() instanceof BeanConfigurationAdapterDescriptor ) { + return; + } + } + fail( "Failed to load BeanConfigurationAdapterDescriptor" ); + } + + @Test + public void testDescriptor() { + ConfigurationAdapterDescriptor descriptor = new BeanConfigurationAdapterDescriptor(); + Map<Class<?>,Class<? extends ConfigurationAdapter>> map = descriptor.providedConfigurationAdapters(); + assertThat( map, hasKey( (Class)Object.class ) ); + Class<? extends ConfigurationAdapter> type = map.get( Object.class ); + assertThat( + "Descriptor didn't return " + BeanConfigurationAdapter.class.getName(), + type == BeanConfigurationAdapter.class ); + } + +}