KNOX-1676 - Enable PMD for tests
authorKevin Risden <krisden@apache.org>
Wed, 12 Dec 2018 14:58:51 +0000 (09:58 -0500)
committerKevin Risden <krisden@apache.org>
Thu, 13 Dec 2018 16:38:20 +0000 (11:38 -0500)
Signed-off-by: Kevin Risden <krisden@apache.org>
117 files changed:
build-tools/src/main/resources/build-tools/pmd/pmd-ruleset.xml
gateway-adapter/src/test/java/org/apache/hadoop/gateway/shirorealm/KnoxPamRealmTest.java
gateway-demo-ldap/src/test/java/org/apache/knox/gateway/security/ldap/SimpleLdapServerTest.java
gateway-discovery-ambari/src/test/java/org/apache/knox/gateway/topology/discovery/ambari/AmbariConfigurationMonitorTest.java
gateway-discovery-ambari/src/test/java/org/apache/knox/gateway/topology/discovery/ambari/AmbariServiceDiscoveryTest.java
gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/messages/MessagesSubject.java [moved from gateway-provider-security-webappsec/src/test/java/org/apache/knox/gateway/webappsec/CSRFTest.java with 74% similarity]
gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/messages/MessagesTest.java
gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/messages/MessagesTestSubject.java [deleted file]
gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesFormattingSubject.java [moved from gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTestFormattingSubject.java with 96% similarity]
gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesLocaleSubject.java [moved from gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject.java with 95% similarity]
gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesNamedSubject.java [moved from gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTestNamedSubject.java with 95% similarity]
gateway-i18n/src/test/java/org/apache/knox/gateway/i18n/resources/ResourcesTest.java
gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesLocaleSubject.properties [moved from gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject.properties with 100% similarity]
gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesLocaleSubject_en.properties [moved from gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject_en.properties with 100% similarity]
gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesLocaleSubject_en_GB.properties [moved from gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject_en_GB.properties with 100% similarity]
gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesLocaleSubject_en_US.properties [moved from gateway-i18n/src/test/resources/org/apache/knox/gateway/i18n/resources/ResourcesTestLocaleSubject_en_US.properties with 100% similarity]
gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/deploy/HaProviderDeploymentContributorTest.java
gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/AtlasZookeeperURLManagerTest.java
gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/DefaultHaProviderTest.java
gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/HBaseZookeeperURLManagerTest.java
gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/HS2ZookeeperURLManagerTest.java
gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorManagerTest.java
gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/KafkaZookeeperURLManagerTest.java
gateway-provider-ha/src/test/java/org/apache/knox/gateway/ha/provider/impl/SOLRZookeeperURLManagerTest.java
gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/filter/CommonIdentityAssertionFilterTest.java
gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/filter/IdentityAssertionHttpServletRequestWrapperTest.java
gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/function/UsernameFunctionProcessorTest.java
gateway-provider-identity-assertion-pseudo/src/test/java/org/apache/knox/gateway/identityasserter/filter/DefaultIdentityAssertionFilterTest.java
gateway-provider-rewrite-func-inbound-query-param/src/test/java/org/apache/knox/gateway/inboundurl/impl/InboundUrlFunctionProcessorTest.java
gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest.java
gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteRulesDescriptorFactoryTest.java
gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletContextListenerTest.java
gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletFilterTest.java
gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessorTest.java
gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteResponseTest.java
gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlFilterReaderBaseTest.java
gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/json/JsonFilterReaderTest.java
gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReaderTest.java
gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporterTest.java
gateway-provider-security-authz-acls/src/test/java/org/apache/knox/gateway/filter/AclParserTest.java
gateway-provider-security-authz-acls/src/test/java/org/apache/knox/gateway/filter/AclsAuthzFilterTest.java
gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/AbstractJWTFilterTest.java
gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/SSOCookieProviderTest.java
gateway-provider-security-pac4j/src/test/java/org/apache/knox/gateway/pac4j/MockHttpServletResponse.java
gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/HeaderPreAuthFederationFilterTest.java
gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/PreAuthSSOTest.java [deleted file]
gateway-provider-security-preauth/src/test/java/org/apache/knox/gateway/provider/federation/PreAuthServiceTest.java
gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/CompositeEnumerationTest.java
gateway-server-xforwarded-filter/src/test/java/org/apache/knox/gateway/filter/TestFilterChain.java
gateway-server/src/test/java/org/apache/knox/gateway/AuditLoggingTest.java
gateway-server/src/test/java/org/apache/knox/gateway/GatewayFilterTest.java
gateway-server/src/test/java/org/apache/knox/gateway/deploy/DeploymentFactoryTest.java
gateway-server/src/test/java/org/apache/knox/gateway/deploy/impl/ServiceDefinitionDeploymentContributorTest.java
gateway-server/src/test/java/org/apache/knox/gateway/services/token/impl/DefaultTokenAuthorityServiceTest.java
gateway-server/src/test/java/org/apache/knox/gateway/services/topology/DefaultTopologyServiceTest.java
gateway-server/src/test/java/org/apache/knox/gateway/topology/builder/PropertyTopologyBuilderTest.java
gateway-server/src/test/java/org/apache/knox/gateway/topology/discovery/PropertiesFileServiceDiscoveryTest.java
gateway-server/src/test/java/org/apache/knox/gateway/topology/discovery/test/extension/PropertiesFileServiceDiscovery.java
gateway-server/src/test/java/org/apache/knox/gateway/topology/simple/ProviderConfigurationParserTest.java
gateway-server/src/test/java/org/apache/knox/gateway/topology/simple/SimpleDescriptorFactoryTest.java
gateway-server/src/test/java/org/apache/knox/gateway/topology/simple/SimpleDescriptorHandlerTest.java
gateway-server/src/test/java/org/apache/knox/gateway/util/KnoxCLITest.java
gateway-server/src/test/java/org/apache/knox/gateway/websockets/BadBackendTest.java
gateway-server/src/test/java/org/apache/knox/gateway/websockets/BadSocket.java [new file with mode: 0644]
gateway-server/src/test/java/org/apache/knox/gateway/websockets/BadUrlTest.java
gateway-server/src/test/java/org/apache/knox/gateway/websockets/BigEchoSocketHandler.java [new file with mode: 0644]
gateway-server/src/test/java/org/apache/knox/gateway/websockets/ConnectionDroppedTest.java
gateway-server/src/test/java/org/apache/knox/gateway/websockets/EchoSocket.java
gateway-server/src/test/java/org/apache/knox/gateway/websockets/MessageFailureTest.java
gateway-server/src/test/java/org/apache/knox/gateway/websockets/ProxyInboundClientTest.java
gateway-server/src/test/java/org/apache/knox/gateway/websockets/WebsocketClient.java
gateway-server/src/test/java/org/apache/knox/gateway/websockets/WebsocketEchoTest.java
gateway-server/src/test/java/org/apache/knox/gateway/websockets/WebsocketMultipleConnectionTest.java
gateway-service-knoxsso/src/test/java/org/apache/knox/gateway/service/knoxsso/WebSSOResourceTest.java
gateway-service-knoxtoken/src/test/java/org/apache/knox/gateway/service/knoxtoken/TokenServiceResourceTest.java
gateway-service-remoteconfig/src/test/java/org/apache/knox/gateway/service/config/remote/config/DefaultRemoteConfigurationRegistriesTest.java
gateway-service-remoteconfig/src/test/java/org/apache/knox/gateway/service/config/remote/util/RemoteRegistryConfigTestUtils.java
gateway-service-remoteconfig/src/test/java/org/apache/knox/gateway/service/config/remote/zk/RemoteConfigurationRegistryClientServiceTest.java
gateway-service-remoteconfig/src/test/java/org/apache/knox/gateway/service/config/remote/zk/RemoteConfigurationRegistryJAASConfigTest.java
gateway-spi/src/test/java/org/apache/knox/gateway/dispatch/CappedBufferHttpEntityTest.java
gateway-spi/src/test/java/org/apache/knox/gateway/dispatch/HadoopAuthCookieStoreTest.java
gateway-spi/src/test/java/org/apache/knox/gateway/dispatch/PartiallyRepeatableHttpEntityTest.java
gateway-spi/src/test/java/org/apache/knox/gateway/security/principal/PrincipalMapperTest.java
gateway-spi/src/test/java/org/apache/knox/gateway/services/security/impl/CMFKeystoreServiceTest.java
gateway-spi/src/test/java/org/apache/knox/gateway/services/security/impl/CMFMasterServiceTest.java
gateway-spi/src/test/java/org/apache/knox/gateway/services/security/token/impl/JWTTokenTest.java
gateway-spi/src/test/java/org/apache/knox/gateway/util/WhitelistUtilsTest.java
gateway-test-release/webhdfs-kerb-test/src/test/java/org/apache/knox/gateway/SecureClusterTest.java
gateway-test-release/webhdfs-kerb-test/src/test/java/org/apache/knox/gateway/SecureKnoxShellTest.java
gateway-test-release/webhdfs-test/src/test/java/org/apache/knox/gateway/ShellTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayAdminFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayAdminTopologyFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayAppFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayBasicFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayCorrelationIdTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayDeployFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayHealthFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayLocalServiceFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayMultiFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewaySampleFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewaySslFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayUIFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/KnoxCliLdapFuncTestNegative.java
gateway-test/src/test/java/org/apache/knox/gateway/KnoxCliLdapFuncTestPositive.java
gateway-test/src/test/java/org/apache/knox/gateway/KnoxCliSysBindTest.java
gateway-test/src/test/java/org/apache/knox/gateway/SimpleDescriptorHandlerFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/deploy/DeploymentFactoryFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/topology/monitor/RemoteConfigurationMonitorTest.java
gateway-util-common/src/test/java/org/apache/knox/gateway/audit/AuditLayoutTest.java
gateway-util-common/src/test/java/org/apache/knox/gateway/audit/AuditServiceTest.java
gateway-util-common/src/test/java/org/apache/knox/gateway/audit/JdbmQueueTest.java
gateway-util-common/src/test/java/org/apache/knox/gateway/util/JsonPathTest.java
gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/FuncTest.java
gateway-util-urltemplate/src/test/java/org/apache/knox/gateway/util/urltemplate/ExpanderTest.java
gateway-util-urltemplate/src/test/java/org/apache/knox/gateway/util/urltemplate/MatcherTest.java
gateway-util-urltemplate/src/test/java/org/apache/knox/gateway/util/urltemplate/RewriterTest.java
pom.xml

index 15c9bc4..2e24c8f 100644 (file)
@@ -30,6 +30,9 @@ limitations under the License.
         <exclude name="AvoidUsingHardCodedIP" />
         <exclude name="ConstantsInInterface" />
         <exclude name="GuardLogStatement" />
+        <exclude name="JUnitAssertionsShouldIncludeMessage" />
+        <exclude name="JUnitTestContainsTooManyAsserts" />
+        <exclude name="JUnitTestsShouldIncludeAssert" />
         <exclude name="MethodReturnsInternalArray" />
         <exclude name="OneDeclarationPerLine" />
         <exclude name="PreserveStackTrace" />
index 30f9adf..d87e89d 100644 (file)
@@ -27,6 +27,7 @@ import org.apache.shiro.authc.UsernamePasswordToken;
 import static org.easymock.EasyMock.createMock;
 import static org.easymock.EasyMock.expect;
 import static org.easymock.EasyMock.replay;
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assume.assumeTrue;
 
@@ -36,7 +37,7 @@ public class KnoxPamRealmTest {
   public void setService() {
     KnoxPamRealm realm = new KnoxPamRealm();
     realm.setService("knox-pam-os-service");
-    //assertEquals(realm.getService(), "knox-pam-os-service");
+    assertEquals(realm.getService(), "knox-pam-os-service");
   }
 
   @Test
index 8f20154..2d1528f 100644 (file)
@@ -30,17 +30,17 @@ import org.junit.Test;
 import java.io.File;
 import java.io.IOException;
 
+import static org.junit.Assert.assertEquals;
 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 {
+  public static void setUpBeforeClass() 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 );
@@ -49,7 +49,7 @@ public class SimpleLdapServerTest {
   }
 
   @AfterClass
-  public static void cleanup() throws Exception {
+  public static void tearDownAfterClass() throws Exception {
     if( ldap != null ) {
       ldap.stop( true );
     }
@@ -72,6 +72,9 @@ public class SimpleLdapServerTest {
       fail( "Expected LdapAuthenticationException" );
     } catch ( LdapAuthenticationException e ) {
       // Expected
+      assertEquals("INVALID_CREDENTIALS: Bind failed: ERR_229 " +
+                       "Cannot authenticate user uid=nobody,ou=people,dc=hadoop,dc=apache,dc=org",
+          e.getMessage());
     } finally {
       connection.close();
     }
@@ -82,10 +85,11 @@ public class SimpleLdapServerTest {
       fail( "Expected LdapAuthenticationException" );
     } catch ( LdapAuthenticationException e ) {
       // Expected
+      assertEquals("INVALID_CREDENTIALS: Bind failed: ERR_229 " +
+                       "Cannot authenticate user uid=guest,ou=people,dc=hadoop,dc=apache,dc=org",
+          e.getMessage());
     } finally {
       connection.close();
     }
-
   }
-
 }
\ No newline at end of file
index ee01e64..0da5a67 100644 (file)
@@ -39,11 +39,10 @@ import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
 public class AmbariConfigurationMonitorTest {
-
     private File dataDir;
 
     @Before
-    public void setup() throws Exception {
+    public void setUp() throws Exception {
         File targetDir = new File( System.getProperty("user.dir"), "target");
         File tempDir = new File(targetDir, this.getClass().getName() + "__data__" + UUID.randomUUID());
         FileUtils.forceMkdir(tempDir);
@@ -332,5 +331,4 @@ public class AmbariConfigurationMonitorTest {
             return null;
         }
     }
-
 }
index 6ce77d4..b5b0b1b 100644 (file)
@@ -27,9 +27,9 @@ import org.easymock.EasyMock;
 import org.junit.Test;
 
 import java.io.File;
-import java.io.FileOutputStream;
 import java.lang.reflect.Field;
 import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Locale;
@@ -68,11 +68,8 @@ public class AmbariServiceDiscoveryTest {
         assertEquals(clusterName, cluster.getName());
         assertTrue(AmbariCluster.class.isAssignableFrom(cluster.getClass()));
         assertEquals(6, ((AmbariCluster) cluster).getComponents().size());
-
-//        printServiceURLs(cluster);
     }
 
-
     @Test
     public void testSingleClusterDiscoveryWithDefaultAddress() throws Exception {
         final String discoveryAddress = "http://ambarihost:8080";
@@ -96,7 +93,6 @@ public class AmbariServiceDiscoveryTest {
         assertEquals(6, ((AmbariCluster) cluster).getComponents().size());
     }
 
-
     @Test
     public void testSingleClusterDiscoveryWithDefaultClusterName() throws Exception {
         final String discoveryAddress = "http://ambarihost:8080";
@@ -121,7 +117,6 @@ public class AmbariServiceDiscoveryTest {
         assertEquals(6, ((AmbariCluster) cluster).getComponents().size());
     }
 
-
     @Test
     public void testSingleClusterDiscoveryWithDefaultAddressAndClusterName() throws Exception {
         final String discoveryAddress = "http://ambarihost:8080";
@@ -145,7 +140,6 @@ public class AmbariServiceDiscoveryTest {
         assertEquals(6, ((AmbariCluster) cluster).getComponents().size());
     }
 
-
     @Test
     public void testSingleClusterDiscoveryWithMissingAddressAndClusterName() throws Exception {
         final String clusterName = "testCluster";
@@ -166,7 +160,6 @@ public class AmbariServiceDiscoveryTest {
         assertNull(cluster);
     }
 
-
     @Test
     public void testSingleClusterDiscoveryWithMissingAddress() throws Exception {
         final String clusterName = "testCluster";
@@ -184,7 +177,6 @@ public class AmbariServiceDiscoveryTest {
         assertNull(cluster);
     }
 
-
     @Test
     public void testSingleClusterDiscoveryWithMissingClusterName() throws Exception {
         final String discoveryAddress = "http://ambarihost:8080";
@@ -204,7 +196,6 @@ public class AmbariServiceDiscoveryTest {
         assertNull(cluster);
     }
 
-
     @Test
     public void testBulkClusterDiscovery() throws Exception {
         final String discoveryAddress = "http://ambarihost:8080";
@@ -227,11 +218,8 @@ public class AmbariServiceDiscoveryTest {
         assertEquals(clusterName, cluster.getName());
         assertTrue(AmbariCluster.class.isAssignableFrom(cluster.getClass()));
         assertEquals(6, ((AmbariCluster) cluster).getComponents().size());
-
-//        printServiceURLs(cluster, "NAMENODE", "WEBHCAT", "OOZIE", "RESOURCEMANAGER");
     }
 
-
     @Test
     public void testClusterDiscoveryWithExternalComponentConfigAugmentation() throws Exception {
         final String discoveryAddress = "http://ambarihost:8080";
@@ -244,7 +232,7 @@ public class AmbariServiceDiscoveryTest {
         Properties compConfOverrideProps = new Properties();
         compConfOverrideProps.setProperty("DISCOVERY_TEST", "test-site");
         File compConfOverrides = File.createTempFile(getClass().getName()+"component-conf-overrides", ".properties");
-        compConfOverrideProps.store(new FileOutputStream(compConfOverrides), "Test Config Overrides");
+        compConfOverrideProps.store(Files.newOutputStream(compConfOverrides.toPath()), "Test Config Overrides");
         System.setProperty(AmbariServiceDiscovery.COMPONENT_CONFIG_MAPPING_SYSTEM_PROPERTY,
                            compConfOverrides.getAbsolutePath());
 
@@ -301,35 +289,6 @@ public class AmbariServiceDiscoveryTest {
         }
     }
 
-
-    private static void printServiceURLs(ServiceDiscovery.Cluster cluster) {
-        final String[] services = new String[]{"NAMENODE",
-                                               "JOBTRACKER",
-                                               "WEBHDFS",
-                                               "WEBHCAT",
-                                               "OOZIE",
-                                               "WEBHBASE",
-                                               "HIVE",
-                                               "RESOURCEMANAGER"};
-        printServiceURLs(cluster, services);
-    }
-
-
-    private static void printServiceURLs(ServiceDiscovery.Cluster cluster, String...services) {
-        for (String name : services) {
-            StringBuilder sb = new StringBuilder();
-            List<String> urls = cluster.getServiceURLs(name);
-            if (urls != null && !urls.isEmpty()) {
-                for (String url : urls) {
-                    sb.append(url);
-                    sb.append(" ");
-                }
-            }
-            System.out.println(String.format(Locale.ROOT, "%18s: %s", name, sb.toString()));
-        }
-    }
-
-
     /**
      * ServiceDiscovery implementation derived from AmbariServiceDiscovery, so the invokeREST method can be overridden
      * to eliminate the need to perform actual HTTP interactions with a real Ambari endpoint.
@@ -356,7 +315,6 @@ public class AmbariServiceDiscoveryTest {
                 //
             }
         }
-
     }
 
     private static final class TestRESTInvoker extends RESTInvoker {
@@ -386,7 +344,6 @@ public class AmbariServiceDiscoveryTest {
         }
     }
 
-
     ////////////////////////////////////////////////////////////////////////
     //  JSON response templates, based on actual response content excerpts
     ////////////////////////////////////////////////////////////////////////
@@ -746,7 +703,7 @@ public class AmbariServiceDiscoveryTest {
     "      },\n" +
     "      \"components\" : [\n" +
     "        {\n" +
-    "          \"href\" : \"http://c6401.ambari.apache.org:8080/api/v1/clusters/"+TestAmbariServiceDiscovery.CLUSTER_PLACEHOLDER+""+TestAmbariServiceDiscovery.CLUSTER_PLACEHOLDER+"/services/ZOOKEEPER/components/ZOOKEEPER_SERVER\",\n" +
+    "          \"href\" : \"http://c6401.ambari.apache.org:8080/api/v1/clusters/"+TestAmbariServiceDiscovery.CLUSTER_PLACEHOLDER+TestAmbariServiceDiscovery.CLUSTER_PLACEHOLDER+"/services/ZOOKEEPER/components/ZOOKEEPER_SERVER\",\n" +
     "          \"ServiceComponentInfo\" : {\n" +
     "            \"cluster_name\" : \""+TestAmbariServiceDiscovery.CLUSTER_PLACEHOLDER+"\",\n" +
     "            \"component_name\" : \"ZOOKEEPER_SERVER\",\n" +
@@ -1151,6 +1108,4 @@ public class AmbariServiceDiscoveryTest {
     "    }\n" +
     "  ]\n" +
     "}";
-
-
 }
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.apache.knox.gateway.webappsec;
+package org.apache.knox.gateway.i18n.messages;
 
-
-import org.junit.Test;
-
-public class CSRFTest extends org.junit.Assert {
-  @Test
-  public void testCsrf() throws Exception {
-    assertTrue(true);
-  }
+@Messages( bundle="some.bundle.name", logger="some.logger.name", codes="ID:{0}" )
+public interface MessagesSubject {
+  @Message(level= MessageLevel.ERROR, code=3, text="p0={0}" )
+  void withFullAnnotationAndParameter( int x );
 }
index dc252b6..bf14cd2 100644 (file)
@@ -31,10 +31,9 @@ import static org.junit.Assert.assertThat;
 
 @Category( { UnitTests.class, FastTests.class } )
 public class MessagesTest {
-
   @Test
   public void testFirst() {
-    MessagesTestSubject log = MessagesFactory.get( MessagesTestSubject.class );
+    MessagesSubject log = MessagesFactory.get( MessagesSubject.class );
 
     log.withFullAnnotationAndParameter( 7 );
 
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
deleted file mode 100644 (file)
index 8bb985f..0000000
+++ /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.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();
-
-}
@@ -18,8 +18,7 @@
 package org.apache.knox.gateway.i18n.resources;
 
 @Resources( bundle="some.bundle.name" )
-public interface ResourcesTestFormattingSubject {
-
+public interface ResourcesFormattingSubject {
   @Resource(text="{0}")
   String withAnnotationWithSimplePatternOneParam( int x );
 
@@ -40,5 +39,4 @@ public interface ResourcesTestFormattingSubject {
 
   @Resource(text="{0}")
   String withLessFormatParamsThanMethodParams( int x, int y );
-
 }
@@ -18,9 +18,7 @@
 package org.apache.knox.gateway.i18n.resources;
 
 @Resources( bundle="org.apache.knox.gateway.i18n.resources.NamedBundle" )
-public interface ResourcesTestNamedSubject {
-
+public interface ResourcesNamedSubject {
   @Resource(text="default=[{0}]")
   String testResource( String param );
-
 }
index 7696266..585b903 100644 (file)
@@ -31,23 +31,21 @@ import static org.junit.Assert.assertThat;
 
 @Category( { UnitTests.class, FastTests.class } )
 public class ResourcesTest {
-
   private Locale locale;
 
   @Before
-  public void setup() {
+  public void setUp() {
     locale = Locale.getDefault();
   }
 
   @After
-  public void cleanup() {
+  public void tearDown() {
     Locale.setDefault( locale );
   }
 
   @Test
   public void testResourceFormatting() {
-
-    ResourcesTestFormattingSubject res = ResourcesFactory.get( ResourcesTestFormattingSubject.class );
+    ResourcesFormattingSubject res = ResourcesFactory.get( ResourcesFormattingSubject.class );
 
     assertThat(
         res.withoutAnnotationsOrParameters(),
@@ -84,8 +82,7 @@ public class ResourcesTest {
 
   @Test
   public void testResourceLocales() {
-
-    ResourcesTestLocaleSubject res = ResourcesFactory.get( ResourcesTestLocaleSubject.class );
+    ResourcesLocaleSubject res = ResourcesFactory.get( ResourcesLocaleSubject.class );
 
     Locale.setDefault( Locale.CHINESE ); // Change to something that we won't have test bundles for.
     assertThat( res.testResource( "queryParam" ), equalTo( "default=[queryParam]" ) );
@@ -98,21 +95,16 @@ public class ResourcesTest {
 
     Locale.setDefault( Locale.UK );
     assertThat( res.testResource( "queryParam" ), equalTo( "uk=[queryParam]" ) );
-
   }
 
   @Test
   public void testNamedBundle() {
-
-    ResourcesTestNamedSubject res = ResourcesFactory.get( ResourcesTestNamedSubject.class );
+    ResourcesNamedSubject res = ResourcesFactory.get( ResourcesNamedSubject.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]" ) );
-
   }
-
-
 }
index e3f3ba4..28a8f14 100644 (file)
@@ -304,50 +304,50 @@ public class HaProviderDeploymentContributorTest {
                                                  String  zooKeeperEnsemble) {
       StringBuilder builder = new StringBuilder();
 
-      builder.append(HaServiceConfigConstants.CONFIG_PARAM_ENABLED);
-      builder.append(HaServiceConfigConstants.CONFIG_PAIR_DELIMITER);
-      builder.append(enabled);
+      builder.append(HaServiceConfigConstants.CONFIG_PARAM_ENABLED)
+          .append(HaServiceConfigConstants.CONFIG_PAIR_DELIMITER)
+          .append(enabled);
 
       if (maxRetryAttempts > -1) {
-         builder.append(HaServiceConfigConstants.CONFIG_PAIRS_DELIMITER);
-         builder.append(HaServiceConfigConstants.CONFIG_PARAM_MAX_RETRY_ATTEMPTS);
-         builder.append(HaServiceConfigConstants.CONFIG_PAIR_DELIMITER);
-         builder.append(maxRetryAttempts);
+         builder.append(HaServiceConfigConstants.CONFIG_PAIRS_DELIMITER)
+             .append(HaServiceConfigConstants.CONFIG_PARAM_MAX_RETRY_ATTEMPTS)
+             .append(HaServiceConfigConstants.CONFIG_PAIR_DELIMITER)
+             .append(maxRetryAttempts);
       }
 
       if (retrySleep > -1) {
-         builder.append(HaServiceConfigConstants.CONFIG_PAIRS_DELIMITER);
-         builder.append(HaServiceConfigConstants.CONFIG_PARAM_RETRY_SLEEP);
-         builder.append(HaServiceConfigConstants.CONFIG_PAIR_DELIMITER);
-         builder.append(retrySleep);
+         builder.append(HaServiceConfigConstants.CONFIG_PAIRS_DELIMITER)
+             .append(HaServiceConfigConstants.CONFIG_PARAM_RETRY_SLEEP)
+             .append(HaServiceConfigConstants.CONFIG_PAIR_DELIMITER)
+             .append(retrySleep);
       }
 
       if (maxFailoverAttempts > -1) {
-         builder.append(HaServiceConfigConstants.CONFIG_PAIRS_DELIMITER);
-         builder.append(HaServiceConfigConstants.CONFIG_PARAM_MAX_FAILOVER_ATTEMPTS);
-         builder.append(HaServiceConfigConstants.CONFIG_PAIR_DELIMITER);
-         builder.append(maxFailoverAttempts);
+         builder.append(HaServiceConfigConstants.CONFIG_PAIRS_DELIMITER)
+             .append(HaServiceConfigConstants.CONFIG_PARAM_MAX_FAILOVER_ATTEMPTS)
+             .append(HaServiceConfigConstants.CONFIG_PAIR_DELIMITER)
+             .append(maxFailoverAttempts);
       }
 
       if (failoverSleep > -1) {
-         builder.append(HaServiceConfigConstants.CONFIG_PAIRS_DELIMITER);
-         builder.append(HaServiceConfigConstants.CONFIG_PARAM_FAILOVER_SLEEP);
-         builder.append(HaServiceConfigConstants.CONFIG_PAIR_DELIMITER);
-         builder.append(failoverSleep);
+         builder.append(HaServiceConfigConstants.CONFIG_PAIRS_DELIMITER)
+             .append(HaServiceConfigConstants.CONFIG_PARAM_FAILOVER_SLEEP)
+             .append(HaServiceConfigConstants.CONFIG_PAIR_DELIMITER)
+             .append(failoverSleep);
       }
 
       if (zooKeeperNamespace != null) {
-         builder.append(HaServiceConfigConstants.CONFIG_PAIRS_DELIMITER);
-         builder.append(HaServiceConfigConstants.CONFIG_PARAM_ZOOKEEPER_NAMESPACE);
-         builder.append(HaServiceConfigConstants.CONFIG_PAIR_DELIMITER);
-         builder.append(zooKeeperNamespace);
+         builder.append(HaServiceConfigConstants.CONFIG_PAIRS_DELIMITER)
+             .append(HaServiceConfigConstants.CONFIG_PARAM_ZOOKEEPER_NAMESPACE)
+             .append(HaServiceConfigConstants.CONFIG_PAIR_DELIMITER)
+             .append(zooKeeperNamespace);
       }
 
       if (zooKeeperEnsemble != null) {
-         builder.append(HaServiceConfigConstants.CONFIG_PAIRS_DELIMITER);
-         builder.append(HaServiceConfigConstants.CONFIG_PARAM_ZOOKEEPER_ENSEMBLE);
-         builder.append(HaServiceConfigConstants.CONFIG_PAIR_DELIMITER);
-         builder.append(zooKeeperEnsemble);
+         builder.append(HaServiceConfigConstants.CONFIG_PAIRS_DELIMITER)
+             .append(HaServiceConfigConstants.CONFIG_PARAM_ZOOKEEPER_ENSEMBLE)
+             .append(HaServiceConfigConstants.CONFIG_PAIR_DELIMITER)
+             .append(zooKeeperEnsemble);
       }
 
       return builder.toString();
@@ -451,6 +451,5 @@ public class HaProviderDeploymentContributorTest {
       public <T> T getDescriptor(String name) {
          return (T)descriptors.get(name);
       }
-
    }
 }
index 1ee54e9..2cb00ce 100644 (file)
@@ -46,7 +46,7 @@ public class AtlasZookeeperURLManagerTest {
     private static String atlasNode2 = "http://atlas.node2:21000";
 
     @Before
-    public void setup() throws Exception {
+    public void setUp() throws Exception {
         cluster = new TestingCluster(3);
         cluster.start();
 
@@ -74,7 +74,7 @@ public class AtlasZookeeperURLManagerTest {
     }
 
     @After
-    public void teardown() throws IOException {
+    public void tearDown() throws IOException {
         if(cluster != null) {
             cluster.close();
         }
index b5b2a3f..71b3abc 100644 (file)
@@ -40,6 +40,7 @@ public class DefaultHaProviderTest {
          fail("provider construction should have failed with null descriptor");
       } catch (IllegalArgumentException e) {
         // Expected exception
+        assertEquals("Descriptor can not be null", e.getMessage());
       }
       HaDescriptor descriptor = new DefaultHaDescriptor();
       HaProvider provider = new DefaultHaProvider(descriptor);
index 8858614..c35f5b6 100644 (file)
@@ -48,13 +48,13 @@ public class HBaseZookeeperURLManagerTest {
   private TestingCluster cluster;
 
   @Before
-  public void setup() throws Exception {
+  public void setUp() throws Exception {
     cluster = new TestingCluster(3);
     cluster.start();
   }
 
   @After
-  public void teardown() throws IOException {
+  public void tearDown() throws IOException {
     if(cluster != null) {
       cluster.close();
     }
index dcdb926..77b17b0 100644 (file)
@@ -38,12 +38,11 @@ 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 {
+  public void setUp() throws Exception {
     cluster = new TestingCluster(3);
     cluster.start();
 
@@ -77,7 +76,7 @@ public class HS2ZookeeperURLManagerTest {
   }
 
   @After
-  public void teardown() throws IOException {
+  public void tearDown() throws IOException {
     if(cluster != null) {
       cluster.close();
     }
@@ -133,6 +132,4 @@ public class HS2ZookeeperURLManagerTest {
     Assert.assertNotNull(manager);
     assertTrue(manager instanceof HS2ZookeeperURLManager);
   }
-
-
 }
index f200217..18c3f3a 100644 (file)
@@ -35,7 +35,6 @@ 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'/>" +
@@ -80,7 +79,6 @@ public class HaDescriptorManagerTest {
       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" +
@@ -89,6 +87,4 @@ public class HaDescriptorManagerTest {
       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']" ) );
    }
-
-
 }
index 30367c6..50a0f7d 100644 (file)
@@ -43,7 +43,7 @@ public class KafkaZookeeperURLManagerTest {
   private TestingCluster cluster;
 
   @Before
-  public void setup() throws Exception {
+  public void setUp() throws Exception {
     cluster = new TestingCluster(3);
     cluster.start();
 
@@ -59,7 +59,7 @@ public class KafkaZookeeperURLManagerTest {
   }
 
   @After
-  public void teardown() throws IOException {
+  public void tearDown() throws IOException {
     if(cluster != null) {
       cluster.close();
     }
index 637fdab..aea7acd 100644 (file)
@@ -43,12 +43,11 @@ import static org.junit.Assert.assertTrue;
  * @see SOLRZookeeperURLManager
  */
 public class SOLRZookeeperURLManagerTest {
-
   private TestingCluster cluster;
   private SOLRZookeeperURLManager manager;
 
   @Before
-  public void setup() throws Exception {
+  public void setUp() throws Exception {
     cluster = new TestingCluster(3);
     cluster.start();
 
@@ -71,7 +70,7 @@ public class SOLRZookeeperURLManagerTest {
   }
 
   @After
-  public void teardown() throws IOException {
+  public void tearDown() throws IOException {
     if(cluster != null) {
       cluster.close();
     }
index ccc7936..15f41c0 100644 (file)
@@ -34,7 +34,6 @@ import javax.servlet.ServletResponse;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
-import java.net.URISyntaxException;
 import java.security.PrivilegedActionException;
 import java.security.PrivilegedExceptionAction;
 import java.util.Locale;
@@ -47,13 +46,12 @@ import static org.junit.Assert.assertTrue;
  *
  */
 public class CommonIdentityAssertionFilterTest {
-
   private String username;
   private String[] mappedGroups;
   private Filter filter;
 
   @Before
-  public void setup() {
+  public void setUp() {
     filter = new CommonIdentityAssertionFilter() {
       @Override
       public String mapUserPrincipal(String principalName) {
@@ -76,9 +74,7 @@ public class CommonIdentityAssertionFilterTest {
   }
 
   @Test
-  public void testSimpleFilter() throws ServletException, IOException,
-      URISyntaxException {
-
+  public void testSimpleFilter() throws ServletException, IOException {
     FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
     EasyMock.replay( config );
 
@@ -127,5 +123,4 @@ public class CommonIdentityAssertionFilterTest {
     assertTrue(mappedGroups[0].equals("USERS") || mappedGroups[0].equals("ADMIN"));
     assertTrue(mappedGroups[1], mappedGroups[1].equals("USERS") || mappedGroups[1].equals("ADMIN"));
   }
-
 }
index 4ff9efb..4595e85 100644 (file)
@@ -62,7 +62,6 @@ public class IdentityAssertionHttpServletRequestWrapperTest {
     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" ) );
   }
@@ -79,7 +78,6 @@ public class IdentityAssertionHttpServletRequestWrapperTest {
     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" ) );
   }
@@ -97,7 +95,6 @@ public class IdentityAssertionHttpServletRequestWrapperTest {
     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" ) );
   }
@@ -115,7 +112,6 @@ public class IdentityAssertionHttpServletRequestWrapperTest {
     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" ) ) );
@@ -275,5 +271,4 @@ public class IdentityAssertionHttpServletRequestWrapperTest {
     s = IdentityAsserterHttpServletRequestWrapper.urlEncode( m, StandardCharsets.UTF_8.name() );
     assertThat( s, is( "two-values=value1&two-values=value2" ) );
   }
-
 }
index 3d9876b..d8e17c4 100644 (file)
@@ -67,7 +67,6 @@ 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;
@@ -79,7 +78,7 @@ public class UsernameFunctionProcessorTest {
     return ClassLoader.getSystemResource( name );
   }
 
-  public void setUp( String username, Map<String,String> initParams ) throws Exception {
+  private void testSetup(String username, Map<String,String> initParams ) throws Exception {
     String descriptorUrl = getTestResource( "rewrite.xml" ).toExternalForm();
 
     Log.setLog( new NoOpLogger() );
@@ -166,7 +165,7 @@ public class UsernameFunctionProcessorTest {
   public void testRequestUrlRewriteOfUsernameViaRewriteRule() throws Exception {
     Map<String,String> initParams = new HashMap<>();
     initParams.put( "request.url", "test-rule-username" );
-    setUp( "test-user", initParams );
+    testSetup( "test-user", initParams );
 
     String input = "<root/>";
     String expect = "<root/>";
@@ -213,7 +212,7 @@ public class UsernameFunctionProcessorTest {
       StringBuffer sourceUrl = httpRequest.getRequestURL();
       String queryString = httpRequest.getQueryString();
       if( queryString != null ) {
-        sourceUrl.append( "?" );
+        sourceUrl.append( '?' );
         sourceUrl.append( queryString );
       }
       try {
@@ -240,5 +239,4 @@ public class UsernameFunctionProcessorTest {
     public void destroy() {
     }
   }
-
 }
index 72d4606..ae9faeb 100644 (file)
@@ -92,7 +92,9 @@ public class DefaultIdentityAssertionFilterTest {
   }
 
   private boolean groupFoundIn(String expected, String[] mappedGroups) {
-    if (mappedGroups == null) return false;
+    if (mappedGroups == null) {
+      return false;
+    }
     for (String mappedGroup : mappedGroups) {
       if (mappedGroup.equals(expected)) {
         return true;
index f3084c6..0981a0f 100644 (file)
@@ -79,8 +79,9 @@ public class InboundUrlFunctionProcessorTest {
         proc = (InboundUrlFunctionProcessor) object ;
       }
     }
-    if( proc == null )
-      fail( "Failed to find " + InboundUrlFunctionProcessor.class.getName() + " via service loader." );
+    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 );
@@ -116,7 +117,6 @@ public class InboundUrlFunctionProcessorTest {
     return new UrlRewriteResponse( config, request, response );
   }
 
-
   @Test
   public void testQueryParam() throws Exception {
     GatewayServices gatewayServices = EasyMock.createNiceMock( GatewayServices.class );
index b014589..ad8be10 100644 (file)
@@ -60,9 +60,7 @@ import java.util.Queue;
 
 import static org.hamcrest.MatcherAssert.assertThat;
 
-
 public class ServiceRegistryFunctionsTest {
-
   private ServletTester server;
   private HttpTester.Request request;
   private HttpTester.Response response;
@@ -74,7 +72,7 @@ public class ServiceRegistryFunctionsTest {
     return ClassLoader.getSystemResource( name );
   }
 
-  public void setUp( String username, Map<String,String> initParams ) throws Exception {
+  private void testSetup(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();
@@ -122,7 +120,7 @@ public class ServiceRegistryFunctionsTest {
   public void testServiceRegistryFunctionsOnXmlRequestBody() throws Exception {
     Map<String,String> initParams = new HashMap<>();
     initParams.put( "request.body", "oozie-conf" );
-    setUp( "test-user", initParams );
+    testSetup( "test-user", initParams );
 
     String input = TestUtils.getResourceString( ServiceRegistryFunctionsTest.class, "test-input-body.xml", StandardCharsets.UTF_8 );
     String expect = TestUtils.getResourceString( ServiceRegistryFunctionsTest.class, "test-expect-body.xml", StandardCharsets.UTF_8 );
@@ -154,7 +152,7 @@ public class ServiceRegistryFunctionsTest {
   public void testServiceRegistryFunctionsOnJsonRequestBody() throws Exception {
     Map<String,String> initParams = new HashMap<>();
     initParams.put( "request.body", "oozie-conf" );
-    setUp( "test-user", initParams );
+    testSetup( "test-user", initParams );
 
     String input = TestUtils.getResourceString( ServiceRegistryFunctionsTest.class, "test-input-body.json", StandardCharsets.UTF_8 );
     String expect = TestUtils.getResourceString( ServiceRegistryFunctionsTest.class, "test-expect-body.json", StandardCharsets.UTF_8 );
@@ -200,7 +198,7 @@ public class ServiceRegistryFunctionsTest {
       StringBuffer sourceUrl = httpRequest.getRequestURL();
       String queryString = httpRequest.getQueryString();
       if( queryString != null ) {
-        sourceUrl.append( "?" );
+        sourceUrl.append( '?' );
         sourceUrl.append( queryString );
       }
       try {
@@ -227,5 +225,4 @@ public class ServiceRegistryFunctionsTest {
     public void destroy() {
     }
   }
-
 }
index 7692df5..c8669d0 100644 (file)
@@ -40,6 +40,8 @@ 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.assertEquals;
+import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertThat;
 import static org.junit.Assert.fail;
 import static org.xmlmatchers.XmlMatchers.hasXPath;
@@ -47,7 +49,7 @@ import static org.xmlmatchers.XmlMatchers.hasXPath;
 public class UrlRewriteRulesDescriptorFactoryTest {
 
   @Test
-  public void testCreate() throws Exception {
+  public void testCreate() {
     UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
     assertThat( descriptor, notNullValue() );
     assertThat( descriptor.getRules(), notNullValue() );
@@ -62,6 +64,7 @@ public class UrlRewriteRulesDescriptorFactoryTest {
     assertThat( descriptor.getRule( "first" ), sameInstance( rule ) );
 
     rule = descriptor.addRule( "second" );
+    assertNotNull(rule);
     assertThat( descriptor.getRules().size(), is( 2 ) );
   }
 
@@ -94,7 +97,7 @@ public class UrlRewriteRulesDescriptorFactoryTest {
   }
 
   @Test
-  public void testLoadEmptyFile() throws IOException {
+  public void testLoadEmptyFile() {
     Logger logger = org.apache.log4j.LogManager.getLogger( "org.apache.commons.digester3.Digester" );
     Level level = logger.getLevel();
     try {
@@ -103,6 +106,9 @@ public class UrlRewriteRulesDescriptorFactoryTest {
       fail( "Should have thrown an IOException." );
     } catch ( IOException e ) {
       // Expected.
+      assertEquals("org.xml.sax.SAXParseException; lineNumber: 16; " +
+                       "columnNumber: 4; Premature end of file.",
+          e.getMessage());
     } catch ( Throwable t ) {
       fail( "Should have thrown an IOException." );
     } finally {
@@ -111,7 +117,7 @@ public class UrlRewriteRulesDescriptorFactoryTest {
   }
 
   @Test
-  public void testLoadInvalidFile() throws IOException {
+  public void testLoadInvalidFile() {
     Logger logger = org.apache.log4j.LogManager.getLogger( "org.apache.commons.digester3.Digester" );
     Level level = logger.getLevel();
     try {
@@ -120,6 +126,9 @@ public class UrlRewriteRulesDescriptorFactoryTest {
       fail( "Should have thrown an IOException." );
     } catch ( IOException e ) {
       // Expected.
+      assertEquals("org.xml.sax.SAXParseException; lineNumber: 18; columnNumber: 2; " +
+                       "The markup in the document preceding the root element must be well-formed.",
+          e.getMessage());
     } catch ( Throwable t ) {
       fail( "Should have thrown an IOException." );
     } finally {
@@ -247,7 +256,5 @@ public class UrlRewriteRulesDescriptorFactoryTest {
     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" ) ) );
-
   }
-
 }
index 2c067bc..8d65d7f 100644 (file)
@@ -21,7 +21,6 @@ import org.apache.knox.test.mock.MockInteraction;
 import org.apache.knox.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.junit.After;
 import org.junit.Before;
@@ -33,12 +32,8 @@ import java.util.EnumSet;
 import java.util.Queue;
 
 public class UrlRewriteServletContextListenerTest {
-
   private ServletTester server;
-  private HttpTester.Request request;
-  private HttpTester.Response response;
   private Queue<MockInteraction> interactions;
-  private MockInteraction interaction;
 
   private static URL getTestResource( String name ) {
     name = UrlRewriteServletFilterTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
@@ -67,10 +62,6 @@ public class UrlRewriteServletContextListenerTest {
         getTestResource( "rewrite.xml" ).toExternalForm() );
 
     server.start();
-
-    interaction = new MockInteraction();
-    request = HttpTester.newRequest();
-    response = null;
   }
 
   @After
index 6c7e8ff..93015ad 100644 (file)
@@ -72,7 +72,7 @@ public class UrlRewriteServletFilterTest {
     return ClassLoader.getSystemResource( name );
   }
 
-  public void setUp( Map<String,String> initParams ) throws Exception {
+  private void testSetUp(Map<String,String> initParams ) throws Exception {
     String descriptorUrl = getTestResource( "rewrite.xml" ).toExternalForm();
 
     server = new ServletTester();
@@ -112,7 +112,7 @@ public class UrlRewriteServletFilterTest {
 
   @Test
   public void testInboundRequestUrlRewrite() throws Exception {
-    setUp( null );
+    testSetUp( null );
     // Setup the server side request/response interaction.
     interaction.expect()
         .method( "GET" )
@@ -134,7 +134,7 @@ public class UrlRewriteServletFilterTest {
 
   @Test
   public void testInboundHeaderRewrite() throws Exception {
-    setUp( null );
+    testSetUp( null );
     // Setup the server side request/response interaction.
     interaction.expect()
         .method( "GET" )
@@ -158,7 +158,7 @@ public class UrlRewriteServletFilterTest {
 
   @Test
   public void testOutboundHeaderRewrite() throws Exception {
-    setUp( null );
+    testSetUp( null );
     // Setup the server side request/response interaction.
     interaction.expect()
         .method( "GET" )
@@ -236,7 +236,7 @@ public class UrlRewriteServletFilterTest {
 
   @Test
   public void testInboundJsonBodyRewrite() throws Exception {
-    setUp( null );
+    testSetUp( null );
 
     String inputJson = "{\"url\":\"http://mock-host:1/test-input-path\"}";
     String outputJson = "{\"url\":\"http://mock-host:1/test-output-path-1\"}";
@@ -265,7 +265,7 @@ public class UrlRewriteServletFilterTest {
 
   @Test
   public void testInboundXmlBodyRewrite() throws Exception {
-    setUp( null );
+    testSetUp( null );
     String input = "<root attribute=\"http://mock-host:1/test-input-path\">http://mock-host:1/test-input-path</root>";
     String output;
     if(System.getProperty("java.vendor").contains("IBM")){
@@ -298,7 +298,7 @@ public class UrlRewriteServletFilterTest {
   // MatcherAssert.assertThat( XmlConverters.the( outputHtml ), XmlMatchers.hasXPath( "/html" ) );
   @Test
   public void testOutboundJsonBodyRewrite() throws Exception {
-    setUp( null );
+    testSetUp( null );
 
     String input = "{\"url\":\"http://mock-host:1/test-input-path\"}";
     String expect = "{\"url\":\"http://mock-host:1/test-output-path-1\"}";
@@ -327,7 +327,7 @@ public class UrlRewriteServletFilterTest {
 
   @Test
   public void testOutboundHtmlBodyRewrite() throws Exception {
-    setUp( null );
+    testSetUp( 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>";
@@ -356,7 +356,7 @@ public class UrlRewriteServletFilterTest {
 
   @Test
   public void testInboundHtmlFormRewrite() throws Exception {
-    setUp( null );
+    testSetUp( 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";
@@ -387,7 +387,7 @@ public class UrlRewriteServletFilterTest {
   public void testRequestUrlRewriteWithFilterInitParam() throws Exception {
     Map<String,String> initParams = new HashMap<>();
     initParams.put( "request.url", "test-rule-2" );
-    setUp( initParams );
+    testSetUp( initParams );
 
     String input = "<root/>";
     String expect = "<root/>";
@@ -420,7 +420,7 @@ public class UrlRewriteServletFilterTest {
   public void testRequestHeaderRewriteWithFilterInitParam() throws Exception {
     Map<String,String> initParams = new HashMap<>();
     initParams.put( "request.headers", "test-filter-2" );
-    setUp( initParams );
+    testSetUp( initParams );
 
     String input = "<root/>";
     String expect = "<root/>";
@@ -463,7 +463,7 @@ public class UrlRewriteServletFilterTest {
     //initParams.put( "url, "" );
     initParams.put( "request.body", "test-filter-2" );
     //initParams.put( "response", "" );
-    setUp( initParams );
+    testSetUp( initParams );
 
     String inputJson = "{\"url\":\"http://mock-host:42/test-input-path-1\"}";
     String expectJson = "{\"url\":\"http://mock-host:42/test-output-path-2\"}";
@@ -495,7 +495,7 @@ public class UrlRewriteServletFilterTest {
   public void testRequestXmlBodyRewriteWithFilterInitParam() throws Exception {
     Map<String,String> initParams = new HashMap<>();
     initParams.put( "request.body", "test-filter-2" );
-    setUp( initParams );
+    testSetUp( 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>";
@@ -531,7 +531,7 @@ public class UrlRewriteServletFilterTest {
 
       Map<String,String> initParams = new HashMap<>();
       initParams.put( "request.body", "test-filter-3" );
-      setUp( initParams );
+      testSetUp( 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>";
@@ -567,7 +567,7 @@ public class UrlRewriteServletFilterTest {
   public void testRequestFormBodyRewriteWithFilterInitParam() throws Exception {
     Map<String,String> initParams = new HashMap<>();
     initParams.put( "request.body", "test-filter-2" );
-    setUp( initParams );
+    testSetUp( 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";
@@ -599,7 +599,7 @@ public class UrlRewriteServletFilterTest {
   public void testResponseHeaderRewriteWithFilterInitParam() throws Exception {
     Map<String,String> initParams = new HashMap<>();
     initParams.put( "response.headers", "test-filter-2" );
-    setUp( initParams );
+    testSetUp( initParams );
 
     String output = "<root url='http://mock-host:42/test-input-path-2'><url>http://mock-host:42/test-input-path-3</url></root>";
 
@@ -643,7 +643,7 @@ public class UrlRewriteServletFilterTest {
     //initParams.put( "url, "" );
     initParams.put( "response.body", "test-filter-2" );
     //initParams.put( "response", "" );
-    setUp( initParams );
+    testSetUp( initParams );
 
     String responseJson = "{\"url\":\"http://mock-host:42/test-input-path-1\"}";
 
@@ -676,7 +676,7 @@ public class UrlRewriteServletFilterTest {
     //initParams.put( "url, "" );
     initParams.put( "response.body", "test-filter-4" );
     //initParams.put( "response", "" );
-    setUp( initParams );
+    testSetUp( initParams );
 
     String responseHtml = "<!DOCTYPE html>\n" +
         "<html>\n" +
@@ -725,7 +725,7 @@ public class UrlRewriteServletFilterTest {
   public void testResponseXmlBodyRewriteWithFilterInitParam() throws Exception {
     Map<String,String> initParams = new HashMap<>();
     initParams.put( "response.body", "test-filter-2" );
-    setUp( initParams );
+    testSetUp( initParams );
 
     String output = "<root url='http://mock-host:42/test-input-path-1'><url>http://mock-host:42/test-input-path-1</url></root>";
 
@@ -761,7 +761,7 @@ public class UrlRewriteServletFilterTest {
     //initParams.put( "url, "" );
     initParams.put( "response.body", "test-filter-5" );
     //initParams.put( "response", "" );
-    setUp( initParams );
+    testSetUp( initParams );
 
     String responseHtml = "<html>" +
                           "  <head>" +
@@ -811,7 +811,7 @@ public class UrlRewriteServletFilterTest {
   public void testResponseHtmlBodyRewritePrefixFunctionTestPrefix() throws Exception {
 
     Map<String,String> initParams = new HashMap<>();
-    setUp( initParams );
+    testSetUp( 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>";
@@ -850,7 +850,7 @@ public class UrlRewriteServletFilterTest {
 
     Map<String,String> initParams = new HashMap<>();
     initParams.put( "response.headers", "test-filter-6" );
-    setUp( initParams );
+    testSetUp( initParams );
 
     String locationHeader = "https://localhost:8443/gateway/knoxsso/api/v1/websso?originalUrl=http://localhost:20070/index.html&doAs=anonymous";
     String responseHtml = "<html>Hello There !</html>";
@@ -890,7 +890,7 @@ public class UrlRewriteServletFilterTest {
 
     Map<String,String> initParams = new HashMap<>();
     initParams.put( "response.headers", "test-filter-6" );
-    setUp( initParams );
+    testSetUp( initParams );
 
     String customHeader = "https://localhost:8443/gateway/sandbox/?query=http://localhost:20070";
     String responseHtml = "<html>Hello There !</html>";
@@ -927,7 +927,7 @@ public class UrlRewriteServletFilterTest {
   public void testResponseHtmlAttributeEscaping() throws Exception {
     final Map<String, String> initParams = new HashMap<>();
     initParams.put("response.body", "test-filter-4");
-    setUp(initParams);
+    testSetUp(initParams);
 
     final String responseHtml = "<!DOCTYPE html>\n" + "<html>\n" + "  <head>\n"
         + "    <meta charset=\"UTF-8\">\n"
@@ -970,8 +970,7 @@ public class UrlRewriteServletFilterTest {
       StringBuffer sourceUrl = httpRequest.getRequestURL();
       String queryString = httpRequest.getQueryString();
       if( queryString != null ) {
-        sourceUrl.append( "?" );
-        sourceUrl.append( queryString );
+        sourceUrl.append('?').append( queryString );
       }
       try {
         request.setAttribute(
index 65b75bf..1a359b3 100644 (file)
@@ -123,7 +123,7 @@ public class FrontendFunctionProcessorTest {
     processor.resolve( null, null );
   }
 
-  public void setUp( String username, Map<String, String> initParams, Attributes attributes ) throws Exception {
+  private void testSetup(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();
@@ -175,7 +175,7 @@ public class FrontendFunctionProcessorTest {
   public void testFrontendFunctionsOnJsonRequestBody() throws Exception {
     Map<String,String> initParams = new HashMap<>();
     initParams.put( "response.body", "test-filter" );
-    setUp( "test-user", initParams, null );
+    testSetup( "test-user", initParams, null );
 
     String input = TestUtils.getResourceString( FrontendFunctionProcessorTest.class, "test-input-body.json", StandardCharsets.UTF_8 );
 
@@ -221,7 +221,7 @@ public class FrontendFunctionProcessorTest {
     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 );
+    testSetup( "test-user", initParams, attributes );
 
     String input = TestUtils.getResourceString( FrontendFunctionProcessorTest.class, "test-input-body.json", StandardCharsets.UTF_8 );
 
@@ -273,7 +273,7 @@ public class FrontendFunctionProcessorTest {
       StringBuffer sourceUrl = httpRequest.getRequestURL();
       String queryString = httpRequest.getQueryString();
       if( queryString != null ) {
-        sourceUrl.append( "?" );
+        sourceUrl.append( '?' );
         sourceUrl.append( queryString );
       }
       try {
@@ -300,5 +300,4 @@ public class FrontendFunctionProcessorTest {
     public void destroy() {
     }
   }
-
 }
index 4d643b3..4124761 100644 (file)
@@ -30,12 +30,11 @@ 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.nio.charset.StandardCharsets;
+import java.nio.file.Files;
 import java.util.List;
 import java.util.zip.GZIPInputStream;
 import java.util.zip.GZIPOutputStream;
@@ -144,26 +143,22 @@ public class UrlRewriteResponseTest {
     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, output;
-    InputStream inStream = null, input = null;
-    try {
-      outStream = isGzip ? new GZIPOutputStream( new FileOutputStream( inputFile ) ) : new FileOutputStream( inputFile );
-      outStream.write( content.getBytes(StandardCharsets.UTF_8) );
-      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, StandardCharsets.UTF_8 ) ), is( content ) );
-    } finally {
-      if ( inStream != null ) {
-        inStream.close();
+    try (OutputStream outputStream = Files.newOutputStream(inputFile.toPath())) {
+      try(OutputStream outStream = isGzip ? new GZIPOutputStream( outputStream ) : outputStream) {
+        outStream.write(content.getBytes(StandardCharsets.UTF_8));
+      }
+
+      try(InputStream input = Files.newInputStream(inputFile.toPath());
+          OutputStream output = Files.newOutputStream(outputFile.toPath())){
+
+        rewriteResponse.streamResponse(input, output);
       }
-      if ( input != null ) {
-        input.close();
+
+      try(InputStream inputStream = Files.newInputStream(outputFile.toPath());
+          InputStream inStream = isGzip ? new GZIPInputStream(inputStream) : inputStream) {
+        assertThat(String.valueOf(IOUtils.toCharArray(inStream, StandardCharsets.UTF_8)), is(content));
       }
+    } finally {
       inputFile.delete();
       outputFile.delete();
     }
index e611b9b..2cb1000 100644 (file)
@@ -618,7 +618,6 @@ public class HtmlFilterReaderBaseTest {
       Reader reader;
       UrlRewriteRulesDescriptor config;
       UrlRewriteRuleDescriptor rule;
-      List<UrlRewriteStepDescriptor> steps;
       UrlRewriteCheckDescriptorExt step;
 
       reader = new StringReader( "<rules><rule><check></check></rule></rules>" );
@@ -691,7 +690,6 @@ public class HtmlFilterReaderBaseTest {
       Reader reader;
       UrlRewriteRulesDescriptor config;
       UrlRewriteRuleDescriptor rule;
-      List<UrlRewriteStepDescriptor> steps;
 
       reader = new StringReader( "<rules><rule><control></control></rule></rules>" );
       config = digester.parse( reader );
@@ -739,27 +737,4 @@ public class HtmlFilterReaderBaseTest {
     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;
-    }
-  }
-
 }
index 25488a0..3a022e0 100644 (file)
@@ -40,6 +40,7 @@ import java.util.Random;
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.containsString;
+import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.fail;
 
 public class JsonFilterReaderTest {
@@ -53,6 +54,7 @@ public class JsonFilterReaderTest {
     UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
     UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "$.apps.app[*]" );
     UrlRewriteFilterApplyDescriptor applyConfig = bufferConfig.addApply( "$.id", "test-rule" );
+    assertNotNull(applyConfig);
 
     JsonFilterReader filter = new JsonFilterReader( new StringReader( input ), contentConfig );
     String output = IOUtils.toString( filter );
@@ -161,6 +163,7 @@ public class JsonFilterReaderTest {
     UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter=1" );
     UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
     UrlRewriteFilterApplyDescriptor applyConfig = contentConfig.addApply( "$['test-str']", "test-rule" );
+    assertNotNull(applyConfig);
 
     JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
     String output = IOUtils.toString( filter );
@@ -261,6 +264,7 @@ public class JsonFilterReaderTest {
     UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
     UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "$" );
     UrlRewriteFilterApplyDescriptor applyConfig = bufferConfig.addApply( "$['name<test-str>']", "test-rule" );
+    assertNotNull(applyConfig);
     //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
 
     JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
@@ -284,6 +288,7 @@ public class JsonFilterReaderTest {
     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" );
+    assertNotNull(applyConfig);
 
     //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
 
@@ -312,6 +317,7 @@ public class JsonFilterReaderTest {
     UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
     UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "$.name<properties>.*.name<property>" );
     UrlRewriteFilterApplyDescriptor applyConfig = bufferConfig.addApply( "$.name<property-value>", "test-rule" );
+    assertNotNull(applyConfig);
 
     //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
 
@@ -340,6 +346,7 @@ public class JsonFilterReaderTest {
     UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/json" );
     UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "$.name<properties>" );
     UrlRewriteFilterApplyDescriptor applyConfig = bufferConfig.addApply( "$.*.name<property>.name<property-value>", "test-rule" );
+    assertNotNull(applyConfig);
 
     //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
 
@@ -395,10 +402,4 @@ public class JsonFilterReaderTest {
     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();
-//  }
-
 }
index e489f7a..d041661 100644 (file)
@@ -65,6 +65,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.contains;
 import static org.hamcrest.Matchers.containsString;
 import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.fail;
 import static org.xmlmatchers.XmlMatchers.hasXPath;
 import static org.xmlmatchers.transform.XmlConverters.the;
@@ -147,6 +148,7 @@ public class XmlFilterReaderTest {
     UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
     UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
     UrlRewriteFilterBufferDescriptor scopeConfig = contentConfig.addBuffer( "/root" );
+    assertNotNull(scopeConfig);
 
     String input = "<root/>";
     //System.out.println( "INPUT=" + input );
@@ -211,6 +213,7 @@ public class XmlFilterReaderTest {
     UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
     UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
     UrlRewriteFilterBufferDescriptor scopeConfig = contentConfig.addBuffer( "/root" );
+    assertNotNull(scopeConfig);
 
     String inputXml = "<root>text</root>";
     StringReader inputReader = new StringReader( inputXml );
@@ -226,6 +229,7 @@ public class XmlFilterReaderTest {
     UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
     UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
     UrlRewriteFilterBufferDescriptor scopeConfig = contentConfig.addBuffer( "/root" );
+    assertNotNull(scopeConfig);
 
     String inputXml = "<root name='value'/>";
     StringReader inputReader = new StringReader( inputXml );
@@ -587,7 +591,6 @@ public class XmlFilterReaderTest {
       Reader reader;
       UrlRewriteRulesDescriptor config;
       UrlRewriteRuleDescriptor rule;
-      List<UrlRewriteStepDescriptor> steps;
       UrlRewriteCheckDescriptorExt step;
 
       reader = new StringReader( "<rules><rule><check></check></rule></rules>" );
@@ -660,7 +663,6 @@ public class XmlFilterReaderTest {
       Reader reader;
       UrlRewriteRulesDescriptor config;
       UrlRewriteRuleDescriptor rule;
-      List<UrlRewriteStepDescriptor> steps;
 
       reader = new StringReader( "<rules><rule><control></control></rule></rules>" );
       config = digester.parse( reader );
@@ -720,6 +722,7 @@ public class XmlFilterReaderTest {
     UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
     UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
     UrlRewriteFilterApplyDescriptor applyConfig = contentConfig.addApply( "/properties/property/value/text()", "test-rule-2" );
+    assertNotNull(applyConfig);
 
     //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
 
@@ -747,6 +750,7 @@ public class XmlFilterReaderTest {
     UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
     UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
     UrlRewriteFilterApplyDescriptor applyConfig = contentConfig.addApply( "/properties/property/value", "test-rule-2" );
+    assertNotNull(applyConfig);
 
     //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
 
@@ -774,6 +778,7 @@ public class XmlFilterReaderTest {
     UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "filter-1" );
     UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
     UrlRewriteFilterApplyDescriptor applyConfig = contentConfig.addApply( "/properties/property/@value", "test-rule-2" );
+    assertNotNull(applyConfig);
 
     //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
 
@@ -802,6 +807,7 @@ public class XmlFilterReaderTest {
     UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "text/xml" );
     UrlRewriteFilterBufferDescriptor bufferconfig = contentConfig.addBuffer( "/properties/property" );
     UrlRewriteFilterApplyDescriptor applyConfig = bufferconfig.addApply( "@value", "test-rule-2" );
+    assertNotNull(applyConfig);
 
     //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
 
@@ -831,6 +837,7 @@ public class XmlFilterReaderTest {
     UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "/properties/property" );
     UrlRewriteFilterDetectDescriptor detectConfig = bufferConfig.addDetect( "name", "test-name-2" );
     UrlRewriteFilterApplyDescriptor applyConfig = detectConfig.addApply( "value", "test-rule-2" );
+    assertNotNull(applyConfig);
 
     //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
 
@@ -860,6 +867,7 @@ public class XmlFilterReaderTest {
     UrlRewriteFilterBufferDescriptor bufferConfig = contentConfig.addBuffer( "/properties/property" );
     UrlRewriteFilterDetectDescriptor detectConfig = bufferConfig.addDetect( "@name", "test-name-2" );
     UrlRewriteFilterApplyDescriptor applyConfig = detectConfig.addApply( "@value", "test-rule-2" );
+    assertNotNull(applyConfig);
 
     //UrlRewriteRulesDescriptorFactory.store( rulesConfig, "xml", new PrintWriter( System.out ) );
 
index 959d09c..31f3602 100644 (file)
@@ -25,6 +25,7 @@ import org.apache.knox.gateway.filter.rewrite.ext.UrlRewriteActionRewriteDescrip
 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.Assert;
 import org.junit.Test;
 import org.xmlmatchers.XmlMatchers;
 import org.xmlmatchers.transform.XmlConverters;
@@ -57,7 +58,6 @@ public class XmlUrlRewriteRulesExporterTest {
     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" ) );
@@ -77,7 +77,6 @@ public class XmlUrlRewriteRulesExporterTest {
     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" ) );
@@ -102,7 +101,6 @@ public class XmlUrlRewriteRulesExporterTest {
     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" ) );
@@ -124,7 +122,6 @@ public class XmlUrlRewriteRulesExporterTest {
     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" ) );
@@ -148,7 +145,6 @@ public class XmlUrlRewriteRulesExporterTest {
     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" ) );
@@ -169,26 +165,38 @@ public class XmlUrlRewriteRulesExporterTest {
     UrlRewriteCheckDescriptor matchCheck = match.addStep( "check" );
     UrlRewriteControlDescriptor matchControl = match.addStep( "control" );
     UrlRewriteActionDescriptor matchRewrite = match.addStep( "rewrite" );
+    Assert.assertNotNull(matchMatch);
+    Assert.assertNotNull(matchCheck);
+    Assert.assertNotNull(matchControl);
+    Assert.assertNotNull(matchRewrite);
 
     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" );
+    Assert.assertNotNull(checkMatch);
+    Assert.assertNotNull(checkCheck);
+    Assert.assertNotNull(checkControl);
+    Assert.assertNotNull(checkRewrite);
 
     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" );
+    Assert.assertNotNull(controlMatch);
+    Assert.assertNotNull(controlCheck);
+    Assert.assertNotNull(controlControl);
+    Assert.assertNotNull(controlRewrite);
 
     UrlRewriteActionDescriptor rewrite = rule.addStep( "rewrite" );
+    Assert.assertNotNull(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" ) );
@@ -211,5 +219,4 @@ public class XmlUrlRewriteRulesExporterTest {
     assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/control/rewrite" ) );
     assertThat( xml, XmlMatchers.hasXPath( "/rules/rule/rewrite" ) );
   }
-
 }
index 113b499..3096916 100644 (file)
@@ -19,6 +19,7 @@ package org.apache.knox.gateway.filter;
 
 import org.junit.Test;
 
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
@@ -29,7 +30,7 @@ import static org.junit.Assert.fail;
  */
 public class AclParserTest {
   @Test
-  public void testValidAcls() throws Exception {
+  public void testValidAcls() {
     AclParser p = new AclParser();
     p.parseAcls("test", "guest;*;*");
     assertTrue(p.users.contains("guest"));
@@ -91,7 +92,7 @@ public class AclParserTest {
   }
 
   @Test
-  public void testValidMultiValuedAcls() throws Exception {
+  public void testValidMultiValuedAcls() {
     AclParser p = new AclParser();
     p.parseAcls("test", "*;admins;127.0.0.1,127.0.0.2");
     assertFalse(p.users.contains("guest"));
@@ -133,81 +134,78 @@ public class AclParserTest {
   }
 
   @Test
-  public void testNullACL() throws Exception {
+  public void testNullACL() {
     AclParser p = new AclParser();
     try {
       p.parseAcls("test", null);
-    }
-    catch (InvalidACLException sle) {
-      // expected
+    } catch (InvalidACLException sle) {
       fail("NULL acl should NOT have thrown InvalidACLException.");
     }
   }
 
   @Test
-  public void testInvalidAcls() throws Exception {
+  public void testInvalidAcls() {
     AclParser p = new AclParser();
     try {
       p.parseAcls("test", "guest");
       fail("Invalid acl should have thrown InvalidACLException.");
-    }
-    catch (InvalidACLException sle) {
+    } catch (InvalidACLException sle) {
       // expected
+      assertEquals("Invalid ACLs specified for requested resource: test", sle.getMessage());
     }
 
     p = new AclParser();
     try {
       p.parseAcls("test", "guest;;");
       fail("Invalid acl should have thrown InvalidACLException.");
-    }
-    catch (InvalidACLException sle) {
+    } catch (InvalidACLException sle) {
       // expected
+      assertEquals("Invalid ACLs specified for requested resource: test", sle.getMessage());
     }
 
     p = new AclParser();
     try {
       p.parseAcls("test", ";;");
       fail("Invalid acl should have thrown InvalidACLException.");
-    }
-    catch (InvalidACLException sle) {
+    } catch (InvalidACLException sle) {
       // expected
+      assertEquals("Invalid ACLs specified for requested resource: test", sle.getMessage());
     }
 
     p = new AclParser();
     try {
       p.parseAcls("test", ";");
       fail("Invalid acl should have thrown InvalidACLException.");
-    }
-    catch (InvalidACLException sle) {
+    } catch (InvalidACLException sle) {
       // expected
+      assertEquals("Invalid ACLs specified for requested resource: test", sle.getMessage());
     }
 
     p = new AclParser();
     try {
       p.parseAcls("test", "guest;");
       fail("Invalid acl should have thrown InvalidACLException.");
-    }
-    catch (InvalidACLException sle) {
+    } catch (InvalidACLException sle) {
       // expected
+      assertEquals("Invalid ACLs specified for requested resource: test", sle.getMessage());
     }
 
     p = new AclParser();
     try {
       p.parseAcls("test", ";admins");
       fail("Invalid acl should have thrown InvalidACLException.");
-    }
-    catch (InvalidACLException sle) {
+    } catch (InvalidACLException sle) {
       // expected
+      assertEquals("Invalid ACLs specified for requested resource: test", sle.getMessage());
     }
 
     p = new AclParser();
     try {
       p.parseAcls("test", "");
       fail("Invalid acl should have thrown InvalidACLException.");
-    }
-    catch (InvalidACLException sle) {
+    } catch (InvalidACLException sle) {
       // expected
+      assertEquals("Invalid ACLs specified for requested resource: test", sle.getMessage());
     }
   }
-
 }
index 43c9bec..396a13b 100644 (file)
@@ -21,7 +21,6 @@ import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
 import java.io.IOException;
-import java.net.URISyntaxException;
 import java.security.PrivilegedActionException;
 import java.security.PrivilegedExceptionAction;
 
@@ -46,13 +45,12 @@ public class AclsAuthzFilterTest {
   private Filter filter;
 
   @Before
-  public void setup() {
+  public void setUp() {
     filter = new AclsAuthorizationFilter() {
       @Override
       public void doFilter(ServletRequest request, ServletResponse response,
                            FilterChain chain) throws IOException, ServletException {
         boolean accessGranted = enforceAclAuthorizationPolicy(request, response, chain);
-        String sourceUrl = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
         if (accessGranted) {
           chain.doFilter(request, response);
         }
@@ -68,9 +66,7 @@ public class AclsAuthzFilterTest {
   }
 
   @Test
-  public void testKnoxAdminGroupsValid() throws ServletException, IOException,
-      URISyntaxException {
-
+  public void testKnoxAdminGroupsValid() throws ServletException, IOException {
     FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
     EasyMock.expect(config.getInitParameter("knox.admin.users")).andReturn(null);
     EasyMock.expect(config.getInitParameter("knox.admin.groups")).andReturn("admin");
@@ -125,9 +121,7 @@ public class AclsAuthzFilterTest {
   }
 
   @Test
-  public void testKnoxAdminGroupsInvalid() throws ServletException, IOException,
-      URISyntaxException {
-
+  public void testKnoxAdminGroupsInvalid() throws ServletException, IOException {
     FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
     EasyMock.expect(config.getInitParameter("knox.admin.users")).andReturn(null);
     EasyMock.expect(config.getInitParameter("knox.admin.groups")).andReturn("admin");
@@ -144,8 +138,7 @@ public class AclsAuthzFilterTest {
 
     final FilterChain chain = new FilterChain() {
       @Override
-      public void doFilter(ServletRequest request, ServletResponse response)
-          throws IOException, ServletException {
+      public void doFilter(ServletRequest request, ServletResponse response) {
       }
     };
 
@@ -182,9 +175,7 @@ public class AclsAuthzFilterTest {
   }
 
   @Test
-  public void testKnoxAdminUsersValid() throws ServletException, IOException,
-      URISyntaxException {
-
+  public void testKnoxAdminUsersValid() throws ServletException, IOException {
     FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
     EasyMock.expect(config.getInitParameter("knox.admin.users")).andReturn("adminuser");
     EasyMock.expect(config.getInitParameter("knox.admin.groups")).andReturn(null);
@@ -201,8 +192,7 @@ public class AclsAuthzFilterTest {
 
     final FilterChain chain = new FilterChain() {
       @Override
-      public void doFilter(ServletRequest request, ServletResponse response)
-          throws IOException, ServletException {
+      public void doFilter(ServletRequest request, ServletResponse response) {
       }
     };
 
@@ -239,9 +229,7 @@ public class AclsAuthzFilterTest {
   }
 
   @Test
-  public void testKnoxAdminUsersInvalid() throws ServletException, IOException,
-      URISyntaxException {
-
+  public void testKnoxAdminUsersInvalid() throws ServletException, IOException {
     FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
     EasyMock.expect(config.getInitParameter("knox.admin.users")).andReturn("adminuser");
     EasyMock.expect(config.getInitParameter("knox.admin.groups")).andReturn(null);
@@ -258,8 +246,7 @@ public class AclsAuthzFilterTest {
 
     final FilterChain chain = new FilterChain() {
       @Override
-      public void doFilter(ServletRequest request, ServletResponse response)
-          throws IOException, ServletException {
+      public void doFilter(ServletRequest request, ServletResponse response) {
       }
     };
 
@@ -296,9 +283,7 @@ public class AclsAuthzFilterTest {
   }
 
   @Test
-  public void testKnoxAdminUsersInvalidButACLUsersValid() throws ServletException, IOException,
-      URISyntaxException {
-
+  public void testKnoxAdminUsersInvalidButACLUsersValid() throws ServletException, IOException {
     FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
     EasyMock.expect(config.getInitParameter("knox.admin.users")).andReturn("adminuser");
     EasyMock.expect(config.getInitParameter("knox.admin.groups")).andReturn(null);
@@ -353,9 +338,7 @@ public class AclsAuthzFilterTest {
   }
 
   @Test
-  public void testKnoxAdminUsersInvalidButACLGroupValid() throws ServletException, IOException,
-      URISyntaxException {
-
+  public void testKnoxAdminUsersInvalidButACLGroupValid() throws ServletException, IOException {
     FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
     EasyMock.expect(config.getInitParameter("knox.admin.users")).andReturn("adminuser");
     EasyMock.expect(config.getInitParameter("knox.admin.groups")).andReturn(null);
@@ -372,8 +355,7 @@ public class AclsAuthzFilterTest {
 
     final FilterChain chain = new FilterChain() {
       @Override
-      public void doFilter(ServletRequest request, ServletResponse response)
-          throws IOException, ServletException {
+      public void doFilter(ServletRequest request, ServletResponse response) {
       }
     };
 
@@ -410,9 +392,7 @@ public class AclsAuthzFilterTest {
   }
 
   @Test
-  public void testKnoxAdminUsersInvalidButKnoxAdminGroupValid() throws ServletException, IOException,
-      URISyntaxException {
-
+  public void testKnoxAdminUsersInvalidButKnoxAdminGroupValid() throws ServletException, IOException {
     FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
     EasyMock.expect(config.getInitParameter("knox.admin.users")).andReturn("adminuser");
     EasyMock.expect(config.getInitParameter("knox.admin.groups")).andReturn("admingroup");
@@ -429,8 +409,7 @@ public class AclsAuthzFilterTest {
 
     final FilterChain chain = new FilterChain() {
       @Override
-      public void doFilter(ServletRequest request, ServletResponse response)
-          throws IOException, ServletException {
+      public void doFilter(ServletRequest request, ServletResponse response) {
       }
     };
 
index 23967c9..22a46fd 100644 (file)
@@ -90,7 +90,7 @@ public abstract class AbstractJWTFilterTest  {
   }
 
   @BeforeClass
-  public static void generateKeys() throws Exception {
+  public static void setUpBeforeClass() throws Exception {
     KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
     kpg.initialize(2048);
     KeyPair KPair = kpg.generateKeyPair();
@@ -105,7 +105,7 @@ public abstract class AbstractJWTFilterTest  {
   }
 
   @After
-  public void teardown() {
+  public void tearDown() {
     handler.destroy();
   }
 
index e0da4f1..7fc28a6 100644 (file)
@@ -19,7 +19,6 @@ 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;
@@ -45,7 +44,7 @@ public class SSOCookieProviderTest extends AbstractJWTFilterTest {
   private static final String SERVICE_URL = "https://localhost:8888/resource";
 
   @Before
-  public void setup() throws Exception, NoSuchAlgorithmException {
+  public void setUp() {
     handler = new TestSSOCookieFederationProvider();
     ((TestSSOCookieFederationProvider) handler).setTokenService(new TestJWTokenAuthority(publicKey));
   }
@@ -100,7 +99,7 @@ public class SSOCookieProviderTest extends AbstractJWTFilterTest {
   }
 
   @Test
-  public void testNoProviderURLJWT() throws Exception {
+  public void testNoProviderURLJWT() {
     try {
       Properties props = getProperties();
       props.remove("sso.authentication.provider.url");
@@ -123,7 +122,7 @@ public class SSOCookieProviderTest extends AbstractJWTFilterTest {
     EasyMock.expect(request.getQueryString()).andReturn("name=value");
     EasyMock.replay(request);
 
-    String loginURL = ((TestSSOCookieFederationProvider)handler).testConstructLoginURL(request);
+    String loginURL = ((TestSSOCookieFederationProvider)handler).constructLoginURL(request);
     Assert.assertNotNull("loginURL should not be null.", loginURL);
     Assert.assertEquals("https://localhost:8443/authserver?originalUrl=" + SERVICE_URL + "?name=value", loginURL);
   }
@@ -139,7 +138,7 @@ public class SSOCookieProviderTest extends AbstractJWTFilterTest {
     EasyMock.expect(request.getQueryString()).andReturn(null);
     EasyMock.replay(request);
 
-    String loginURL = ((TestSSOCookieFederationProvider)handler).testConstructLoginURL(request);
+    String loginURL = ((TestSSOCookieFederationProvider)handler).constructLoginURL(request);
     Assert.assertNotNull("LoginURL should not be null.", loginURL);
     Assert.assertEquals("https://localhost:8443/authserver?originalUrl=" + SERVICE_URL, loginURL);
   }
@@ -162,7 +161,7 @@ public class SSOCookieProviderTest extends AbstractJWTFilterTest {
     Assert.assertNotNull("LoginURL should not be null.", providerURL);
     Assert.assertEquals(providerURL, "https://localhost:8443/gateway/knoxsso/api/v1/websso");
 
-    String loginURL = ((TestSSOCookieFederationProvider) handler).testConstructLoginURL(request);
+    String loginURL = ((TestSSOCookieFederationProvider) handler).constructLoginURL(request);
     Assert.assertNotNull("LoginURL should not be null.", loginURL);
     Assert.assertEquals(loginURL, "https://localhost:8443/gateway/knoxsso/api/v1/websso?originalUrl=" + SERVICE_URL);
   }
@@ -184,7 +183,7 @@ public class SSOCookieProviderTest extends AbstractJWTFilterTest {
     Assert.assertNotNull("LoginURL should not be null.", providerURL);
     Assert.assertEquals(providerURL, "https://remotehost:8443/gateway/knoxsso/api/v1/websso");
 
-    String loginURL = ((TestSSOCookieFederationProvider) handler).testConstructLoginURL(request);
+    String loginURL = ((TestSSOCookieFederationProvider) handler).constructLoginURL(request);
     Assert.assertNotNull("LoginURL should not be null.", loginURL);
     Assert.assertEquals(loginURL, "https://remotehost:8443/gateway/knoxsso/api/v1/websso?originalUrl=" + SERVICE_URL);
   }
@@ -206,7 +205,7 @@ public class SSOCookieProviderTest extends AbstractJWTFilterTest {
     Assert.assertNotNull("LoginURL should not be null.", providerURL);
     Assert.assertEquals(providerURL, "https://remotehost:8443/notgateway/knoxsso/api/v1/websso");
 
-    String loginURL = ((TestSSOCookieFederationProvider) handler).testConstructLoginURL(request);
+    String loginURL = ((TestSSOCookieFederationProvider) handler).constructLoginURL(request);
     Assert.assertNotNull("LoginURL should not be null.", loginURL);
     Assert.assertEquals(loginURL, "https://remotehost:8443/notgateway/knoxsso/api/v1/websso?originalUrl=" + SERVICE_URL);
   }
@@ -217,13 +216,13 @@ public class SSOCookieProviderTest extends AbstractJWTFilterTest {
   }
 
   private static class TestSSOCookieFederationProvider extends SSOCookieFederationFilter {
-    public String testConstructLoginURL(HttpServletRequest req) {
-      return constructLoginURL(req);
+    @Override
+    public String constructLoginURL(HttpServletRequest req) {
+      return super.constructLoginURL(req);
     }
 
-    public void setTokenService(JWTokenAuthority ts) {
+    void setTokenService(JWTokenAuthority ts) {
       authority = ts;
     }
   }
-
 }
index 6608e28..688465d 100644 (file)
@@ -32,7 +32,6 @@ import java.util.Map;
 public class MockHttpServletResponse extends HttpServletResponseWrapper {
 
     private List<Cookie> cookies = new ArrayList<>();
-    private String location;
     private int status;
     private Map<String, String> headers = new HashMap<>();
 
index 86516fe..2cd72d3 100644 (file)
@@ -124,7 +124,7 @@ public class HeaderPreAuthFederationFilterTest extends org.junit.Assert {
 
 
   public static class DummyValidator implements PreAuthValidator {
-    static String NAME = "DummyValidator";
+    static final String NAME = "DummyValidator";
 
     public DummyValidator() {
 
@@ -133,7 +133,7 @@ public class HeaderPreAuthFederationFilterTest extends org.junit.Assert {
     @Override
     public boolean validate(HttpServletRequest httpRequest, FilterConfig filterConfig) {
       String token = httpRequest.getHeader("CUSTOM_TOKEN");
-      return token.equalsIgnoreCase("HelloWorld");
+      return "HelloWorld".equalsIgnoreCase(token);
     }
 
     @Override
@@ -141,5 +141,4 @@ public class HeaderPreAuthFederationFilterTest extends org.junit.Assert {
       return NAME;
     }
   }
-
 }
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
deleted file mode 100644 (file)
index 6b90400..0000000
+++ /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.knox.gateway.provider.federation;
-
-import org.junit.Test;
-
-public class PreAuthSSOTest extends org.junit.Assert {
-  @Test
-  public void testPreAuth() throws Exception {
-    assertTrue(true);
-  }
-}
index cae69ee..3d812b2 100644 (file)
@@ -124,6 +124,9 @@ public class PreAuthServiceTest extends org.junit.Assert {
       fail("Should throw exception due to invalid validator");
     } catch (Exception e) {
       //Expected
+      assertEquals("Unable to find validator with name 'preauth.default.validation,  " +
+                       "NOT_EXISTED_VALIDATOR'",
+          e.getMessage());
     }
   }
 }
index 5372efb..d8a544d 100644 (file)
@@ -26,13 +26,10 @@ import java.util.NoSuchElementException;
 
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.fail;
 
 public class CompositeEnumerationTest {
-
   @Test
   public void testBasics() {
-
     String[] a = new String[]{ "1", "2" };
     Enumeration<String> ea = Collections.enumeration( Arrays.asList( a ) );
 
@@ -46,7 +43,6 @@ public class CompositeEnumerationTest {
     assertThat( ce.nextElement(), is( "3" ) );
     assertThat( ce.nextElement(), is( "4" ) );
     assertThat( ce.hasMoreElements(), is( false ) );
-
   }
 
   @Test
@@ -66,7 +62,6 @@ public class CompositeEnumerationTest {
 
   @Test
   public void testEmptyEnumerations() {
-
     String[] a = new String[]{ "1", "2" };
     String[] b = new String[]{ "3", "4" };
     String[] c = new String[]{};
@@ -91,27 +86,15 @@ public class CompositeEnumerationTest {
     assertThat( ce.hasMoreElements(), is( false ) );
   }
 
-  @Test
+  @Test (expected = NoSuchElementException.class)
   public void testEmpty() {
     CompositeEnumeration<String> ce = new CompositeEnumeration<>();
     assertThat( ce.hasMoreElements(), is( false ) );
-
-    try {
-      ce.nextElement();
-      fail( "Should have throws NoSuchElementExcpetion" );
-    } catch( NoSuchElementException e ) {
-      // Expected.
-    }
+    ce.nextElement();
   }
 
-  @Test
+  @Test (expected = IllegalArgumentException.class)
   public void testNulls() {
-    try {
-      CompositeEnumeration<String> ce = new CompositeEnumeration<>( null );
-      fail( "Expected IllegalArgumentException" );
-    } catch( IllegalArgumentException e ) {
-      // Expected.
-    }
+    new CompositeEnumeration<>( null );
   }
-
 }
index e3b2378..e5a0d6e 100644 (file)
@@ -28,7 +28,9 @@ 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 );
+    if( !isEmpty() ) {
+      pop().doFilter( request, response, this );
+    }
   }
 }
 
index affd47d..861a886 100644 (file)
@@ -30,7 +30,6 @@ import org.apache.knox.gateway.audit.log4j.audit.Log4jAuditService;
 import org.apache.knox.gateway.audit.log4j.correlation.Log4jCorrelationService;
 import org.apache.knox.gateway.config.GatewayConfig;
 import org.apache.knox.gateway.dispatch.DefaultDispatch;
-import org.apache.knox.gateway.i18n.resources.ResourcesFactory;
 import org.apache.knox.test.log.CollectAppender;
 import org.apache.log4j.spi.LoggingEvent;
 import org.easymock.EasyMock;
@@ -76,16 +75,14 @@ public class AuditLoggingTest {
   private static final String ADDRESS = "address";
   private static final String HOST = "host";
 
-  private static final GatewayResources RES = ResourcesFactory.get( GatewayResources.class );
-
   @Before
-  public void loggingSetup() {
+  public void setUp() {
     AuditServiceFactory.getAuditService().createContext();
     CollectAppender.queue.clear();
   }
 
   @After
-  public void reset() {
+  public void tearDown() {
     AuditServiceFactory.getAuditService().detachContext();
   }
 
@@ -291,11 +288,4 @@ public class AuditLoggingTest {
       assertThat( actual, is( expected ) );
     }
   }
-
-  private String getRequestId( LoggingEvent event ) {
-    CorrelationContext cc = (CorrelationContext) event
-        .getMDC( Log4jCorrelationService.MDC_CORRELATION_CONTEXT_KEY );
-    return cc == null ? null : cc.getRequestId();
-  }
-
 }
index 6f5129e..5e0d844 100644 (file)
@@ -46,12 +46,12 @@ import static org.hamcrest.MatcherAssert.assertThat;
 public class GatewayFilterTest {
 
   @Before
-  public void setup() {
+  public void setUp() {
     AuditServiceFactory.getAuditService().createContext();
   }
 
   @After
-  public void reset() {
+  public void tearDown() {
     AuditServiceFactory.getAuditService().detachContext();
   }
 
index a74a985..9fde6ad 100644 (file)
@@ -36,10 +36,10 @@ import org.xml.sax.SAXException;
 import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.core.IsEqual.equalTo;
 import static org.hamcrest.xml.HasXPath.hasXPath;
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.fail;
 
 public class DeploymentFactoryTest {
-
   @Test( timeout = TestUtils.MEDIUM_TIMEOUT )
   public void testEmptyTopology() throws IOException, SAXException, ParserConfigurationException, TransformerException {
     GatewayConfig config = new GatewayConfigImpl();
@@ -90,6 +90,9 @@ public class DeploymentFactoryTest {
       fail( "Expected DeploymentException" );
     } catch ( DeploymentException e ) {
       // Expected.
+      assertEquals("Topology test-topology contains both services and " +
+                       "an application test-application with a root url.",
+          e.getMessage());
     }
 
     topology = new Topology();
@@ -107,6 +110,9 @@ public class DeploymentFactoryTest {
       fail( "Expected DeploymentException" );
     } catch ( DeploymentException e ) {
       // Expected.
+      assertEquals("Topology test-topology contains both services and an " +
+                       "application test-application with a root url.",
+          e.getMessage());
     }
 
     topology = new Topology();
@@ -124,6 +130,9 @@ public class DeploymentFactoryTest {
       fail( "Expected DeploymentException" );
     } catch ( DeploymentException e ) {
       // Expected.
+      assertEquals("Topology test-topology contains both services and an " +
+                       "application test-application with a root url.",
+          e.getMessage());
     }
 
     topology = new Topology();
@@ -142,8 +151,10 @@ public class DeploymentFactoryTest {
       fail( "Expected DeploymentException" );
     } catch ( DeploymentException e ) {
       // Expected.
+      assertEquals("Topology test-topology contains both services and an " +
+                       "application test-application with a root url.",
+          e.getMessage());
     }
-
   }
 
   @Test( timeout = TestUtils.SHORT_TIMEOUT )
@@ -233,6 +244,10 @@ public class DeploymentFactoryTest {
       fail( "Expected DeploymentException" );
     } catch ( DeploymentException e ) {
       // Expected.
+      assertEquals("Topology test-topology contains applications " +
+                       "test-application-1 and test-application-2 with the " +
+                       "same url: /test-application-dup",
+          e.getMessage());
     }
 
     topology = new Topology();
@@ -250,6 +265,9 @@ public class DeploymentFactoryTest {
       fail( "Expected DeploymentException" );
     } catch ( DeploymentException e ) {
       // Expected.
+      assertEquals("Topology test-topology contains applications " +
+                       "test-application-1 and test-application-2 with the same url: /",
+          e.getMessage());
     }
 
     topology = new Topology();
@@ -267,6 +285,9 @@ public class DeploymentFactoryTest {
       fail( "Expected DeploymentException" );
     } catch ( DeploymentException e ) {
       // Expected.
+      assertEquals("Topology test-topology contains applications " +
+                       "test-application-1 and test-application-2 with the same url: ",
+          e.getMessage());
     }
 
     topology = new Topology();
@@ -283,6 +304,10 @@ public class DeploymentFactoryTest {
       fail( "Expected DeploymentException" );
     } catch ( DeploymentException e ) {
       // Expected.
+      assertEquals("Topology test-topology contains applications " +
+                       "test-application-1 and test-application-2 with the " +
+                       "same url: test-application-1",
+          e.getMessage());
     }
 
     topology = new Topology();
@@ -298,6 +323,10 @@ public class DeploymentFactoryTest {
       fail( "Expected DeploymentException" );
     } catch ( DeploymentException e ) {
       // Expected.
+      assertEquals("Topology test-topology contains applications " +
+                       "test-application-1 and test-application-1 with the " +
+                       "same url: test-application-1",
+          e.getMessage());
     }
 
     topology = new Topology();
@@ -317,8 +346,10 @@ public class DeploymentFactoryTest {
       fail( "Expected DeploymentException" );
     } catch ( DeploymentException e ) {
       // Expected.
+      assertEquals("Topology test-topology contains applications " +
+                       "test-application-1 and test-application-2 with the " +
+                       "same url: /test-application-3",
+          e.getMessage());
     }
-
   }
-
 }
index 16f0c55..10c635f 100644 (file)
@@ -138,8 +138,8 @@ public class ServiceDefinitionDeploymentContributorTest {
     sddc.contributeService(context, service);
 
     List<ResourceDescriptor> resources = gd.resources();
-    assertEquals(1, gd.resources().size());
-    ResourceDescriptor res = gd.resources().get(0);
+    assertEquals(1, resources.size());
+    ResourceDescriptor res = resources.get(0);
     assertNotNull(res);
     List<FilterDescriptor> filterList = res.filters();
     assertEquals(1, filterList.size());
@@ -254,8 +254,8 @@ public class ServiceDefinitionDeploymentContributorTest {
     sddc.contributeService(context, service);
 
     List<ResourceDescriptor> resources = gd.resources();
-    assertEquals(1, gd.resources().size());
-    ResourceDescriptor res = gd.resources().get(0);
+    assertEquals(1, resources.size());
+    ResourceDescriptor res = resources.get(0);
     assertNotNull(res);
     List<FilterDescriptor> filterList = res.filters();
     assertEquals(1, filterList.size());
index 24f1665..2251f16 100644 (file)
@@ -40,7 +40,6 @@ public class DefaultTokenAuthorityServiceTest extends org.junit.Assert {
 
   @Test
   public void testTokenCreation() throws Exception {
-
     Principal principal = EasyMock.createNiceMock(Principal.class);
     EasyMock.expect(principal.getName()).andReturn("john.doe@example.com");
 
@@ -82,7 +81,6 @@ public class DefaultTokenAuthorityServiceTest extends org.junit.Assert {
 
   @Test
   public void testTokenCreationAudience() throws Exception {
-
     Principal principal = EasyMock.createNiceMock(Principal.class);
     EasyMock.expect(principal.getName()).andReturn("john.doe@example.com");
 
@@ -125,7 +123,6 @@ public class DefaultTokenAuthorityServiceTest extends org.junit.Assert {
 
   @Test
   public void testTokenCreationNullAudience() throws Exception {
-
     Principal principal = EasyMock.createNiceMock(Principal.class);
     EasyMock.expect(principal.getName()).andReturn("john.doe@example.com");
 
@@ -167,7 +164,6 @@ public class DefaultTokenAuthorityServiceTest extends org.junit.Assert {
 
   @Test
   public void testTokenCreationSignatureAlgorithm() throws Exception {
-
     Principal principal = EasyMock.createNiceMock(Principal.class);
     EasyMock.expect(principal.getName()).andReturn("john.doe@example.com");
 
@@ -208,9 +204,8 @@ public class DefaultTokenAuthorityServiceTest extends org.junit.Assert {
     assertTrue(ta.verifyToken(token));
   }
 
-  @Test
+  @Test (expected = TokenServiceException.class)
   public void testTokenCreationBadSignatureAlgorithm() throws Exception {
-
     Principal principal = EasyMock.createNiceMock(Principal.class);
     EasyMock.expect(principal.getName()).andReturn("john.doe@example.com");
 
@@ -242,13 +237,7 @@ public class DefaultTokenAuthorityServiceTest extends org.junit.Assert {
     ta.setKeystoreService(ks);
 
     ta.init(config, new HashMap<>());
-
-    try {
-      ta.issueToken(principal, "none");
-      fail("Failure expected on a bad signature algorithm");
-    } catch (TokenServiceException ex) {
-        // expected
-    }
+    ta.issueToken(principal, "none");
   }
 
   @Test
index 99dd6d4..c0b861e 100644 (file)
@@ -21,8 +21,6 @@ import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.FilenameUtils;
 import org.apache.commons.io.IOUtils;
 import org.apache.commons.io.monitor.FileAlterationListener;
-import org.apache.commons.io.monitor.FileAlterationMonitor;
-import org.apache.commons.io.monitor.FileAlterationObserver;
 import org.apache.knox.gateway.config.GatewayConfig;
 import org.apache.knox.gateway.services.topology.impl.DefaultTopologyService;
 import org.apache.knox.gateway.services.security.AliasService;
@@ -62,7 +60,6 @@ import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
 
 public class DefaultTopologyServiceTest {
-
   private File createDir() throws IOException {
     return TestUtils.createTempDir(this.getClass().getSimpleName() + "-");
   }
@@ -101,7 +98,6 @@ public class DefaultTopologyServiceTest {
       createFile(topologyDir, "one.xml", "org/apache/knox/gateway/topology/file/topology-one.xml", time);
 
       TestTopologyListener topoListener = new TestTopologyListener();
-      FileAlterationMonitor monitor = new FileAlterationMonitor(Long.MAX_VALUE);
 
       TopologyService provider = new DefaultTopologyService();
       Map<String, String> c = new HashMap<>();
@@ -203,7 +199,6 @@ public class DefaultTopologyServiceTest {
 
     try {
       TestTopologyListener topoListener = new TestTopologyListener();
-      FileAlterationMonitor monitor = new FileAlterationMonitor(Long.MAX_VALUE);
 
       DefaultTopologyService provider = new DefaultTopologyService();
       Map<String, String> c = new HashMap<>();
@@ -322,7 +317,6 @@ public class DefaultTopologyServiceTest {
 
     try {
       TestTopologyListener topoListener = new TestTopologyListener();
-      FileAlterationMonitor monitor = new FileAlterationMonitor(Long.MAX_VALUE);
 
       TopologyService ts = new DefaultTopologyService();
       Map<String, String> c = new HashMap<>();
@@ -415,7 +409,6 @@ public class DefaultTopologyServiceTest {
 
     try {
       TestTopologyListener topoListener = new TestTopologyListener();
-      FileAlterationMonitor monitor = new FileAlterationMonitor(Long.MAX_VALUE);
 
       TopologyService ts = new DefaultTopologyService();
       Map<String, String> c = new HashMap<>();
@@ -544,12 +537,6 @@ public class DefaultTopologyServiceTest {
     }
   }
 
-  private void kickMonitor(FileAlterationMonitor monitor) {
-    for (FileAlterationObserver observer : monitor.getObservers()) {
-      observer.checkAndNotify();
-    }
-  }
-
   @Test
   public void testProviderParamsOrderIsPreserved() {
 
@@ -580,14 +567,12 @@ public class DefaultTopologyServiceTest {
   }
 
   private class TestTopologyListener implements TopologyListener {
-
-    ArrayList<List<TopologyEvent>> events = new ArrayList<>();
+    List<List<TopologyEvent>> events = new ArrayList<>();
 
     @Override
     public void handleTopologyEvent(List<TopologyEvent> events) {
       this.events.add(events);
     }
-
   }
 
   private class TestTopologyDeleteListener implements TopologyListener {
index 1a6bb3b..8896dc3 100644 (file)
@@ -35,12 +35,12 @@ public class PropertyTopologyBuilderTest {
   private static Enumeration<Appender> realAppenders;
 
   @BeforeClass
-  public static void setup() {
+  public static void setUpBeforeClass() {
     realAppenders = NoOpAppender.setUpAndReturnOriginalAppenders();
   }
 
   @AfterClass
-  public static void teardown() {
+  public static void tearDownAfterClass() {
     NoOpAppender.resetOriginalAppenders( realAppenders );
   }
 
index 6a118a1..026adab 100644 (file)
@@ -21,10 +21,10 @@ import org.easymock.EasyMock;
 import org.junit.Test;
 
 import java.io.File;
-import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
 import java.util.HashMap;
 import java.util.List;
-import java.util.Locale;
 import java.util.Map;
 import java.util.Properties;
 
@@ -32,7 +32,6 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 
-
 public class PropertiesFileServiceDiscoveryTest {
 
     private static final Map<String, String> clusterProperties = new HashMap<>();
@@ -57,7 +56,6 @@ public class PropertiesFileServiceDiscoveryTest {
         }
     }
 
-
     @Test
     public void testPropertiesFileServiceDiscovery() throws Exception {
         ServiceDiscovery sd = ServiceDiscoveryFactory.get("PROPERTIES_FILE");
@@ -68,8 +66,8 @@ public class PropertiesFileServiceDiscoveryTest {
 
         String discoveryAddress = this.getClass().getName() + "__test-discovery-source.properties";
         File discoverySource = new File(discoveryAddress);
-        try {
-            config.store(new FileOutputStream(discoverySource), "Test discovery source for PropertiesFileServiceDiscovery");
+        try (OutputStream outputStream = Files.newOutputStream(discoverySource.toPath())){
+            config.store(outputStream, "Test discovery source for PropertiesFileServiceDiscovery");
 
             ServiceDiscovery.Cluster c =
                     sd.discover(gc, new DefaultServiceDiscoveryConfig(discoverySource.getAbsolutePath()), "mycluster");
@@ -101,18 +99,4 @@ public class PropertiesFileServiceDiscoveryTest {
             discoverySource.delete();
         }
     }
-
-
-    private void printServiceURLs(ServiceDiscovery.Cluster cluster, String...services) {
-        for (String name : services) {
-            StringBuilder value = new StringBuilder();
-            List<String> urls = cluster.getServiceURLs(name);
-            if (urls != null && !urls.isEmpty()) {
-                for (String url : urls) {
-                    value.append(url).append(" ");
-                }
-            }
-            System.out.println(String.format(Locale.ROOT, "%18s: %s", name, value.toString()));
-        }
-    }
 }
index fa9a717..e5ad8f3 100644 (file)
@@ -23,8 +23,10 @@ import org.apache.knox.gateway.topology.discovery.GatewayService;
 import org.apache.knox.gateway.topology.discovery.ServiceDiscovery;
 import org.apache.knox.gateway.topology.discovery.ServiceDiscoveryConfig;
 
-import java.io.FileInputStream;
 import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -50,8 +52,8 @@ class PropertiesFileServiceDiscovery implements ServiceDiscovery {
         Map<String, ServiceDiscovery.Cluster> result = new HashMap<>();
 
         Properties p = new Properties();
-        try {
-            p.load(new FileInputStream(discoveryConfig.getAddress()));
+        try (InputStream inputStream = Files.newInputStream(Paths.get(discoveryConfig.getAddress()))){
+            p.load(inputStream);
 
             Map<String, Map<String, Map<String, String>>> clusterProperties = new HashMap<>();
             Map<String, Map<String, List<String>>> clusterURLs = new HashMap<>();
@@ -68,7 +70,7 @@ class PropertiesFileServiceDiscovery implements ServiceDiscovery {
                     }
                     String serviceName = parts[1];
                     String property    = parts[2];
-                    if (property.equals("url")) {
+                    if ("url".equals(property)) {
                         String serviceURL = p.getProperty(propertyKey);
                         Map<String, List<String>> serviceURLs = clusterURLs.get(clusterName);
                         if (!serviceURLs.containsKey(serviceName)) {
@@ -80,7 +82,7 @@ class PropertiesFileServiceDiscovery implements ServiceDiscovery {
                         for (String url : svcURLs) {
                           serviceURLs.get(serviceName).add(url);
                         }
-                    } else if (!property.equalsIgnoreCase("name")) { // ZooKeeper config properties
+                    } else if (!"name".equalsIgnoreCase(property)) { // ZooKeeper config properties
                         Map<String, Map<String, String>> props = clusterProperties.get(clusterName);
                         if (!props.containsKey(serviceName)) {
                             props.put(serviceName, new HashMap<>());
index 50d2e52..27217ae 100644 (file)
@@ -23,11 +23,12 @@ import org.junit.BeforeClass;
 import org.junit.Test;
 
 import java.io.File;
-import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.io.Writer;
 import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
 import java.util.List;
 import java.util.Map;
 
@@ -41,7 +42,7 @@ public class ProviderConfigurationParserTest {
   private static File tmpDir;
 
   @BeforeClass
-  public static void createTempDir() {
+  public static void setUpBeforeClass() {
     try {
       tmpDir = TestUtils.createTempDir(ProviderConfigurationParser.class.getName());
     } catch (IOException e) {
@@ -50,7 +51,7 @@ public class ProviderConfigurationParserTest {
   }
 
   @AfterClass
-  public static void removeTempDir() {
+  public static void tearDownAfterClass() {
     if (tmpDir != null) {
       FileUtils.deleteQuietly(tmpDir);
     }
@@ -291,7 +292,6 @@ public class ProviderConfigurationParserTest {
     }
   }
 
-
   /**
    * Parse the specified configuration, and return the parse result for validation by the caller.
    *
@@ -305,10 +305,11 @@ public class ProviderConfigurationParserTest {
 
     File testConfig = new File(tmpDir, fileName);
 
-    Writer fw = new OutputStreamWriter(new FileOutputStream(testConfig), StandardCharsets.UTF_8);
-    fw.write(config);
-    fw.flush();
-    fw.close();
+    try (OutputStream outputStream = Files.newOutputStream(testConfig.toPath());
+         Writer fw = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
+      fw.write(config);
+      fw.flush();
+    }
 
     try {
       pc = ProviderConfigurationParser.parse(testConfig.getAbsolutePath());
@@ -318,6 +319,4 @@ public class ProviderConfigurationParserTest {
 
     return pc;
   }
-
-
 }
index 5504d1c..52cc6ee 100644 (file)
@@ -19,10 +19,13 @@ package org.apache.knox.gateway.topology.simple;
 import org.junit.Test;
 
 import java.io.File;
-import java.io.FileOutputStream;
+import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.io.Writer;
 import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
@@ -34,7 +37,6 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
-
 public class SimpleDescriptorFactoryTest {
 
     private enum FileType {
@@ -541,9 +543,9 @@ public class SimpleDescriptorFactoryTest {
                            Map<String, Map<String, String>> serviceParams,
                            Map<String, List<String>>        apps,
                            Map<String, Map<String, String>> appParams) throws Exception {
-        File f = new File(path);
-
-        Writer fw = new OutputStreamWriter(new FileOutputStream(f), StandardCharsets.UTF_8);
+      Path pathObject = Paths.get(path);
+      try (OutputStream outputStream = Files.newOutputStream(pathObject);
+           Writer fw = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
         fw.write("{" + "\n");
         fw.write("\"discovery-type\":\"" + discoveryType + "\",\n");
         fw.write("\"discovery-address\":\"" + discoveryAddress + "\",\n");
@@ -552,22 +554,21 @@ public class SimpleDescriptorFactoryTest {
         fw.write("\"cluster\":\"" + clusterName + "\"");
 
         if (services != null && !services.isEmpty()) {
-            fw.write(",\n\"services\":[\n");
-            writeServiceOrApplicationJSON(fw, services, serviceParams, serviceVersions);
-            fw.write("]\n");
+          fw.write(",\n\"services\":[\n");
+          writeServiceOrApplicationJSON(fw, services, serviceParams, serviceVersions);
+          fw.write("]\n");
         }
 
         if (apps != null && !apps.isEmpty()) {
-            fw.write(",\n\"applications\":[\n");
-            writeServiceOrApplicationJSON(fw, apps, appParams, null);
-            fw.write("]\n");
+          fw.write(",\n\"applications\":[\n");
+          writeServiceOrApplicationJSON(fw, apps, appParams, null);
+          fw.write("]\n");
         }
 
         fw.write("}\n");
         fw.flush();
-        fw.close();
-
-        return f;
+      }
+      return pathObject.toFile();
     }
 
     private void writeServiceOrApplicationJSON(Writer fw,
@@ -637,30 +638,29 @@ public class SimpleDescriptorFactoryTest {
                            Map<String, List<String>>        apps,
                            Map<String, Map<String, String>> appParams) throws Exception {
 
-        File f = new File(path);
-
-        Writer fw = new OutputStreamWriter(new FileOutputStream(f), StandardCharsets.UTF_8);
+      Path pathObject = Paths.get(path);
+      try (OutputStream outputStream = Files.newOutputStream(pathObject);
+           Writer fw = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
         fw.write("---" + "\n");
         fw.write("discovery-type: " + discoveryType + "\n");
         fw.write("discovery-address: " + discoveryAddress + "\n");
         fw.write("discovery-user: " + discoveryUser + "\n");
         fw.write("provider-config-ref: " + providerConfig + "\n");
-        fw.write("cluster: " + clusterName+ "\n");
+        fw.write("cluster: " + clusterName + "\n");
 
         if (services != null && !services.isEmpty()) {
-            fw.write("services:\n");
-            writeServiceOrApplicationYAML(fw, services, serviceParams, serviceVersions);
+          fw.write("services:\n");
+          writeServiceOrApplicationYAML(fw, services, serviceParams, serviceVersions);
         }
 
         if (apps != null && !apps.isEmpty()) {
-            fw.write("applications:\n");
-            writeServiceOrApplicationYAML(fw, apps, appParams, null);
+          fw.write("applications:\n");
+          writeServiceOrApplicationYAML(fw, apps, appParams, null);
         }
 
         fw.flush();
-        fw.close();
-
-        return f;
+      }
+      return pathObject.toFile();
     }
 
     private void writeServiceOrApplicationYAML(Writer                           fw,
index 89fd866..db422e2 100644 (file)
@@ -38,10 +38,11 @@ import javax.xml.xpath.XPathFactory;
 import java.io.ByteArrayInputStream;
 import java.io.File;
 import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.io.StringWriter;
 import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
@@ -155,8 +156,8 @@ public class SimpleDescriptorHandlerTest {
         DISCOVERY_PROPERTIES.setProperty(clusterName + ".HIVE.url", "http://hivehostname:10001/clipath");
         DISCOVERY_PROPERTIES.setProperty(clusterName + ".RESOURCEMANAGER.url", "http://remanhost:8088/ws");
 
-        try {
-            DISCOVERY_PROPERTIES.store(new FileOutputStream(discoveryConfig), null);
+        try (OutputStream outputStream = Files.newOutputStream(discoveryConfig.toPath())){
+            DISCOVERY_PROPERTIES.store(outputStream, null);
         } catch (FileNotFoundException e) {
             fail(e.getMessage());
         }
@@ -338,9 +339,11 @@ public class SimpleDescriptorHandlerTest {
         serviceDiscoverySourceProps.setProperty(CLUSTER_NAME + ".HIVE.url",            "{SCHEME}://localhost:10000/");
         serviceDiscoverySourceProps.setProperty(CLUSTER_NAME + ".RESOURCEMANAGER.url", DEFAULT_VALID_SERVICE_URL);
         serviceDiscoverySourceProps.setProperty(CLUSTER_NAME + ".AMBARIUI.url",        DEFAULT_VALID_SERVICE_URL);
+
         File serviceDiscoverySource = File.createTempFile("service-discovery", ".properties");
-        serviceDiscoverySourceProps.store(new FileOutputStream(serviceDiscoverySource),
-                                          "Test Service Discovery Source");
+        try (OutputStream outputStream = Files.newOutputStream(serviceDiscoverySource.toPath())) {
+          serviceDiscoverySourceProps.store(outputStream, "Test Service Discovery Source");
+        }
 
         // Prepare a mock SimpleDescriptor
         final String type = "PROPERTIES_FILE";
@@ -457,13 +460,11 @@ public class SimpleDescriptorHandlerTest {
         }
     }
 
-
     /*
      * KNOX-1216
      */
-    @Test
+    @Test (expected = IllegalArgumentException.class)
     public void testMissingProviderConfigReference() throws Exception {
-
         // Prepare a mock SimpleDescriptor
         final Map<String, List<String>> serviceURLs = new HashMap<>();
         serviceURLs.put("NAMENODE", null);
@@ -499,20 +500,9 @@ public class SimpleDescriptorHandlerTest {
         EasyMock.expect(testDescriptor.getServices()).andReturn(serviceMocks).anyTimes();
         EasyMock.replay(testDescriptor);
 
-        try {
-            // Invoke the simple descriptor handler
-            SimpleDescriptorHandler.handle(gc, testDescriptor, destDir, destDir);
-            fail("Expected an IllegalArgumentException because the provider configuration reference is missing.");
-        } catch (IllegalArgumentException e) {
-            // Expected
-        } catch (Exception e) {
-            e.printStackTrace();
-            fail("Unexpected exception for missing provider configuration reference: " +
-                 e.getClass().getName() + " : " + e.getMessage());
-        }
+        SimpleDescriptorHandler.handle(gc, testDescriptor, destDir, destDir);
     }
 
-
     /*
      * KNOX-1153
      *
@@ -557,8 +547,8 @@ public class SimpleDescriptorHandlerTest {
         DISCOVERY_PROPERTIES.setProperty(clusterName + ".ATLAS-API.ensemble", ATLAS_HA_ENSEMBLE);
         DISCOVERY_PROPERTIES.setProperty(clusterName + ".ATLAS-API.url", "http://atlasapihost:2222");
 
-        try {
-            DISCOVERY_PROPERTIES.store(new FileOutputStream(discoveryConfig), null);
+        try (OutputStream outputStream = Files.newOutputStream(discoveryConfig.toPath())){
+            DISCOVERY_PROPERTIES.store(outputStream, null);
         } catch (FileNotFoundException e) {
             fail(e.getMessage());
         }
index 9e7921f..f94e979 100644 (file)
@@ -33,11 +33,12 @@ import org.junit.Test;
 
 import java.io.ByteArrayOutputStream;
 import java.io.File;
-import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.io.PrintStream;
 import java.net.URL;
 import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
 import java.util.UUID;
 
 import static org.hamcrest.CoreMatchers.containsString;
@@ -60,7 +61,7 @@ public class KnoxCLITest {
   private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
 
   @Before
-  public void setup() throws Exception {
+  public void setUp() throws Exception {
     System.setOut(new PrintStream(outContent, false, StandardCharsets.UTF_8.name()));
     System.setErr(new PrintStream(errContent, false, StandardCharsets.UTF_8.name()));
   }
@@ -965,9 +966,9 @@ public class KnoxCLITest {
     config.setConfDir( new File(topoURL.getFile()).getParentFile().getParent() );
 
     File tempFile = new File( config.getGatewayTopologyDir(), name + ".xml." + UUID.randomUUID() );
-    FileOutputStream stream = new FileOutputStream( tempFile );
-    xml.toStream( stream );
-    stream.close();
+    try(OutputStream stream = Files.newOutputStream(tempFile.toPath())) {
+      xml.toStream(stream);
+    }
     File descriptor = new File( config.getGatewayTopologyDir(), name + ".xml" );
     tempFile.renameTo( descriptor );
     return descriptor;
@@ -1015,7 +1016,9 @@ public class KnoxCLITest {
   public void testValidateTopologyOutput() throws Exception {
 
     File bad = writeTestTopology( "test-cluster-bad", createBadTopology() );
+    assertNotNull(bad);
     File good = writeTestTopology( "test-cluster-good", createGoodTopology() );
+    assertNotNull(good);
 
     GatewayConfigMock config = new GatewayConfigMock();
     URL topoURL = ClassLoader.getSystemResource("conf-demo/conf/topologies/admin.xml");
diff --git a/gateway-server/src/test/java/org/apache/knox/gateway/websockets/BadSocket.java b/gateway-server/src/test/java/org/apache/knox/gateway/websockets/BadSocket.java
new file mode 100644 (file)
index 0000000..0744f8c
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.knox.gateway.websockets;
+
+import org.eclipse.jetty.io.RuntimeIOException;
+import org.eclipse.jetty.util.BufferUtil;
+import org.eclipse.jetty.websocket.api.BatchMode;
+import org.eclipse.jetty.websocket.api.RemoteEndpoint;
+import org.eclipse.jetty.websocket.api.Session;
+import org.eclipse.jetty.websocket.api.WebSocketAdapter;
+
+import java.io.IOException;
+
+/**
+ * Simulate a bad socket.
+ *
+ * @since 0.10
+ */
+class BadSocket extends WebSocketAdapter {
+  @Override
+  public void onWebSocketConnect(final Session session) {
+  }
+
+  @Override
+  public void onWebSocketBinary(byte[] payload, int offset, int len) {
+    if (isNotConnected()) {
+      return;
+    }
+
+    try {
+      RemoteEndpoint remote = getRemote();
+      remote.sendBytes(BufferUtil.toBuffer(payload, offset, len), null);
+      if (remote.getBatchMode() == BatchMode.ON) {
+        remote.flush();
+      }
+    } catch (IOException x) {
+      throw new RuntimeIOException(x);
+    }
+  }
+
+  @Override
+  public void onWebSocketError(Throwable cause) {
+    throw new RuntimeException(cause);
+  }
+
+  @Override
+  public void onWebSocketText(String message) {
+    if (isNotConnected()) {
+      return;
+    }
+    // Throw an exception on purpose
+    throw new RuntimeException("Simulating bad connection ...");
+  }
+}
index e61ddde..a3c5cf8 100644 (file)
@@ -45,10 +45,11 @@ import javax.websocket.CloseReason;
 import javax.websocket.ContainerProvider;
 import javax.websocket.WebSocketContainer;
 import java.io.File;
-import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.net.URI;
 import java.net.URL;
+import java.nio.file.Files;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
@@ -95,12 +96,12 @@ public class BadUrlTest {
   }
 
   @BeforeClass
-  public static void startServers() throws Exception {
+  public static void setUpBeforeClass() throws Exception {
     startGatewayServer();
   }
 
   @AfterClass
-  public static void stopServers() {
+  public static void tearDownAfterClass() {
     try {
       gatewayServer.stop();
     } catch (final Exception e) {
@@ -173,9 +174,9 @@ public class BadUrlTest {
     URL serviceUrl = ClassLoader.getSystemResource("websocket-services");
 
     final File descriptor = new File(topoDir, "websocket.xml");
-    final FileOutputStream stream = new FileOutputStream(descriptor);
-    createKnoxTopology(backend).toStream(stream);
-    stream.close();
+    try(OutputStream stream = Files.newOutputStream(descriptor.toPath())) {
+      createKnoxTopology(backend).toStream(stream);
+    }
 
     final TestTopologyListener topoListener = new TestTopologyListener();
 
@@ -271,8 +272,7 @@ public class BadUrlTest {
   }
 
   private static class TestTopologyListener implements TopologyListener {
-
-    public ArrayList<List<TopologyEvent>> events = new ArrayList<>();
+    public List<List<TopologyEvent>> events = new ArrayList<>();
 
     @Override
     public void handleTopologyEvent(List<TopologyEvent> events) {
diff --git a/gateway-server/src/test/java/org/apache/knox/gateway/websockets/BigEchoSocketHandler.java b/gateway-server/src/test/java/org/apache/knox/gateway/websockets/BigEchoSocketHandler.java
new file mode 100644 (file)
index 0000000..080a5a1
--- /dev/null
@@ -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.websockets;
+
+import org.eclipse.jetty.websocket.api.WebSocketAdapter;
+import org.eclipse.jetty.websocket.server.WebSocketHandler;
+import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest;
+import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse;
+import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
+import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
+
+/**
+ * A Mock websocket handler that just Echos messages
+ */
+class BigEchoSocketHandler extends WebSocketHandler implements WebSocketCreator {
+  private final WebSocketAdapter socket;
+
+  BigEchoSocketHandler(final WebSocketAdapter socket) {
+    this.socket = socket;
+  }
+
+  @Override
+  public void configure(WebSocketServletFactory factory) {
+    factory.getPolicy().setMaxTextMessageSize(10);
+    factory.getPolicy().setMaxBinaryMessageSize(10);
+    factory.setCreator(this);
+  }
+
+  @Override
+  public Object createWebSocket(ServletUpgradeRequest req,
+                                ServletUpgradeResponse resp) {
+    return socket;
+  }
+}
index 88a3275..80e3509 100644 (file)
  */
 package org.apache.knox.gateway.websockets;
 
-import org.eclipse.jetty.io.RuntimeIOException;
 import org.eclipse.jetty.server.Server;
 import org.eclipse.jetty.server.ServerConnector;
 import org.eclipse.jetty.server.handler.ContextHandler;
-import org.eclipse.jetty.util.BufferUtil;
-import org.eclipse.jetty.websocket.api.BatchMode;
-import org.eclipse.jetty.websocket.api.RemoteEndpoint;
-import org.eclipse.jetty.websocket.api.Session;
-import org.eclipse.jetty.websocket.api.WebSocketAdapter;
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -46,7 +40,6 @@ import java.util.concurrent.TimeUnit;
  *
  */
 public class ConnectionDroppedTest {
-
   private static Server backend;
   private static ServerConnector connector;
   private static URI serverUri;
@@ -61,13 +54,13 @@ public class ConnectionDroppedTest {
   }
 
   @BeforeClass
-  public static void startServer() throws Exception {
+  public static void setUpBeforeClass() throws Exception {
     startBackend();
     startProxy();
   }
 
   @AfterClass
-  public static void stopServer() throws Exception {
+  public static void tearDownAfterClass() throws Exception {
     /* ORDER MATTERS ! */
     proxy.stop();
     backend.stop();
@@ -116,7 +109,6 @@ public class ConnectionDroppedTest {
     }
     int port = connector.getLocalPort();
     serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
-
   }
 
   private static void startProxy() throws Exception {
@@ -142,51 +134,5 @@ public class ConnectionDroppedTest {
     }
     int port = proxyConnector.getLocalPort();
     proxyUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
-
   }
-
-}
-
-/**
- * Simulate a bad socket.
- *
- * @since 0.10
- */
-class BadSocket extends WebSocketAdapter {
-
-  private Session session;
-
-  @Override
-  public void onWebSocketConnect(final Session session) {
-    this.session = session;
-  }
-
-  @Override
-  public void onWebSocketBinary(byte[] payload, int offset, int len) {
-    if (isNotConnected())
-      return;
-
-    try {
-      RemoteEndpoint remote = getRemote();
-      remote.sendBytes(BufferUtil.toBuffer(payload, offset, len), null);
-      if (remote.getBatchMode() == BatchMode.ON)
-        remote.flush();
-    } catch (IOException x) {
-      throw new RuntimeIOException(x);
-    }
-  }
-
-  @Override
-  public void onWebSocketError(Throwable cause) {
-    throw new RuntimeException(cause);
-  }
-
-  @Override
-  public void onWebSocketText(String message) {
-    if (isNotConnected())
-      return;
-    // Throw an exception on purpose
-    throw new RuntimeException("Simulating bad connection ...");
-  }
-
 }
index 4d55b60..3e025e7 100644 (file)
@@ -32,14 +32,16 @@ public class EchoSocket extends WebSocketAdapter {
 
   @Override
   public void onWebSocketBinary(byte[] payload, int offset, int len) {
-    if (isNotConnected())
+    if (isNotConnected()) {
       return;
+    }
 
     try {
       RemoteEndpoint remote = getRemote();
       remote.sendBytes(BufferUtil.toBuffer(payload, offset, len), null);
-      if (remote.getBatchMode() == BatchMode.ON)
+      if (remote.getBatchMode() == BatchMode.ON) {
         remote.flush();
+      }
     } catch (IOException x) {
       throw new RuntimeIOException(x);
     }
@@ -52,14 +54,16 @@ public class EchoSocket extends WebSocketAdapter {
 
   @Override
   public void onWebSocketText(String message) {
-    if (isNotConnected())
+    if (isNotConnected()) {
       return;
+    }
 
     try {
       RemoteEndpoint remote = getRemote();
       remote.sendString(message, null);
-      if (remote.getBatchMode() == BatchMode.ON)
+      if (remote.getBatchMode() == BatchMode.ON) {
         remote.flush();
+      }
     } catch (IOException x) {
       throw new RuntimeIOException(x);
     }
index 9786dc1..a265f65 100644 (file)
@@ -20,12 +20,6 @@ package org.apache.knox.gateway.websockets;
 import org.eclipse.jetty.server.Server;
 import org.eclipse.jetty.server.ServerConnector;
 import org.eclipse.jetty.server.handler.ContextHandler;
-import org.eclipse.jetty.websocket.api.WebSocketAdapter;
-import org.eclipse.jetty.websocket.server.WebSocketHandler;
-import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest;
-import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse;
-import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
-import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
 import org.hamcrest.CoreMatchers;
 import org.junit.AfterClass;
 import org.junit.Assert;
@@ -41,11 +35,9 @@ import java.util.concurrent.Executors;
 import java.util.concurrent.TimeUnit;
 
 /**
- * Dummy Test for max message size.
- *
+ * Test for max message size.
  */
 public class MessageFailureTest {
-
   private static Server backend;
   private static ServerConnector connector;
   private static URI serverUri;
@@ -60,13 +52,13 @@ public class MessageFailureTest {
   }
 
   @BeforeClass
-  public static void startServer() throws Exception {
+  public static void setUpBeforeClass() throws Exception {
     startBackend();
     startProxy();
   }
 
   @AfterClass
-  public static  void stopServer() throws Exception {
+  public static void tearDownAfterClass() throws Exception {
     /* ORDER MATTERS ! */
     proxy.stop();
     backend.stop();
@@ -109,7 +101,6 @@ public class MessageFailureTest {
     client.messageQueue.awaitMessages(1, 1000, TimeUnit.MILLISECONDS);
 
     Assert.assertThat(client.messageQueue.get(0), CoreMatchers.is("Echo"));
-
   }
 
   private static void startBackend() throws Exception {
@@ -135,7 +126,6 @@ public class MessageFailureTest {
     }
     int port = connector.getLocalPort();
     serverUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
-
   }
 
   private static void startProxy() throws Exception {
@@ -163,28 +153,3 @@ public class MessageFailureTest {
     proxyUri = new URI(String.format(Locale.ROOT, "ws://%s:%d/", host, port));
   }
 }
-
-/**
- * A Mock websocket handler that just Echos messages
- */
-class BigEchoSocketHandler extends WebSocketHandler implements WebSocketCreator {
-  private final WebSocketAdapter socket;
-
-  BigEchoSocketHandler(final WebSocketAdapter socket) {
-    this.socket = socket;
-  }
-
-  @Override
-  public void configure(WebSocketServletFactory factory) {
-    factory.getPolicy().setMaxTextMessageSize(10);
-    factory.getPolicy().setMaxBinaryMessageSize(10);
-    factory.setCreator(this);
-  }
-
-  @Override
-  public Object createWebSocket(ServletUpgradeRequest req,
-      ServletUpgradeResponse resp) {
-    return socket;
-  }
-
-}
index c445254..e812c13 100644 (file)
@@ -45,15 +45,11 @@ import static org.hamcrest.Matchers.instanceOf;
  * @since 0.14.0
  */
 public class ProxyInboundClientTest {
-
   private static Server server;
   private static URI serverUri;
-  private static Handler handler;
-
-  String recievedMessage;
-
-  byte[] recievedBinaryMessage;
 
+  private String receivedMessage;
+  private byte[] receivedBinaryMessage;
 
   /* create an instance */
   public ProxyInboundClientTest() {
@@ -61,13 +57,12 @@ public class ProxyInboundClientTest {
   }
 
   @BeforeClass
-  public static void startWSServer() throws Exception
-  {
+  public static void setUpBeforeClass() throws Exception {
     server = new Server();
     ServerConnector connector = new ServerConnector(server);
     server.addConnector(connector);
 
-    handler = new WebsocketEchoHandler();
+    Handler handler = new WebsocketEchoHandler();
 
     ContextHandler context = new ContextHandler();
     context.setContextPath("/");
@@ -77,8 +72,7 @@ public class ProxyInboundClientTest {
     server.start();
 
     String host = connector.getHost();
-    if (host == null)
-    {
+    if (host == null) {
       host = "localhost";
     }
     int port = connector.getLocalPort();
@@ -86,14 +80,10 @@ public class ProxyInboundClientTest {
   }
 
   @AfterClass
-  public static void stopServer()
-  {
-    try
-    {
+  public static void tearDownAfterClass() {
+    try {
       server.stop();
-    }
-    catch (Exception e)
-    {
+    } catch (Exception e) {
       e.printStackTrace(System.err);
     }
   }
@@ -101,23 +91,18 @@ public class ProxyInboundClientTest {
   //@Test(timeout = 3000)
   @Test
   public void testClientInstance() throws IOException, DeploymentException {
-
     final String textMessage = "Echo";
-    final ByteBuffer binarymessage = ByteBuffer.wrap(textMessage.getBytes(StandardCharsets.UTF_8));
 
     final AtomicBoolean isTestComplete = new AtomicBoolean(false);
 
     final WebSocketContainer container = ContainerProvider.getWebSocketContainer();
     final ProxyInboundClient client = new ProxyInboundClient( new MessageEventCallback() {
-
       @Override
       public void doCallback(String message) {
-
       }
 
       @Override
       public void onConnectionOpen(Object session) {
-
       }
 
       @Override
@@ -132,16 +117,14 @@ public class ProxyInboundClientTest {
 
       @Override
       public void onMessageText(String message, Object session) {
-        recievedMessage = message;
+        receivedMessage = message;
         isTestComplete.set(true);
       }
 
       @Override
-      public void onMessageBinary(byte[] message, boolean last,
-          Object session) {
-
+      public void onMessageBinary(byte[] message, boolean last, Object session) {
       }
-    } );
+    });
 
     Assert.assertThat(client, instanceOf(javax.websocket.Endpoint.class));
 
@@ -149,16 +132,15 @@ public class ProxyInboundClientTest {
 
     session.getBasicRemote().sendText(textMessage);
 
-    while(!isTestComplete.get()) {
+    while(!isTestComplete.get()) { // NOPMD
       /* just wait for the test to finish */
     }
 
-    Assert.assertEquals("The received text message is not the same as the sent", textMessage, recievedMessage);
+    Assert.assertEquals("The received text message is not the same as the sent", textMessage, receivedMessage);
   }
 
   @Test(timeout = 3000)
   public void testBinarymessage() throws IOException, DeploymentException {
-
     final String textMessage = "Echo";
     final ByteBuffer binarymessage = ByteBuffer.wrap(textMessage.getBytes(StandardCharsets.UTF_8));
 
@@ -166,15 +148,12 @@ public class ProxyInboundClientTest {
 
     final WebSocketContainer container = ContainerProvider.getWebSocketContainer();
     final ProxyInboundClient client = new ProxyInboundClient( new MessageEventCallback() {
-
       @Override
       public void doCallback(String message) {
-
       }
 
       @Override
       public void onConnectionOpen(Object session) {
-
       }
 
       @Override
@@ -189,17 +168,16 @@ public class ProxyInboundClientTest {
 
       @Override
       public void onMessageText(String message, Object session) {
-        recievedMessage = message;
+        receivedMessage = message;
         isTestComplete.set(true);
       }
 
       @Override
-      public void onMessageBinary(byte[] message, boolean last,
-          Object session) {
-        recievedBinaryMessage = message;
+      public void onMessageBinary(byte[] message, boolean last, Object session) {
+        receivedBinaryMessage = message;
         isTestComplete.set(true);
       }
-    } );
+    });
 
     Assert.assertThat(client, instanceOf(javax.websocket.Endpoint.class));
 
@@ -207,31 +185,27 @@ public class ProxyInboundClientTest {
 
     session.getBasicRemote().sendBinary(binarymessage);
 
-    while(!isTestComplete.get()) {
+    while(!isTestComplete.get()) { // NOPMD
       /* just wait for the test to finish */
     }
 
-    Assert.assertEquals("Binary message does not match", textMessage, new String(recievedBinaryMessage, StandardCharsets.UTF_8));
+    Assert.assertEquals("Binary message does not match", textMessage, new String(receivedBinaryMessage, StandardCharsets.UTF_8));
   }
 
   @Test(timeout = 3000)
   public void testTextMaxBufferLimit() throws IOException, DeploymentException {
-
     final String longMessage = RandomStringUtils.random(100000);
 
     final AtomicBoolean isTestComplete = new AtomicBoolean(false);
 
     final WebSocketContainer container = ContainerProvider.getWebSocketContainer();
     final ProxyInboundClient client = new ProxyInboundClient( new MessageEventCallback() {
-
       @Override
       public void doCallback(String message) {
-
       }
 
       @Override
       public void onConnectionOpen(Object session) {
-
       }
 
       @Override
@@ -246,16 +220,14 @@ public class ProxyInboundClientTest {
 
       @Override
       public void onMessageText(String message, Object session) {
-        recievedMessage = message;
+        receivedMessage = message;
         isTestComplete.set(true);
       }
 
       @Override
-      public void onMessageBinary(byte[] message, boolean last,
-          Object session) {
-
+      public void onMessageBinary(byte[] message, boolean last, Object session) {
       }
-    } );
+    });
 
     Assert.assertThat(client, instanceOf(javax.websocket.Endpoint.class));
 
@@ -263,14 +235,10 @@ public class ProxyInboundClientTest {
 
     session.getBasicRemote().sendText(longMessage);
 
-    while(!isTestComplete.get()) {
+    while(!isTestComplete.get()) { // NOPMD
       /* just wait for the test to finish */
     }
 
-    Assert.assertEquals(longMessage, recievedMessage);
-
+    Assert.assertEquals(longMessage, receivedMessage);
   }
-
-
-
 }
index 6cb9cd1..772be94 100644 (file)
@@ -19,6 +19,7 @@ package org.apache.knox.gateway.websockets;
 
 import java.io.IOException;
 import java.util.LinkedList;
+import java.util.List;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
@@ -43,7 +44,7 @@ public class WebsocketClient {
   private Session session;
   public CloseReason close;
   public MessageQueue messageQueue = new MessageQueue();
-  public LinkedList<Throwable> errors = new LinkedList<>();
+  public List<Throwable> errors = new LinkedList<>();
   public CountDownLatch closeLatch = new CountDownLatch(1);
 
   public boolean onError;
index b8bfd2e..4d1f38f 100644 (file)
@@ -43,10 +43,11 @@ import javax.websocket.ContainerProvider;
 import javax.websocket.Session;
 import javax.websocket.WebSocketContainer;
 import java.io.File;
-import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.net.URI;
 import java.net.URL;
+import java.nio.file.Files;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
@@ -113,13 +114,13 @@ public class WebsocketEchoTest {
   }
 
   @BeforeClass
-  public static void startServers() throws Exception {
+  public static void setUpBeforeClass() throws Exception {
     startWebsocketServer();
     startGatewayServer();
   }
 
   @AfterClass
-  public static void stopServers() {
+  public static void tearDownAfterClass() {
     try {
       gatewayServer.stop();
       backendServer.stop();
@@ -258,9 +259,9 @@ public class WebsocketEchoTest {
     URL serviceUrl = ClassLoader.getSystemResource("websocket-services");
 
     final File descriptor = new File(topoDir, "websocket.xml");
-    final FileOutputStream stream = new FileOutputStream(descriptor);
-    createKnoxTopology(backend).toStream(stream);
-    stream.close();
+    try(OutputStream stream = Files.newOutputStream(descriptor.toPath())) {
+      createKnoxTopology(backend).toStream(stream);
+    }
 
     final TestTopologyListener topoListener = new TestTopologyListener();
 
@@ -337,7 +338,6 @@ public class WebsocketEchoTest {
         .getService(GatewayServices.TOPOLOGY_SERVICE);
     monitor.addTopologyChangeListener(topoListener);
     monitor.reloadTopologies();
-
   }
 
   private static File createDir() throws IOException {
@@ -353,8 +353,7 @@ public class WebsocketEchoTest {
   }
 
   private static class TestTopologyListener implements TopologyListener {
-
-    public ArrayList<List<TopologyEvent>> events = new ArrayList<>();
+    public List<List<TopologyEvent>> events = new ArrayList<>();
 
     @Override
     public void handleTopologyEvent(List<TopologyEvent> events) {
index eb635ef..1335696 100644 (file)
@@ -47,12 +47,13 @@ import javax.websocket.MessageHandler;
 import javax.websocket.Session;
 import javax.websocket.WebSocketContainer;
 import java.io.File;
-import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.lang.management.ManagementFactory;
 import java.lang.management.MemoryMXBean;
 import java.net.URI;
 import java.net.URL;
+import java.nio.file.Files;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
@@ -138,7 +139,7 @@ public class WebsocketMultipleConnectionTest {
 
     MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
 
-    System.gc();
+    System.gc(); // NOPMD
     final long heapt1 = memoryMXBean.getHeapMemoryUsage().getUsed();
     final long nonHeapt1 = memoryMXBean.getNonHeapMemoryUsage().getUsed();
 
@@ -165,7 +166,7 @@ public class WebsocketMultipleConnectionTest {
 
     latch.await(5 * MAX_CONNECTIONS, TimeUnit.MILLISECONDS);
 
-    System.gc();
+    System.gc(); // NOPMD
 
     final long heapUsed = memoryMXBean.getHeapMemoryUsage().getUsed() - heapt1;
     final long nonHeapUsed = memoryMXBean.getNonHeapMemoryUsage().getUsed()
@@ -256,9 +257,9 @@ public class WebsocketMultipleConnectionTest {
     URL serviceUrl = ClassLoader.getSystemResource("websocket-services");
 
     final File descriptor = new File(topoDir, "websocket.xml");
-    final FileOutputStream stream = new FileOutputStream(descriptor);
-    createKnoxTopology(backend).toStream(stream);
-    stream.close();
+    try(OutputStream stream = Files.newOutputStream(descriptor.toPath())) {
+      createKnoxTopology(backend).toStream(stream);
+    }
 
     final TestTopologyListener topoListener = new TestTopologyListener();
 
@@ -350,8 +351,7 @@ public class WebsocketMultipleConnectionTest {
   }
 
   private static class TestTopologyListener implements TopologyListener {
-
-    public ArrayList<List<TopologyEvent>> events = new ArrayList<>();
+    public List<List<TopologyEvent>> events = new ArrayList<>();
 
     @Override
     public void handleTopologyEvent(List<TopologyEvent> events) {
index 2f3c38e..18bde96 100644 (file)
@@ -79,7 +79,7 @@ public class WebSSOResourceTest {
   private static RSAPrivateKey gatewayPrivateKey;
 
   @BeforeClass
-  public static void setup() throws Exception {
+  public static void setUpBeforeClass() throws Exception {
     KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
     kpg.initialize(2048);
     KeyPair keyPair = kpg.generateKeyPair();
index 44ab79f..fa3c623 100644 (file)
@@ -62,7 +62,7 @@ public class TokenServiceResourceTest {
   private static RSAPrivateKey privateKey;
 
   @BeforeClass
-  public static void setup() throws Exception {
+  public static void setUpBeforeClass() throws Exception {
     KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
     kpg.initialize(2048);
     KeyPair KPair = kpg.generateKeyPair();
@@ -616,9 +616,9 @@ public class TokenServiceResourceTest {
       value = value.substring(1);
     }
     if (value.contains("\"")) {
-      return value.substring(0, value.indexOf("\""));
+      return value.substring(0, value.indexOf('\"'));
     } else if (value.contains(",")) {
-      return value.substring(0, value.indexOf(","));
+      return value.substring(0, value.indexOf(','));
     } else {
       return value.substring(0, value.length() - 1);
     }
index 363b12a..9e88147 100644 (file)
@@ -49,7 +49,6 @@ public class DefaultRemoteConfigurationRegistriesTest {
         doTestPropertiesRemoteConfigurationRegistries(testProperties);
     }
 
-
     /*
      * Test a single registry configuration with kerberos auth configuration.
      */
@@ -144,9 +143,9 @@ public class DefaultRemoteConfigurationRegistriesTest {
             Enumeration names = props.propertyNames();
             while (names.hasMoreElements()) {
                 String propertyName = (String) names.nextElement();
-                propertyValueString.append(propertyName).append("=").append(props.get(propertyName));
+                propertyValueString.append(propertyName).append('=').append(props.get(propertyName));
                 if (names.hasMoreElements()) {
-                    propertyValueString.append(";");
+                    propertyValueString.append(';');
                 }
             }
             EasyMock.expect(gc.getRemoteRegistryConfiguration(registryName))
@@ -181,5 +180,4 @@ public class DefaultRemoteConfigurationRegistriesTest {
         assertEquals(Boolean.valueOf((String)expected.get(GatewayConfig.REMOTE_CONFIG_REGISTRY_USE_KEYTAB)), registryConfig.isUseKeyTab());
         assertEquals(Boolean.valueOf((String)expected.get(GatewayConfig.REMOTE_CONFIG_REGISTRY_USE_TICKET_CACHE)), registryConfig.isUseTicketCache());
     }
-
 }
index 4caef66..80d22bf 100644 (file)
@@ -34,8 +34,8 @@ public class RemoteRegistryConfigTestUtils {
     public static final String PROPERTY_USE_TICKET_CACHE = "useTicketCache";
 
     public static String createRemoteConfigRegistriesXML(Collection<Map<String, String>> configProperties) {
-        StringBuilder result = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
-                                                     "<remote-configuration-registries>\n");
+        StringBuilder result = new StringBuilder(128);
+        result.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<remote-configuration-registries>\n");
 
         for (Map<String, String> props : configProperties) {
             String authType = props.get(PROPERTY_AUTH_TYPE);
index a335f15..72e2fa0 100644 (file)
@@ -94,7 +94,6 @@ public class RemoteConfigurationRegistryClientServiceTest {
         final String REGISTRY_CLIENT_NAME_2 = "zkclient2";
         final String PRINCIPAL = null;
         final String PWD = null;
-        final String CRED_ALIAS = null;
 
         // Configure and start a secure ZK cluster
         try (TestingCluster zkCluster = setupAndStartSecureTestZooKeeper(PRINCIPAL, PWD)) {
index 8ce2eca..752ed34 100644 (file)
@@ -154,6 +154,7 @@ public class RemoteConfigurationRegistryJAASConfigTest {
         try {
             RemoteConfigurationRegistryJAASConfig jaasConfig =
                                             RemoteConfigurationRegistryJAASConfig.configure(registryConfigs, null);
+            assertNotNull(jaasConfig);
             fail("Expected IllegalArgumentException because the AliasService is not available.");
         } catch (IllegalArgumentException e) {
             // Expected
index be5ff41..06b9eb2 100644 (file)
@@ -27,13 +27,14 @@ import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.io.OutputStream;
 import java.nio.charset.Charset;
 import java.nio.charset.StandardCharsets;
 
 import static org.hamcrest.CoreMatchers.nullValue;
 import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.fail;
+import static org.junit.Assert.assertNotNull;
 
 public class CappedBufferHttpEntityTest {
   // Variables
@@ -72,9 +73,7 @@ public class CappedBufferHttpEntityTest {
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 20 );
 
-    String output;
-
-    output = byteRead( replay.getContent(), -1 );
+    String output = byteRead( replay.getContent(), -1 );
     assertThat( output, is( data ) );
   }
 
@@ -88,13 +87,11 @@ public class CappedBufferHttpEntityTest {
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 20 );
 
-    String output;
-
-    output = blockRead( replay.getContent(), StandardCharsets.UTF_8, -1, 3 );
+    String output = blockRead( replay.getContent(), StandardCharsets.UTF_8, -1, 3 );
     assertThat( output, is( data ) );
   }
 
-  @Test
+  @Test (expected = IOException.class)
   public void testS__C1_FC_OB() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
@@ -104,17 +101,10 @@ public class CappedBufferHttpEntityTest {
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 5 );
 
-    String output;
-
-    try {
-      output = byteRead( replay.getContent(), -1 );
-      fail("expected IOException");
-    } catch (IOException e) {
-      // expected
-    }
+    byteRead( replay.getContent(), -1 );
   }
 
-  @Test
+  @Test (expected = IOException.class)
   public void testB__C1_FC_OB() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
@@ -124,14 +114,7 @@ public class CappedBufferHttpEntityTest {
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 5 );
 
-    String output;
-
-    try {
-      output = blockRead( replay.getContent(), StandardCharsets.UTF_8, -1, 3 );
-      fail("expected IOException");
-    } catch (IOException e) {
-      // expected
-    }
+    blockRead( replay.getContent(), StandardCharsets.UTF_8, -1, 3 );
   }
 
   @Test
@@ -172,7 +155,7 @@ public class CappedBufferHttpEntityTest {
     assertThat( output, is( data ) );
   }
 
-  @Test
+  @Test (expected = IOException.class)
   public void testS_C1_FC_OB__C2_AC__EE() throws Exception {
     String data = "0123456789";
     BasicHttpEntity basic;
@@ -182,17 +165,10 @@ public class CappedBufferHttpEntityTest {
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 5 );
 
-    String output;
-
-    try {
-      output = byteRead( replay.getContent(), -1 );
-    fail( "Expected IOException" );
-    } catch( IOException e ) {
-     // Expected.
-   }
+    byteRead( replay.getContent(), -1 );
   }
 
-  @Test
+  @Test (expected = IOException.class)
   public void testB_C1_FC_OB__C2_AC__EE() throws Exception {
     String data = "0123456789";
     BasicHttpEntity basic;
@@ -202,13 +178,7 @@ public class CappedBufferHttpEntityTest {
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 5 );
 
-    String output;
-    try {
-      output = blockRead( replay.getContent(), StandardCharsets.UTF_8, -1, 3 );
-      fail( "Expected IOException" );
-    } catch( IOException e ) {
-      // Expected.
-    }
+    blockRead( replay.getContent(), StandardCharsets.UTF_8, -1, 3 );
   }
 
   //   C1 FC/IB; C1 XC; C2 FC.
@@ -257,46 +227,34 @@ public class CappedBufferHttpEntityTest {
   }
 
   //   C1 FC/OB; C1 XC; C2 AC; EE
-  @Test
+  @Test (expected = IOException.class)
   public void testS_C1_FC_OB__C1_XC__C2_AC__EE() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
     CappedBufferHttpEntity replay;
-    InputStream stream;
-    String text;
 
     basic = new BasicHttpEntity();
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 5 );
 
-    stream = replay.getContent();
-    try {
-      text = byteRead( stream, -1 );
-      fail( "Expected IOException" );
-    } catch( IOException e ) {
-      // Expected.
+    try(InputStream stream = replay.getContent()) {
+      byteRead(stream, -1);
     }
   }
 
   //   C1 FC/OB; C1 XC; C2 AC; EE
-  @Test
+  @Test (expected = IOException.class)
   public void testB_C1_FC_OB__C1_XC__C2_AC_EE() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
     CappedBufferHttpEntity replay;
-    InputStream stream;
-    String text;
 
     basic = new BasicHttpEntity();
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 5 );
 
-    stream = replay.getContent();
-    try {
-      text = blockRead( stream, StandardCharsets.UTF_8, -1, 3 );
-      fail( "Expected IOException" );
-    } catch( IOException e ) {
-      // Expected.
+    try(InputStream stream = replay.getContent()) {
+      blockRead(stream, StandardCharsets.UTF_8, -1, 3);
     }
   }
 
@@ -306,16 +264,15 @@ public class CappedBufferHttpEntityTest {
     String data = "0123456789";
     BasicHttpEntity basic;
     CappedBufferHttpEntity replay;
-    InputStream stream;
-    String text;
 
     basic = new BasicHttpEntity();
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 20 );
 
-    stream = replay.getContent();
-    text = byteRead( stream, 3 );
-    assertThat( text, is( "012" ) );
+    try(InputStream stream = replay.getContent()) {
+      String text = byteRead(stream, 3);
+      assertThat(text, is("012"));
+    }
   }
 
   //   C1 PC/IB.
@@ -324,61 +281,45 @@ public class CappedBufferHttpEntityTest {
     String data = "0123456789";
     BasicHttpEntity basic;
     CappedBufferHttpEntity replay;
-    InputStream stream;
-    String text;
 
     basic = new BasicHttpEntity();
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 20 );
 
-    stream = replay.getContent();
-    text = blockRead( stream, StandardCharsets.UTF_8, 3, 3 );
-    assertThat( text, is( "012" ) );
+    try(InputStream stream = replay.getContent()) {
+      String text = blockRead(stream, StandardCharsets.UTF_8, 3, 3);
+      assertThat(text, is("012"));
+    }
   }
 
   //   C1 PC/OB.
-  @Test
+  @Test (expected = IOException.class)
   public void testS_C1_PC_OB() throws IOException {
+    String data = "0123456789";
+    BasicHttpEntity basic;
+    CappedBufferHttpEntity replay;
 
-    try {
-      String data = "0123456789";
-      BasicHttpEntity basic;
-      CappedBufferHttpEntity replay;
-      InputStream stream;
-      String text;
-
-      basic = new BasicHttpEntity();
-      basic.setContent(new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)));
-      replay = new CappedBufferHttpEntity(basic, 5);
-      stream = replay.getContent();
-      text = byteRead(stream, -1);
-      fail("Expected IOException");
-      assertThat(text, is("0123456789"));
-      stream.close();
-    } catch (IOException e) {
-      // expected
+    basic = new BasicHttpEntity();
+    basic.setContent(new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)));
+    replay = new CappedBufferHttpEntity(basic, 5);
+    try(InputStream stream = replay.getContent()) {
+      byteRead(stream, -1);
     }
   }
 
   //   C1 PC/OB.
-  @Test
+  @Test (expected = IOException.class)
   public void testB_C1_PC_OB() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
     CappedBufferHttpEntity replay;
-    InputStream stream;
-    String text;
 
     basic = new BasicHttpEntity();
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 5 );
 
-    stream = replay.getContent();
-    try {
-      text = blockRead( stream, StandardCharsets.UTF_8, -1, 4 );
-      fail( "Expected IOException" );
-    } catch (IOException e) {
-      // expected
+    try (InputStream stream = replay.getContent()) {
+      blockRead(stream, StandardCharsets.UTF_8, -1, 4);
     }
   }
 
@@ -388,21 +329,20 @@ public class CappedBufferHttpEntityTest {
     String data = "0123456789";
     BasicHttpEntity basic;
     CappedBufferHttpEntity replay;
-    InputStream stream;
-    String text;
 
     basic = new BasicHttpEntity();
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 20 );
 
-    stream = replay.getContent();
-    text = byteRead( stream, 4 );
-    assertThat( text, is( "0123" ) );
-    stream.close();
+    try(InputStream stream = replay.getContent()) {
+      String text = byteRead(stream, 4);
+      assertThat(text, is("0123"));
+    }
 
-    stream = replay.getContent();
-    text = byteRead( stream, -1 );
-    assertThat( text, is( "0123456789" ) );
+    try(InputStream stream = replay.getContent()) {
+      String text = byteRead(stream, -1);
+      assertThat(text, is("0123456789"));
+    }
   }
 
   //   C1 PC/IB; C2 FC.
@@ -411,66 +351,52 @@ public class CappedBufferHttpEntityTest {
     String data = "0123456789";
     BasicHttpEntity basic;
     CappedBufferHttpEntity replay;
-    InputStream stream;
-    String text;
 
     basic = new BasicHttpEntity();
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 20 );
 
-    stream = replay.getContent();
-    text = blockRead( stream, StandardCharsets.UTF_8, 4, 1 );
-    assertThat( text, is( "0123" ) );
-    stream.close();
+    try(InputStream stream = replay.getContent()) {
+      String text = blockRead(stream, StandardCharsets.UTF_8, 4, 1);
+      assertThat(text, is("0123"));
+    }
 
-    stream = replay.getContent();
-    text = blockRead( stream, StandardCharsets.UTF_8, -1, 7 );
-    assertThat( text, is( "0123456789" ) );
+    try(InputStream stream = replay.getContent()) {
+      String text = blockRead(stream, StandardCharsets.UTF_8, -1, 7);
+      assertThat(text, is("0123456789"));
+    }
   }
 
   //   C1 PC/OB; C2 AC; EE
-  @Test
+  @Test (expected = IOException.class)
   public void testS_C1_PC_OB__C2_AC__EE() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
     CappedBufferHttpEntity replay;
-    InputStream stream;
-    String text;
 
-    try {
-      basic = new BasicHttpEntity();
-      basic.setContent(new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)));
-      replay = new CappedBufferHttpEntity(basic, 5);
+    basic = new BasicHttpEntity();
+    basic.setContent(new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)));
+    replay = new CappedBufferHttpEntity(basic, 5);
 
-      stream = replay.getContent();
-      text = byteRead(stream, 7);
+    try(InputStream stream = replay.getContent()) {
+      String text = byteRead(stream, 7);
       assertThat(text, is("0123456"));
-      stream.close();
-      fail("Expected IOException");
-    } catch (IOException e) {
-      // Expected.
     }
   }
 
   //   C1 PC/OB; C2 AC; EE
-  @Test
+  @Test (expected = IOException.class)
   public void testB_C1_PC_OB__C2_AC__EE() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
     CappedBufferHttpEntity replay;
-    InputStream stream;
-    String text;
 
     basic = new BasicHttpEntity();
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 5 );
 
-    stream = replay.getContent();
-    try {
-      text = blockRead( stream, StandardCharsets.UTF_8, 7, 2 );
-      fail("Expected IOExceptin");
-    } catch (IOException e) {
-      // expected
+    try(InputStream stream = replay.getContent()) {
+      blockRead(stream, StandardCharsets.UTF_8, 7, 2);
     }
   }
 
@@ -480,21 +406,20 @@ public class CappedBufferHttpEntityTest {
     String data = "0123456789";
     BasicHttpEntity basic;
     CappedBufferHttpEntity replay;
-    InputStream stream;
-    String text;
 
     basic = new BasicHttpEntity();
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 20 );
 
-    stream = replay.getContent();
-    text = byteRead( stream, 7 );
-    assertThat( text, is( "0123456" ) );
-    stream.close();
+    try(InputStream stream = replay.getContent()) {
+      String text = byteRead(stream, 7);
+      assertThat(text, is("0123456"));
+    }
 
-    stream = replay.getContent();
-    text = byteRead( stream, -1 );
-    assertThat( text, is( "0123456789" ) );
+    try(InputStream stream = replay.getContent()) {
+      String text = byteRead(stream, -1);
+      assertThat(text, is("0123456789"));
+    }
   }
 
   //   C1 PC/IB; C1 XC; C2 FC.
@@ -503,21 +428,20 @@ public class CappedBufferHttpEntityTest {
     String data = "0123456789";
     BasicHttpEntity basic;
     CappedBufferHttpEntity replay;
-    InputStream stream;
-    String text;
 
     basic = new BasicHttpEntity();
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 20 );
 
-    stream = replay.getContent();
-    text = blockRead( stream, StandardCharsets.UTF_8, 7, 2 );
-    assertThat( text, is( "0123456" ) );
-    stream.close();
+    try(InputStream stream = replay.getContent()) {
+      String text = blockRead(stream, StandardCharsets.UTF_8, 7, 2);
+      assertThat(text, is("0123456"));
+    }
 
-    stream = replay.getContent();
-    text = blockRead( stream, StandardCharsets.UTF_8, -1, 7 );
-    assertThat( text, is( "0123456789" ) );
+    try(InputStream stream = replay.getContent()) {
+      String text = blockRead( stream, StandardCharsets.UTF_8, -1, 7 );
+      assertThat( text, is( "0123456789" ) );
+    }
   }
 
   //   C1 PC/OB; C1 XC; C2 AC; EE
@@ -526,39 +450,29 @@ public class CappedBufferHttpEntityTest {
     String data = "0123456789";
     BasicHttpEntity basic;
     CappedBufferHttpEntity replay;
-    InputStream stream;
-    String text;
 
     basic = new BasicHttpEntity();
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 5 );
 
-    try {
-      stream = replay.getContent();
-    } catch ( IOException e ) {
-      // Expected.
+    try (InputStream stream = replay.getContent()) {
+      assertNotNull(stream);
     }
   }
 
   //   C1 PC/OB; C1 XC; C2 AC; EE
-  @Test
+  @Test (expected = IOException.class)
   public void testB_C1_PC_OB__C1_XC__C2_AC__EE() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
     CappedBufferHttpEntity replay;
-    InputStream stream;
-    String text;
 
     basic = new BasicHttpEntity();
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 5 );
 
-    stream = replay.getContent();
-    try {
-      text = blockRead( stream, StandardCharsets.UTF_8, 7, 2 );
-      fail( "Expected IOException" );
-    } catch ( IOException e ) {
-      // Expected.
+    try(InputStream stream = replay.getContent()) {
+      blockRead( stream, StandardCharsets.UTF_8, 7, 2 );
     }
   }
 
@@ -568,23 +482,23 @@ public class CappedBufferHttpEntityTest {
     String data = "0123456789";
     BasicHttpEntity basic;
     CappedBufferHttpEntity replay;
-    InputStream stream1, stream2;
     String text;
 
     basic = new BasicHttpEntity();
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 20 );
 
-    stream1 = replay.getContent();
-    text = byteRead( stream1, 3 );
-    assertThat( text, is( "012" ) );
+    try(InputStream stream1 = replay.getContent();
+        InputStream stream2 = replay.getContent()) {
+      text = byteRead(stream1, 3);
+      assertThat(text, is("012"));
 
-    stream2 = replay.getContent();
-    text = byteRead( stream2, 4 );
-    assertThat( text, is( "0123" ) );
+      text = byteRead(stream2, 4);
+      assertThat(text, is("0123"));
 
-    text = byteRead( stream1, 3 );
-    assertThat( text, is( "345" ) );
+      text = byteRead(stream1, 3);
+      assertThat(text, is("345"));
+    }
   }
 
   //   C1 PC/IB; C2 PC/IB; C1 PC/IB; C2 PC/IB - Back and forth before buffer overflow is OK.
@@ -634,32 +548,28 @@ public class CappedBufferHttpEntityTest {
   }
 
   //   C1 PC/IB; C2 PC/OB; C1 AC; EE
-  @Test
+  @Test (expected = IOException.class)
   public void testB_C1_PC_IB__C2_PC_OB__C1_AC__EE() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
     CappedBufferHttpEntity replay;
-    InputStream stream1, stream2;
     String text;
 
     basic = new BasicHttpEntity();
     basic.setContent( new ByteArrayInputStream( data.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 5 );
 
-    stream1 = replay.getContent();
-    text = blockRead( stream1, StandardCharsets.UTF_8, 3, 2 );
-    assertThat( text, is( "012" ) );
+    try (InputStream stream = replay.getContent()) {
+      text = blockRead( stream, StandardCharsets.UTF_8, 3, 2 );
+      assertThat( text, is( "012" ) );
+    }
 
-    stream2 = replay.getContent();
-    try {
-      text = blockRead( stream2, StandardCharsets.UTF_8, 6, 4 );
-      fail("expected IOException");
-    } catch (IOException e) {
-      // expected
+    try (InputStream stream = replay.getContent()) {
+      blockRead( stream, StandardCharsets.UTF_8, 6, 4 );
     }
   }
 
-  @Test
+  @Test (expected = IOException.class)
   public void testWriteTo() throws Exception {
     String input = "0123456789";
     BasicHttpEntity basic;
@@ -669,12 +579,8 @@ public class CappedBufferHttpEntityTest {
     basic.setContent( new ByteArrayInputStream( input.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 5 );
 
-    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
-    try {
-      replay.writeTo( buffer );
-      fail("expected IOException");
-    } catch (IOException e) {
-      // expected
+    try(OutputStream buffer = new ByteArrayOutputStream()) {
+      replay.writeTo(buffer);
     }
   }
 
@@ -790,7 +696,7 @@ public class CappedBufferHttpEntityTest {
     assertThat( replay.isStreaming(), is( true ) );
   }
 
-  @Test
+  @Test (expected = UnsupportedOperationException.class)
   public void testConsumeContent() throws Exception {
     String input = "0123456789";
     BasicHttpEntity basic;
@@ -799,13 +705,7 @@ public class CappedBufferHttpEntityTest {
     basic = new BasicHttpEntity();
     basic.setContent( new ByteArrayInputStream( input.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new CappedBufferHttpEntity( basic, 5 );
-
-    try {
-      replay.consumeContent();
-      fail( "Expected UnsupportedOperationException" );
-    } catch ( UnsupportedOperationException e ) {
-      // Expected.
-    }
+    replay.consumeContent();
   }
 
   private static String byteRead( InputStream stream, int total ) throws IOException {
@@ -846,5 +746,4 @@ public class CappedBufferHttpEntityTest {
     }
     return string == null ? null : string.toString();
   }
-
 }
index 6330db3..909bb05 100644 (file)
@@ -24,8 +24,9 @@ import org.easymock.EasyMock;
 import org.junit.Test;
 
 import java.io.File;
-import java.io.FileOutputStream;
+import java.io.OutputStream;
 import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
 import java.util.List;
 
 import static org.hamcrest.CoreMatchers.is;
@@ -166,10 +167,10 @@ public class HadoopAuthCookieStoreTest {
     File result = null;
     try {
       File f = File.createTempFile(filename, ".conf");
-      FileOutputStream out = new FileOutputStream(f);
-      out.write(contents.getBytes(StandardCharsets.UTF_8));
-      out.flush();
-      out.close();
+      try(OutputStream out = Files.newOutputStream(f.toPath())) {
+        out.write(contents.getBytes(StandardCharsets.UTF_8));
+        out.flush();
+      }
       result = f;
     } catch (Exception e) {
       //
index 4865d01..54a1a2c 100644 (file)
@@ -33,7 +33,6 @@ import java.nio.charset.StandardCharsets;
 import static org.hamcrest.CoreMatchers.nullValue;
 import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.fail;
 
 public class PartiallyRepeatableHttpEntityTest {
 
@@ -165,7 +164,7 @@ public class PartiallyRepeatableHttpEntityTest {
     assertThat( output, is( data ) );
   }
 
-  @Test
+  @Test (expected = IOException.class)
   public void testS_C1_FC_OB__C2_AC__EE() throws Exception {
     String data = "0123456789";
     BasicHttpEntity basic;
@@ -180,15 +179,10 @@ public class PartiallyRepeatableHttpEntityTest {
     output = byteRead( replay.getContent(), -1 );
     assertThat( output, is( data ) );
 
-    try {
-      replay.getContent();
-      fail( "Expected IOException" );
-    } catch( IOException e ) {
-      // Expected.
-    }
+    replay.getContent();
   }
 
-  @Test
+  @Test (expected = IOException.class)
   public void testB_C1_FC_OB__C2_AC__EE() throws Exception {
     String data = "0123456789";
     BasicHttpEntity basic;
@@ -203,12 +197,7 @@ public class PartiallyRepeatableHttpEntityTest {
     output = blockRead( replay.getContent(), StandardCharsets.UTF_8, -1, 3 );
     assertThat( output, is( data ) );
 
-    try {
-      replay.getContent();
-      fail( "Expected IOException" );
-    } catch( IOException e ) {
-      // Expected.
-    }
+    replay.getContent();
   }
 
   //   C1 FC/IB; C1 XC; C2 FC.
@@ -257,7 +246,7 @@ public class PartiallyRepeatableHttpEntityTest {
   }
 
   //   C1 FC/OB; C1 XC; C2 AC; EE
-  @Test
+  @Test (expected = IOException.class)
   public void testS_C1_FC_OB__C1_XC__C2_AC__EE() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
@@ -274,16 +263,11 @@ public class PartiallyRepeatableHttpEntityTest {
     assertThat( text, is( "0123456789" ) );
     stream.close();
 
-    try {
-      replay.getContent();
-      fail( "Expected IOException" );
-    } catch( IOException e ) {
-      // Expected.
-    }
+    replay.getContent();
   }
 
   //   C1 FC/OB; C1 XC; C2 AC; EE
-  @Test
+  @Test (expected = IOException.class)
   public void testB_C1_FC_OB__C1_XC__C2_AC_EE() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
@@ -300,12 +284,7 @@ public class PartiallyRepeatableHttpEntityTest {
     assertThat( text, is( "0123456789" ) );
     stream.close();
 
-    try {
-      replay.getContent();
-      fail( "Expected IOException" );
-    } catch( IOException e ) {
-      // Expected.
-    }
+    replay.getContent();
   }
 
   //   C1 PC/IB.
@@ -429,7 +408,7 @@ public class PartiallyRepeatableHttpEntityTest {
   }
 
   //   C1 PC/OB; C2 AC; EE
-  @Test
+  @Test (expected = IOException.class)
   public void testS_C1_PC_OB__C2_AC__EE() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
@@ -446,16 +425,11 @@ public class PartiallyRepeatableHttpEntityTest {
     assertThat( text, is( "0123456" ) );
     stream.close();
 
-    try {
-      replay.getContent();
-      fail( "Expected IOException" );
-    } catch ( IOException e ) {
-      // Expected.
-    }
+    replay.getContent();
   }
 
   //   C1 PC/OB; C2 AC; EE
-  @Test
+  @Test (expected = IOException.class)
   public void testB_C1_PC_OB__C2_AC__EE() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
@@ -472,12 +446,7 @@ public class PartiallyRepeatableHttpEntityTest {
     assertThat( text, is( "0123456" ) );
     stream.close();
 
-    try {
-      replay.getContent();
-      fail( "Expected IOException" );
-    } catch ( IOException e ) {
-      // Expected.
-    }
+    replay.getContent();
   }
 
   //   C1 PC/IB; C1 XC; C2 FC.
@@ -527,7 +496,7 @@ public class PartiallyRepeatableHttpEntityTest {
   }
 
   //   C1 PC/OB; C1 XC; C2 AC; EE
-  @Test
+  @Test (expected = IOException.class)
   public void testS_C1_PC_OB__C1_XC__C2_AC__EE() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
@@ -544,16 +513,11 @@ public class PartiallyRepeatableHttpEntityTest {
     assertThat( text, is( "0123456" ) );
     stream.close();
 
-    try {
-      replay.getContent();
-      fail( "Expected IOException" );
-    } catch ( IOException e ) {
-      // Expected.
-    }
+    replay.getContent();
   }
 
   //   C1 PC/OB; C1 XC; C2 AC; EE
-  @Test
+  @Test (expected = IOException.class)
   public void testB_C1_PC_OB__C1_XC__C2_AC__EE() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
@@ -570,12 +534,7 @@ public class PartiallyRepeatableHttpEntityTest {
     assertThat( text, is( "0123456" ) );
     stream.close();
 
-    try {
-      replay.getContent();
-      fail( "Expected IOException" );
-    } catch ( IOException e ) {
-      // Expected.
-    }
+    replay.getContent();
   }
 
   //   C1 PC/IB; C2 PC/IB; C1 PC/IB; C2 PC/IB - Back and forth before buffer overflow is OK.
@@ -628,7 +587,7 @@ public class PartiallyRepeatableHttpEntityTest {
   }
 
   //   C1 PC/IB; C2 PC/OB; C1 AC; EE
-  @Test
+  @Test (expected = IOException.class)
   public void testS_C1_PC_IB__C2_PC_OB__C1_AC__EE() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
@@ -648,16 +607,11 @@ public class PartiallyRepeatableHttpEntityTest {
     text = byteRead( stream2, 6 );
     assertThat( text, is( "012345" ) );
 
-    try {
-      byteRead( stream1, 1 );
-      fail( "Expected IOException" );
-    } catch ( IOException e ) {
-      // Expected.
-    }
+    byteRead( stream1, 1 );
   }
 
   //   C1 PC/IB; C2 PC/OB; C1 AC; EE
-  @Test
+  @Test (expected = IOException.class)
   public void testB_C1_PC_IB__C2_PC_OB__C1_AC__EE() throws IOException {
     String data = "0123456789";
     BasicHttpEntity basic;
@@ -677,12 +631,7 @@ public class PartiallyRepeatableHttpEntityTest {
     text = blockRead( stream2, StandardCharsets.UTF_8, 6, 4 );
     assertThat( text, is( "012345" ) );
 
-    try {
-      blockRead( stream1, StandardCharsets.UTF_8, 6, 4 );
-      fail( "Expected IOException" );
-    } catch ( IOException e ) {
-      // Expected.
-    }
+    blockRead( stream1, StandardCharsets.UTF_8, 6, 4 );
   }
 
   @Test
@@ -813,7 +762,7 @@ public class PartiallyRepeatableHttpEntityTest {
     assertThat( replay.isStreaming(), is( true ) );
   }
 
-  @Test
+  @Test (expected = UnsupportedOperationException.class)
   public void testConsumeContent() throws Exception {
     String input = "0123456789";
     BasicHttpEntity basic;
@@ -823,12 +772,7 @@ public class PartiallyRepeatableHttpEntityTest {
     basic.setContent( new ByteArrayInputStream( input.getBytes( StandardCharsets.UTF_8 ) ) );
     replay = new PartiallyRepeatableHttpEntity( basic, 5 );
 
-    try {
-      replay.consumeContent();
-      fail( "Expected UnsupportedOperationException" );
-    } catch ( UnsupportedOperationException e ) {
-      // Expected.
-    }
+    replay.consumeContent();
   }
 
   private static String byteRead( InputStream stream, int total ) throws IOException {
@@ -869,5 +813,4 @@ public class PartiallyRepeatableHttpEntityTest {
     }
     return string == null ? null : string.toString();
   }
-
 }
index 066d546..8ee49f8 100644 (file)
@@ -35,7 +35,7 @@ public class PrincipalMapperTest {
   PrincipalMapper mapper;
 
   @Before
-  public void setup() {
+  public void setUp() {
     mapper = new SimplePrincipalMapper();
   }
 
index 358dfe9..8a21782 100644 (file)
@@ -49,7 +49,7 @@ public class CMFKeystoreServiceTest {
   File certificateFile = new File("ambari");
 
   @Before
-  public void setup() {
+  public void setUp() {
     try {
       ks = new CMFKeystoreService(".", "ambari");
       ks.setMasterService(new MasterService() {
index ed23bd4..27ad390 100644 (file)
@@ -43,7 +43,7 @@ public class JWTTokenTest extends org.junit.Assert {
   private static RSAPrivateKey privateKey;
 
   @BeforeClass
-  public static void setup() throws Exception {
+  public static void setUpBeforeClass() throws Exception {
     KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
     kpg.initialize(2048);
 
@@ -225,14 +225,16 @@ public class JWTTokenTest extends org.junit.Assert {
 
   @Test
   public void testUnsignedToken() throws Exception {
-      String unsignedToken = "eyJhbGciOiJub25lIn0.eyJzdWIiOiJhbGljZSIsImp0aSI6ImY2YmNj"
-          + "MDVjLWI4MTktNGM0Mi1iMGMyLWJlYmY1MDE4YWFiZiJ9.";
-
-      try {
-          new JWTToken(unsignedToken);
-          fail("Failure expected on an unsigned token");
-      } catch (ParseException ex) {
-          // expected
-      }
+    String unsignedToken = "eyJhbGciOiJub25lIn0.eyJzdWIiOiJhbGljZSIsImp0aSI6ImY2YmNj"
+                               + "MDVjLWI4MTktNGM0Mi1iMGMyLWJlYmY1MDE4YWFiZiJ9.";
+
+    try {
+      new JWTToken(unsignedToken);
+      fail("Failure expected on an unsigned token");
+    } catch (ParseException ex) {
+      // expected
+      assertEquals("Invalid JWS header: The algorithm \"alg\" header parameter must be for signatures",
+          ex.getMessage());
+    }
   }
 }
index af51587..0f0804d 100644 (file)
@@ -26,7 +26,6 @@ import java.lang.reflect.Method;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
-import java.util.Locale;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -184,13 +183,6 @@ public class WhitelistUtilsTest {
     EasyMock.replay(request);
 
     String result = null;
-//    if (serverName != null && !serverName.isEmpty() && !isLocalhostServerName(serverName) && xForwardedHost == null) {
-//      try {
-//        result = doTestDeriveDomainBasedWhitelist(serverName);
-//      } catch (Exception e) {
-//        e.printStackTrace();
-//      }
-//    } else if (xForwardedHost != null && !xForwardedHost.isEmpty()) {
     if (xForwardedHost != null && !xForwardedHost.isEmpty()) {
       try {
         Method method = WhitelistUtils.class.getDeclaredMethod("deriveDefaultDispatchWhitelist", HttpServletRequest.class);
@@ -218,10 +210,6 @@ public class WhitelistUtilsTest {
     return (String) defineWhitelistMethod.invoke(null, domain);
   }
 
-  private static boolean isLocalhostServerName(final String serverName) {
-    return LOCALHOST_NAMES.contains(serverName.toLowerCase(Locale.ROOT));
-  }
-
   private static GatewayConfig createMockGatewayConfig(final List<String> serviceRoles, final String whitelist) {
     GatewayConfig config = EasyMock.createNiceMock(GatewayConfig.class);
     EasyMock.expect(config.getDispatchWhitelistServices()).andReturn(serviceRoles).anyTimes();
@@ -230,5 +218,4 @@ public class WhitelistUtilsTest {
 
     return config;
   }
-
 }
index 5909163..1878653 100644 (file)
@@ -48,11 +48,12 @@ import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
 import java.io.File;
-import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.io.Writer;
 import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
 import java.security.Principal;
 import java.util.Locale;
 import java.util.Properties;
@@ -90,7 +91,7 @@ public class SecureClusterTest {
   private static File baseDir;
 
   @BeforeClass
-  public static void setupSuite() throws Exception {
+  public static void setUpBeforeClass() throws Exception {
     nameNodeHttpPort = TestUtils.findFreePort();
     configuration = new HdfsConfiguration();
     baseDir = new File(KeyStoreTestUtil.getClasspathDir(SecureClusterTest.class));
@@ -175,7 +176,7 @@ public class SecureClusterTest {
   }
 
   @AfterClass
-  public static void cleanupSuite() throws Exception {
+  public static void tearDownAfterClass() throws Exception {
     if(kdc != null) {
       kdc.stop();
     }
@@ -232,22 +233,23 @@ public class SecureClusterTest {
       file.delete();
       file.createNewFile();
     }
-    Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
-    String content = String.format(Locale.ROOT,
-        "com.sun.security.jgss.initiate {\n" +
-            "com.sun.security.auth.module.Krb5LoginModule required\n" +
-            "renewTGT=true\n" +
-            "doNotPrompt=true\n" +
-            "useKeyTab=true\n" +
-            "keyTab=\"%s\"\n" +
-            "principal=\"%s\"\n" +
-            "isInitiator=true\n" +
-            "storeKey=true\n" +
-            "useTicketCache=true\n" +
-            "client=true;\n" +
-            "};\n", keyTabFile, principal);
-    writer.write(content);
-    writer.close();
+    try(OutputStream outputStream = Files.newOutputStream(file.toPath());
+        Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
+      String content = String.format(Locale.ROOT,
+          "com.sun.security.jgss.initiate {\n" +
+              "com.sun.security.auth.module.Krb5LoginModule required\n" +
+              "renewTGT=true\n" +
+              "doNotPrompt=true\n" +
+              "useKeyTab=true\n" +
+              "keyTab=\"%s\"\n" +
+              "principal=\"%s\"\n" +
+              "isInitiator=true\n" +
+              "storeKey=true\n" +
+              "useTicketCache=true\n" +
+              "client=true;\n" +
+              "};\n", keyTabFile, principal);
+      writer.write(content);
+    }
     return file;
   }
 
index fddda57..9e46ff9 100644 (file)
@@ -38,12 +38,13 @@ import org.junit.Test;
 import org.junit.experimental.categories.Category;
 
 import java.io.File;
-import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.io.Writer;
 import java.net.URL;
 import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
 import java.util.Locale;
 import java.util.Properties;
 
@@ -72,7 +73,6 @@ import static org.junit.Assert.assertTrue;
  */
 @Category(ReleaseTest.class)
 public class SecureKnoxShellTest {
-
   private static final String SCRIPT = "SecureWebHdfsPutGet.groovy";
   private static MiniKdc kdc;
   private static String userName;
@@ -83,22 +83,14 @@ public class SecureKnoxShellTest {
   private static String hdfsPrincipal;
   private static String spnegoPrincipal;
   private static String keytab;
-  private static File ticketCache;
 
   private static MiniDFSCluster miniDFSCluster;
   private static GatewayTestDriver driver = new GatewayTestDriver();
 
-  public SecureKnoxShellTest() {
-    super();
-  }
-
   @BeforeClass
-  public static void setupSuite() throws Exception {
+  public static void setUpBeforeClass() throws Exception {
     baseDir = new File(
         KeyStoreTestUtil.getClasspathDir(SecureKnoxShellTest.class));
-    ticketCache = new File(
-        KeyStoreTestUtil.getClasspathDir(SecureKnoxShellTest.class)
-            + "/ticketCache");
 
     nameNodeHttpPort = TestUtils.findFreePort();
     configuration = new HdfsConfiguration();
@@ -117,7 +109,6 @@ public class SecureKnoxShellTest {
   }
 
   private static void initKdc() throws Exception {
-
     final Properties kdcConf = MiniKdc.createConf();
     kdc = new MiniKdc(kdcConf, baseDir);
     kdc.start();
@@ -167,8 +158,7 @@ public class SecureKnoxShellTest {
   }
 
   @AfterClass
-  public static void cleanupSuite() throws Exception {
-
+  public static void tearDownAfterClass() throws Exception {
     if(kdc != null) {
       kdc.stop();
     }
@@ -178,7 +168,6 @@ public class SecureKnoxShellTest {
     if(driver != null) {
       driver.cleanup();
     }
-
   }
 
   private static File setupJaasConf(File baseDir, String keyTabFile,
@@ -190,16 +179,16 @@ public class SecureKnoxShellTest {
       file.delete();
       file.createNewFile();
     }
-    final Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
-    String content = String.format(Locale.ROOT, "com.sun.security.jgss.initiate {\n"
-        + "com.sun.security.auth.module.Krb5LoginModule required\n"
-        + "renewTGT=true\n" + "doNotPrompt=true\n" + "useKeyTab=true\n"
-        + "keyTab=\"%s\"\n" + "principal=\"%s\"\n" + "isInitiator=true\n"
-        + "storeKey=true\n" + "useTicketCache=true\n" +
-        //"ticketCache=\"%s\"\n" +
-        "debug=false\n" + "client=true;\n" + "};\n", keyTabFile, principal);
-    writer.write(content);
-    writer.close();
+    try(OutputStream outputStream = Files.newOutputStream(file.toPath());
+        Writer writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)) {
+      String content = String.format(Locale.ROOT, "com.sun.security.jgss.initiate {\n"
+                                                      + "com.sun.security.auth.module.Krb5LoginModule required\n"
+                                                      + "renewTGT=true\n" + "doNotPrompt=true\n" + "useKeyTab=true\n"
+                                                      + "keyTab=\"%s\"\n" + "principal=\"%s\"\n" + "isInitiator=true\n"
+                                                      + "storeKey=true\n" + "useTicketCache=true\n" +
+                                                      "debug=false\n" + "client=true;\n" + "};\n", keyTabFile, principal);
+      writer.write(content);
+    }
     return file;
   }
 
@@ -208,8 +197,7 @@ public class SecureKnoxShellTest {
 
     File jaasConf = setupJaasConf(baseDir, keytab, hdfsPrincipal);
 
-    System.setProperty("java.security.krb5.conf",
-        ((MiniKdc) kdc).getKrb5conf().getAbsolutePath());
+    System.setProperty("java.security.krb5.conf", kdc.getKrb5conf().getAbsolutePath());
     System.setProperty("java.security.auth.login.config",
         jaasConf.getAbsolutePath());
     System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
@@ -317,7 +305,6 @@ public class SecureKnoxShellTest {
 
     URL readme = driver.getResourceUrl("README");
     File file = new File(readme.toURI());
-    //System.out.println(file.exists());
     binding.setProperty("file", file.getAbsolutePath());
 
     final GroovyShell shell = new GroovyShell(binding);
@@ -326,11 +313,9 @@ public class SecureKnoxShellTest {
 
     String status = (String) binding.getProperty("status");
     assertNotNull(status);
-    //System.out.println(status);
 
     String fetchedFile = (String) binding.getProperty("fetchedFile");
     assertNotNull(fetchedFile);
-    //`(fetchedFile);
     assertTrue(fetchedFile.contains("README"));
   }
 
@@ -340,5 +325,4 @@ public class SecureKnoxShellTest {
             + resource;
     return ClassLoader.getSystemResource(filePath);
   }
-
 }
index 54365d8..fd5cdf3 100644 (file)
@@ -16,6 +16,7 @@
  * limitations under the License.
  */
 package org.apache.knox.gateway;
+
 import org.apache.knox.test.category.ReleaseTest;
 import org.junit.experimental.categories.Category;
 
@@ -46,10 +47,8 @@ import static org.junit.Assert.assertNotNull;
 
 import static org.hamcrest.MatcherAssert.assertThat;
 
-
 @Category(ReleaseTest.class)
 public class ShellTest {
-
   private static MiniDFSCluster miniDFSCluster;
   private static HdfsConfiguration configuration;
   private static int nameNodeHttpPort;
@@ -59,7 +58,7 @@ public class ShellTest {
   private static File baseDir;
 
   @BeforeClass
-  public static void setupSuite() throws Exception {
+  public static void setUpBeforeClass() throws Exception {
     nameNodeHttpPort = TestUtils.findFreePort();
     configuration = new HdfsConfiguration();
     baseDir = new File(KeyStoreTestUtil.getClasspathDir(ShellTest.class));
@@ -72,12 +71,12 @@ public class ShellTest {
         .racks(null)
         .build();
     userName = UserGroupInformation.createUserForTesting("guest", new String[] {"users"}).getUserName();
+    assertNotNull(userName);
 
     setupKnox();
   }
 
   private static void setupKnox() throws Exception {
-    //knox setup
     System.setProperty("gateway.hadoop.kerberos.secured", "false");
     GatewayTestConfig config = new GatewayTestConfig();
     config.setGatewayPath( "gateway" );
@@ -88,7 +87,7 @@ public class ShellTest {
   }
 
   @AfterClass
-  public static void cleanupSuite() throws Exception {
+  public static void tearDownAfterClass() throws Exception {
     miniDFSCluster.shutdown();
     driver.cleanup();
   }
index dd739fd..75291f7 100644 (file)
@@ -33,8 +33,9 @@ import org.slf4j.LoggerFactory;
 
 import javax.ws.rs.core.MediaType;
 import java.io.File;
-import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.Files;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.UUID;
@@ -43,10 +44,8 @@ import static io.restassured.RestAssured.given;
 import static org.hamcrest.CoreMatchers.notNullValue;
 
 public class GatewayAdminFuncTest {
+  private static final Logger LOG = LoggerFactory.getLogger( GatewayAdminFuncTest.class );
 
-  private static Logger LOG = LoggerFactory.getLogger( GatewayAdminFuncTest.class );
-
-  //public static Enumeration<Appender> appenders;
   public static GatewayConfig config;
   public static GatewayServer gateway;
   public static String gatewayUrl;
@@ -54,21 +53,18 @@ public class GatewayAdminFuncTest {
   private static GatewayTestDriver driver = new GatewayTestDriver();
 
   @BeforeClass
-  public static void setupSuite() throws Exception {
+  public static void setUpBeforeClass() throws Exception {
     TestUtils.LOG_ENTER();
-    //appenders = NoOpAppender.setUpAndReturnOriginalAppenders();
     driver.setupLdap(0);
     setupGateway();
     TestUtils.LOG_EXIT();
   }
 
   @AfterClass
-  public static void cleanupSuite() throws Exception {
+  public static void tearDownAfterClass() throws Exception {
     TestUtils.LOG_ENTER();
     gateway.stop();
     driver.cleanup();
-    //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
-    //NoOpAppender.resetOriginalAppenders( appenders );
     TestUtils.LOG_EXIT();
   }
 
@@ -89,9 +85,9 @@ public class GatewayAdminFuncTest {
     deployDir.mkdirs();
 
     File descriptor = new File( topoDir, "test-cluster.xml" );
-    FileOutputStream stream = new FileOutputStream( descriptor );
-    createTopology().toStream( stream );
-    stream.close();
+    try(OutputStream stream = Files.newOutputStream(descriptor.toPath())) {
+      createTopology().toStream( stream );
+    }
 
     DefaultGatewayServices srvcs = new DefaultGatewayServices();
     Map<String,String> options = new HashMap<>();
@@ -171,5 +167,4 @@ public class GatewayAdminFuncTest {
 
     TestUtils.LOG_EXIT();
   }
-
 }
index 5ffd352..dcc1701 100644 (file)
 package org.apache.knox.gateway;
 
 import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
+import java.io.OutputStream;
 import java.io.StringReader;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.net.URLDecoder;
 import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
 import java.util.Arrays;
-import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -52,7 +51,6 @@ import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.FilenameUtils;
 import org.apache.knox.test.TestUtils;
 import org.apache.http.HttpStatus;
-import org.apache.log4j.Appender;
 import org.hamcrest.MatcherAssert;
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
@@ -81,10 +79,8 @@ import static org.junit.Assert.assertThat;
 import static org.junit.Assert.fail;
 
 public class GatewayAdminTopologyFuncTest {
+  private static final Logger LOG = LoggerFactory.getLogger( GatewayAdminTopologyFuncTest.class );
 
-  private static Logger LOG = LoggerFactory.getLogger( GatewayAdminTopologyFuncTest.class );
-
-  public static Enumeration<Appender> appenders;
   public static GatewayConfig config;
   public static GatewayServer gateway;
   public static String gatewayUrl;
@@ -92,22 +88,18 @@ public class GatewayAdminTopologyFuncTest {
   private static GatewayTestDriver driver = new GatewayTestDriver();
 
   @BeforeClass
-  public static void setupSuite() throws Exception {
-    //appenders = NoOpAppender.setUpAndReturnOriginalAppenders();
+  public static void setUpBeforeClass() throws Exception {
     driver.setupLdap(0);
     setupGateway(new GatewayTestConfig());
   }
 
   @AfterClass
-  public static void cleanupSuite() throws Exception {
+  public static void tearDownAfterClass() throws Exception {
     gateway.stop();
     driver.cleanup();
-    //FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
-    //NoOpAppender.resetOriginalAppenders( appenders );
   }
 
   public static void setupGateway(GatewayTestConfig testConfig) throws Exception {
-
     File targetDir = new File( System.getProperty( "user.dir" ), "target" );
     File gatewayDir = new File( targetDir, "gateway-home-" + UUID.randomUUID() );
     gatewayDir.mkdirs();
@@ -128,14 +120,14 @@ public class GatewayAdminTopologyFuncTest {
     descriptorsDir.mkdirs();
 
     File descriptor = new File( topoDir, "admin.xml" );
-    FileOutputStream stream = new FileOutputStream( descriptor );
-    createKnoxTopology().toStream( stream );
-    stream.close();
+    try(OutputStream stream = Files.newOutputStream(descriptor.toPath())) {
+      createKnoxTopology().toStream(stream);
+    }
 
     File descriptor2 = new File( topoDir, "test-cluster.xml" );
-    FileOutputStream stream2 = new FileOutputStream( descriptor2 );
-    createNormalTopology().toStream( stream2 );
-    stream.close();
+    try(OutputStream stream = Files.newOutputStream(descriptor2.toPath())) {
+      createNormalTopology().toStream(stream);
+    }
 
     DefaultGatewayServices srvcs = new DefaultGatewayServices();
     Map<String,String> options = new HashMap<>();
@@ -292,47 +284,40 @@ public class GatewayAdminTopologyFuncTest {
   }
 
   private static String createDescriptor(String clusterName, String providerConfigRef, boolean discovery) {
-    StringBuilder sb = new StringBuilder();
+    StringBuilder sb = new StringBuilder(1024);
     if (providerConfigRef == null) {
       providerConfigRef = "sandbox-providers";
     }
 
     sb.append("{\n");
     if (discovery) {
-      sb.append("  \"discovery-type\":\"AMBARI\",\n");
-      sb.append("  \"discovery-address\":\"http://c6401.ambari.apache.org:8080\",\n");
-      sb.append("  \"discovery-user\":\"ambariuser\",\n");
-      sb.append("  \"discovery-pwd-alias\":\"ambari.discovery.password\",\n");
+      sb.append("\"discovery-type\":\"AMBARI\",\n" +
+                    "\"discovery-address\":\"http://c6401.ambari.apache.org:8080\",\n" +
+                    "\"discovery-user\":\"ambariuser\",\n" +
+                    "\"discovery-pwd-alias\":\"ambari.discovery.password\",\n");
     }
-    sb.append("  \"provider-config-ref\":\"");
-    sb.append(providerConfigRef);
-    sb.append("\",\n");
-    sb.append("  \"cluster\":\"");
-    sb.append(clusterName);
-    sb.append("\",\n");
-    sb.append("  \"services\":[\n");
-    sb.append("    {\"name\":\"NAMENODE\"},\n");
-    sb.append("    {\"name\":\"JOBTRACKER\"},\n");
-    sb.append("    {\"name\":\"WEBHDFS\"},\n");
-    sb.append("    {\"name\":\"WEBHCAT\"},\n");
-    sb.append("    {\"name\":\"OOZIE\"},\n");
-    sb.append("    {\"name\":\"WEBHBASE\"},\n");
-    sb.append("    {\"name\":\"HIVE\"},\n");
-    sb.append("    {\"name\":\"RESOURCEMANAGER\"},\n");
-    sb.append("    {\"name\":\"AMBARI\", \"urls\":[\"http://c6401.ambari.apache.org:8080\"]}\n");
-    sb.append("  ]\n");
-    sb.append("}\n");
+    sb.append("\"provider-config-ref\":\"")
+        .append(providerConfigRef)
+        .append("\",\n\"cluster\":\"")
+        .append(clusterName)
+        .append("\",\n" +
+                  "\"services\":[\n" +
+                  "{\"name\":\"NAMENODE\"},\n" +
+                  "{\"name\":\"JOBTRACKER\"},\n" +
+                  "{\"name\":\"WEBHDFS\"},\n" +
+                  "{\"name\":\"WEBHCAT\"},\n" +
+                  "{\"name\":\"OOZIE\"},\n" +
+                  "{\"name\":\"WEBHBASE\"},\n" +
+                  "{\"name\":\"HIVE\"},\n" +
+                  "{\"name\":\"RESOURCEMANAGER\"},\n" +
+                  "{\"name\":\"AMBARI\", \"urls\":[\"http://c6401.ambari.apache.org:8080\"]}\n" +
+                  "]\n}\n");
 
     return sb.toString();
   }
 
-  //@Test
-  public void waitForManualTesting() throws IOException {
-    System.in.read();
-  }
-
   @Test( timeout = TestUtils.LONG_TIMEOUT )
-  public void testTopologyCollection() throws ClassNotFoundException {
+  public void testTopologyCollection() {
     LOG_ENTER();
 
     String username = "admin";
@@ -1161,9 +1146,9 @@ public class GatewayAdminTopologyFuncTest {
 
     // Manually write a file to the shared-providers directory
     File providerConfig = new File(sharedProvidersDir, configFileNames.get(0));
-    FileOutputStream stream = new FileOutputStream(providerConfig);
-    createProviderConfiguration().toStream(stream);
-    stream.close();
+    try(OutputStream stream = Files.newOutputStream(providerConfig.toPath())) {
+      createProviderConfiguration().toStream(stream);
+    }
 
     // Request a listing of all the provider configs
     responseBody = given()
@@ -1180,9 +1165,9 @@ public class GatewayAdminTopologyFuncTest {
 
     // Manually write another file to the shared-providers directory
     File anotherProviderConfig = new File(sharedProvidersDir, configFileNames.get(1));
-    stream = new FileOutputStream(anotherProviderConfig);
-    createProviderConfiguration().toStream(stream);
-    stream.close();
+    try(OutputStream stream = Files.newOutputStream(anotherProviderConfig.toPath())) {
+      createProviderConfiguration().toStream(stream);
+    }
 
     // Request a listing of all the provider configs
     responseBody = given()
@@ -1326,15 +1311,15 @@ public class GatewayAdminTopologyFuncTest {
 
     // Manually add two provider config files to the shared-providers directory
     File providerConfigOneFile = new File(sharedProvidersDir, "deleteme-one-config.xml");
-    FileOutputStream stream = new FileOutputStream(providerConfigOneFile);
-    createProviderConfiguration().toStream(stream);
-    stream.close();
+    try(OutputStream stream = Files.newOutputStream(providerConfigOneFile.toPath())) {
+      createProviderConfiguration().toStream(stream);
+    }
     assertTrue(providerConfigOneFile.exists());
 
     File providerConfigTwoFile = new File(sharedProvidersDir, "deleteme-two-config.xml");
-    stream = new FileOutputStream(providerConfigTwoFile);
-    createProviderConfiguration().toStream(stream);
-    stream.close();
+    try(OutputStream stream = Files.newOutputStream(providerConfigTwoFile.toPath())) {
+      createProviderConfiguration().toStream(stream);
+    }
     assertTrue(providerConfigTwoFile.exists());
 
     // Request a listing of all the provider configs
@@ -1404,15 +1389,15 @@ public class GatewayAdminTopologyFuncTest {
 
     // Manually add two provider config files to the shared-providers directory
     File providerConfigOneFile = new File(sharedProvidersDir, "deleteme-one-config.xml");
-    FileOutputStream stream = new FileOutputStream(providerConfigOneFile);
-    createProviderConfiguration().toStream(stream);
-    stream.close();
+    try(OutputStream stream = Files.newOutputStream(providerConfigOneFile.toPath())) {
+      createProviderConfiguration().toStream(stream);
+    }
     assertTrue(providerConfigOneFile.exists());
 
     File providerConfigTwoFile = new File(sharedProvidersDir, "deleteme-two-config.xml");
-    stream = new FileOutputStream(providerConfigTwoFile);
-    createProviderConfiguration().toStream(stream);
-    stream.close();
+    try(OutputStream stream = Files.newOutputStream(providerConfigTwoFile.toPath())) {
+      createProviderConfiguration().toStream(stream);
+    }
     assertTrue(providerConfigTwoFile.exists());
 
     // Request a listing of all the provider configs
@@ -1537,15 +1522,15 @@ public class GatewayAdminTopologyFuncTest {
 
     // Manually add two provider config files to the shared-providers directory
     File providerConfigOneFile = new File(sharedProvidersDir, "force-deleteme-one-config.xml");
-    FileOutputStream stream = new FileOutputStream(providerConfigOneFile);
-    createProviderConfiguration().toStream(stream);
-    stream.close();
+    try(OutputStream stream = Files.newOutputStream(providerConfigOneFile.toPath())) {
+      createProviderConfiguration().toStream(stream);
+