KNOX-1664 - Miscellaneous code cleanup
authorKevin Risden <krisden@apache.org>
Sat, 8 Dec 2018 13:54:39 +0000 (08:54 -0500)
committerKevin Risden <krisden@apache.org>
Sat, 8 Dec 2018 14:28:17 +0000 (09:28 -0500)
* Unnecessary boxing/unboxing
* Collection.toArray()
* String concatenation in loop
* StringBuffer -> StringBuilder where possible
* Identical catch block collapse
* Inline redundant variable
* Collections methods (addAll, isEmpty)
* Use isEmpty where applicable
* Remove redundant initializer

Signed-off-by: Kevin Risden <krisden@apache.org>
227 files changed:
gateway-discovery-ambari/src/main/java/org/apache/knox/gateway/topology/discovery/ambari/AmbariCluster.java
gateway-discovery-ambari/src/main/java/org/apache/knox/gateway/topology/discovery/ambari/AmbariComponent.java
gateway-discovery-ambari/src/main/java/org/apache/knox/gateway/topology/discovery/ambari/AmbariConfigurationMonitor.java
gateway-discovery-ambari/src/main/java/org/apache/knox/gateway/topology/discovery/ambari/PropertyEqualsHandler.java
gateway-discovery-ambari/src/main/java/org/apache/knox/gateway/topology/discovery/ambari/ServiceURLFactory.java
gateway-discovery-ambari/src/main/java/org/apache/knox/gateway/topology/discovery/ambari/ServiceURLPropertyConfig.java
gateway-discovery-ambari/src/test/java/org/apache/knox/gateway/topology/discovery/ambari/AmbariConfigurationMonitorTest.java
gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/messages/loggers/test/TestMessageLogger.java
gateway-i18n/src/main/java/org/apache/knox/gateway/i18n/resources/ResourcesInvoker.java
gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/URLManagerLoader.java
gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/BaseZookeeperURLManager.java
gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HBaseZookeeperURLManager.java
gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HS2ZookeeperURLManager.java
gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorFactory.java
gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/HaDescriptorManager.java
gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/KafkaZookeeperURLManager.java
gateway-provider-ha/src/main/java/org/apache/knox/gateway/ha/provider/impl/SOLRZookeeperURLManager.java
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/DefaultHaProviderTest.java
gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/AbstractIdentityAssertionFilter.java
gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/CommonIdentityAssertionFilter.java
gateway-provider-identity-assertion-common/src/main/java/org/apache/knox/gateway/identityasserter/common/filter/IdentityAsserterHttpServletRequestWrapper.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/UsernameFunctionDescriptorTest.java
gateway-provider-identity-assertion-common/src/test/java/org/apache/knox/gateway/identityasserter/function/UsernameFunctionProcessorTest.java
gateway-provider-identity-assertion-hadoop-groups/src/main/java/org/apache/knox/gateway/identityasserter/hadoop/groups/filter/HadoopGroupProviderFilter.java
gateway-provider-identity-assertion-pseudo/src/test/java/org/apache/knox/gateway/identityasserter/filter/DefaultIdentityAssertionFilterTest.java
gateway-provider-rewrite-func-hostmap-static/src/main/java/org/apache/knox/gateway/hostmap/impl/HostmapDeploymentContributor.java
gateway-provider-rewrite-func-hostmap-static/src/test/java/org/apache/knox/gateway/hostmap/impl/HostmapFunctionProcessorTest.java
gateway-provider-rewrite-func-inbound-query-param/src/main/java/org/apache/knox/gateway/inboundurl/impl/InboundUrlFunctionProcessor.java
gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceAddressFunctionProcessorTest.java
gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceHostFunctionProcessorTest.java
gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedAddressFunctionProcessorTest.java
gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedHostFunctionProcessorTest.java
gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceMappedUrlFunctionProcessorTest.java
gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServicePathFunctionProcessorTest.java
gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServicePortFunctionProcessorTest.java
gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceRegistryFunctionsTest.java
gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceSchemeFunctionProcessorTest.java
gateway-provider-rewrite-func-service-registry/src/test/java/org/apache/knox/gateway/svcregfunc/impl/ServiceUrlFunctionProcessorTest.java
gateway-provider-rewrite-step-encrypt-uri/src/main/java/org/apache/knox/gateway/encrypturi/impl/EncryptUriProcessor.java
gateway-provider-rewrite-step-encrypt-uri/src/test/java/org/apache/knox/gateway/encrypturi/impl/EncryptDecryptUriProcessorTest.java
gateway-provider-rewrite-step-secure-query/src/test/java/org/apache/knox/gateway/securequery/SecureQueryEncryptDecryptProcessorTest.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteFunctionDescriptorFactory.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletContextListener.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteServletEnvironment.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteStepDescriptorFactory.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/ext/ScopedMatcher.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/FrontendFunctionProcessor.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRequest.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteResponse.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteRulesDescriptorImpl.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteStepProcessorHolder.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteUtil.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/form/FormFilterReader.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlImportFunctionProcessor.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlInfixProcessor.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlPostfixProcessor.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/html/HtmlPrefixProcessor.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlFilterReader.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesExporter.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteRulesImporter.java
gateway-provider-rewrite/src/main/java/org/apache/knox/gateway/filter/rewrite/impl/xml/XmlUrlRewriteStreamFilter.java
gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/api/UrlRewriteProcessorTest.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/UrlRewriteContextImplTest.java
gateway-provider-rewrite/src/test/java/org/apache/knox/gateway/filter/rewrite/impl/UrlRewriteResponseTest.java
gateway-provider-security-authz-acls/src/main/java/org/apache/knox/gateway/filter/AclsAuthorizationFilter.java
gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/AbstractJWTFilter.java
gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTAccessTokenAssertionFilter.java
gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/JWTFederationFilter.java
gateway-provider-security-jwt/src/main/java/org/apache/knox/gateway/provider/federation/jwt/filter/SSOCookieFederationFilter.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/JWTFederationFilterTest.java
gateway-provider-security-jwt/src/test/java/org/apache/knox/gateway/provider/federation/SSOCookieProviderTest.java
gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/filter/Pac4jDispatcherFilter.java
gateway-provider-security-pac4j/src/main/java/org/apache/knox/gateway/pac4j/session/KnoxSessionStore.java
gateway-provider-security-preauth/src/main/java/org/apache/knox/gateway/preauth/filter/HeaderPreAuthFederationFilter.java
gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/deploy/impl/ShiroConfig.java
gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/deploy/impl/ShiroDeploymentContributor.java
gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/filter/ShiroSubjectIdentityAdapter.java
gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxLdapContextFactory.java
gateway-provider-security-shiro/src/main/java/org/apache/knox/gateway/shirorealm/KnoxLdapRealm.java
gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/filter/StrictTransportFilter.java
gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/filter/XContentTypeOptionsFilter.java
gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/filter/XFrameOptionsFilter.java
gateway-provider-security-webappsec/src/main/java/org/apache/knox/gateway/webappsec/filter/XSSProtectionFilter.java
gateway-provider-security-webappsec/src/test/java/org/apache/knox/gateway/webappsec/StrictTransportFilterTest.java
gateway-provider-security-webappsec/src/test/java/org/apache/knox/gateway/webappsec/XFrameOptionsFilterTest.java
gateway-provider-security-webappsec/src/test/java/org/apache/knox/gateway/webappsec/XSSProtectionFilterTest.java
gateway-server-xforwarded-filter/src/main/java/org/apache/knox/gateway/filter/CompositeEnumeration.java
gateway-server-xforwarded-filter/src/main/java/org/apache/knox/gateway/filter/XForwardedHeaderRequestWrapper.java
gateway-server/src/main/java/org/apache/knox/gateway/GatewayCommandLine.java
gateway-server/src/main/java/org/apache/knox/gateway/GatewayFilter.java
gateway-server/src/main/java/org/apache/knox/gateway/GatewayServer.java
gateway-server/src/main/java/org/apache/knox/gateway/GatewayServlet.java
gateway-server/src/main/java/org/apache/knox/gateway/config/impl/GatewayConfigImpl.java
gateway-server/src/main/java/org/apache/knox/gateway/deploy/DeploymentFactory.java
gateway-server/src/main/java/org/apache/knox/gateway/deploy/impl/ApplicationDeploymentContributor.java
gateway-server/src/main/java/org/apache/knox/gateway/descriptor/xml/XmlGatewayDescriptorExporter.java
gateway-server/src/main/java/org/apache/knox/gateway/descriptor/xml/XmlGatewayDescriptorImporter.java
gateway-server/src/main/java/org/apache/knox/gateway/dispatch/UrlConnectionDispatch.java
gateway-server/src/main/java/org/apache/knox/gateway/filter/BasicAuthChallengeFilter.java
gateway-server/src/main/java/org/apache/knox/gateway/filter/PortMappingHelperHandler.java
gateway-server/src/main/java/org/apache/knox/gateway/filter/RequestUpdateHandler.java
gateway-server/src/main/java/org/apache/knox/gateway/services/metrics/impl/DefaultMetricsService.java
gateway-server/src/main/java/org/apache/knox/gateway/services/registry/impl/DefaultServiceRegistryService.java
gateway-server/src/main/java/org/apache/knox/gateway/services/security/impl/DefaultAliasService.java
gateway-server/src/main/java/org/apache/knox/gateway/services/security/impl/DefaultCryptoService.java
gateway-server/src/main/java/org/apache/knox/gateway/services/security/impl/DefaultKeystoreService.java
gateway-server/src/main/java/org/apache/knox/gateway/services/security/impl/JettySSLService.java
gateway-server/src/main/java/org/apache/knox/gateway/services/topology/impl/DefaultTopologyService.java
gateway-server/src/main/java/org/apache/knox/gateway/topology/discovery/DefaultServiceDiscoveryConfig.java
gateway-server/src/main/java/org/apache/knox/gateway/topology/simple/ProviderConfigurationParser.java
gateway-server/src/main/java/org/apache/knox/gateway/topology/validation/TopologyValidator.java
gateway-server/src/main/java/org/apache/knox/gateway/util/KnoxCLI.java
gateway-server/src/main/java/org/apache/knox/gateway/websockets/GatewayWebsocketHandler.java
gateway-server/src/test/java/org/apache/knox/gateway/AuditLoggingTest.java
gateway-server/src/test/java/org/apache/knox/gateway/GatewayGlobalConfigTest.java
gateway-server/src/test/java/org/apache/knox/gateway/services/security/CryptoServiceTest.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/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/util/KnoxCLITest.java
gateway-server/src/test/java/org/apache/knox/gateway/websockets/BadUrlTest.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-admin/src/main/java/org/apache/knox/gateway/service/admin/TopologiesResource.java
gateway-service-health/src/main/java/org/apache/knox/gateway/service/health/MetricsResource.java
gateway-service-health/src/main/java/org/apache/knox/gateway/service/health/PingResource.java
gateway-service-knoxtoken/src/main/java/org/apache/knox/gateway/service/knoxtoken/TokenResource.java
gateway-service-nifi/src/main/java/org/apache/knox/gateway/dispatch/NiFiDispatch.java
gateway-service-nifi/src/main/java/org/apache/knox/gateway/dispatch/NiFiHaDispatch.java
gateway-service-nifi/src/main/java/org/apache/knox/gateway/dispatch/NiFiResponseUtil.java
gateway-service-remoteconfig/src/main/java/org/apache/knox/gateway/service/config/remote/zk/CuratorClientService.java
gateway-service-remoteconfig/src/main/java/org/apache/knox/gateway/service/config/remote/zk/RemoteConfigurationRegistryJAASConfig.java
gateway-service-remoteconfig/src/test/java/org/apache/knox/gateway/service/config/remote/util/RemoteRegistryConfigTestUtils.java
gateway-service-test/src/main/java/org/apache/knox/gateway/service/test/ServiceTestResource.java
gateway-shell/src/main/java/org/apache/knox/gateway/shell/AbstractJavaConsoleCredentialCollector.java
gateway-shell/src/main/java/org/apache/knox/gateway/shell/KnoxSession.java
gateway-shell/src/main/java/org/apache/knox/gateway/shell/KnoxSh.java
gateway-shell/src/main/java/org/apache/knox/gateway/shell/hbase/HBase.java
gateway-shell/src/main/java/org/apache/knox/gateway/shell/manager/DeployResourceRequest.java
gateway-shell/src/main/java/org/apache/knox/gateway/shell/manager/ListResourcesRequest.java
gateway-shell/src/main/java/org/apache/knox/gateway/shell/manager/ListTopologiesRequest.java
gateway-shell/src/main/java/org/apache/knox/gateway/shell/manager/ResourceType.java
gateway-shell/src/main/java/org/apache/knox/gateway/shell/manager/UndeployResourceRequest.java
gateway-spi/src/main/java/org/apache/knox/gateway/dispatch/AbstractGatewayDispatch.java
gateway-spi/src/main/java/org/apache/knox/gateway/dispatch/CappedBufferHttpEntity.java
gateway-spi/src/main/java/org/apache/knox/gateway/dispatch/DefaultHttpClientFactory.java
gateway-spi/src/main/java/org/apache/knox/gateway/dispatch/HadoopAuthCookieStore.java
gateway-spi/src/main/java/org/apache/knox/gateway/dispatch/InputStreamEntity.java
gateway-spi/src/main/java/org/apache/knox/gateway/dispatch/PartiallyRepeatableHttpEntity.java
gateway-spi/src/main/java/org/apache/knox/gateway/filter/AbstractGatewayFilter.java
gateway-spi/src/main/java/org/apache/knox/gateway/security/GroupPrincipal.java
gateway-spi/src/main/java/org/apache/knox/gateway/security/ImpersonatedPrincipal.java
gateway-spi/src/main/java/org/apache/knox/gateway/security/PrimaryPrincipal.java
gateway-spi/src/main/java/org/apache/knox/gateway/security/PromptUtils.java
gateway-spi/src/main/java/org/apache/knox/gateway/security/SubjectUtils.java
gateway-spi/src/main/java/org/apache/knox/gateway/security/UsernamePassword.java
gateway-spi/src/main/java/org/apache/knox/gateway/security/principal/SimplePrincipalMapper.java
gateway-spi/src/main/java/org/apache/knox/gateway/services/security/impl/BaseKeystoreService.java
gateway-spi/src/main/java/org/apache/knox/gateway/services/security/impl/CMFKeystoreService.java
gateway-spi/src/main/java/org/apache/knox/gateway/services/security/impl/CMFMasterService.java
gateway-spi/src/main/java/org/apache/knox/gateway/services/security/impl/ConfigurableEncryptor.java
gateway-spi/src/main/java/org/apache/knox/gateway/services/security/token/impl/JWTToken.java
gateway-spi/src/main/java/org/apache/knox/gateway/topology/Version.java
gateway-test-release-utils/src/main/java/org/apache/knox/gateway/GatewayTestConfig.java
gateway-test-release-utils/src/main/java/org/apache/knox/gateway/GatewayTestDriver.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-utils/src/main/java/org/apache/knox/test/TestUtils.java
gateway-test-utils/src/main/java/org/apache/knox/test/mock/MockRequestMatcher.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/GatewayBasicFuncTest.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/GatewayLdapDynamicGroupFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayLdapGroupFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayLdapPosixGroupFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayLocalServiceFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayPortMappingDisableFeatureTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayPortMappingFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewaySampleFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/GatewayUIFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/Knox242FuncTest.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/WebHdfsHaFuncTest.java
gateway-test/src/test/java/org/apache/knox/gateway/topology/monitor/RemoteConfigurationMonitorTest.java
gateway-util-common/src/main/java/org/apache/knox/gateway/audit/log4j/appender/JdbmQueue.java
gateway-util-common/src/main/java/org/apache/knox/gateway/audit/log4j/appender/JdbmStoreAndForwardAppender.java
gateway-util-common/src/main/java/org/apache/knox/gateway/audit/log4j/audit/Log4jAuditContext.java
gateway-util-common/src/main/java/org/apache/knox/gateway/audit/log4j/audit/Log4jAuditor.java
gateway-util-common/src/main/java/org/apache/knox/gateway/audit/log4j/correlation/Log4jCorrelationContext.java
gateway-util-common/src/main/java/org/apache/knox/gateway/util/CertificateUtils.java
gateway-util-common/src/main/java/org/apache/knox/gateway/util/HttpUtils.java
gateway-util-common/src/main/java/org/apache/knox/gateway/util/JsonPath.java
gateway-util-common/src/main/java/org/apache/knox/gateway/util/JsonUtils.java
gateway-util-common/src/main/java/org/apache/knox/gateway/util/Urls.java
gateway-util-common/src/main/java/org/apache/knox/gateway/util/X500PrincipalParser.java
gateway-util-common/src/test/java/org/apache/knox/gateway/util/JsonPathTest.java
gateway-util-configinjector/src/main/java/org/apache/knox/gateway/config/impl/DefaultConfigurationInjector.java
gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/FuncTest.java
gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/OptionalTest.java
gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/impl/BeanConfigurationAdapterDescriptorTest.java
gateway-util-configinjector/src/test/java/org/apache/knox/gateway/config/impl/BeanConfigurationAdapterTest.java
gateway-util-launcher/src/main/java/org/apache/knox/gateway/launcher/Config.java
gateway-util-launcher/src/main/java/org/apache/knox/gateway/launcher/Invoker.java
gateway-util-launcher/src/main/java/org/apache/knox/gateway/launcher/Launcher.java
gateway-util-launcher/src/test/java/org/apache/knox/gateway/launcher/ConfigTest.java
gateway-util-urltemplate/src/main/java/org/apache/knox/gateway/util/urltemplate/Builder.java
gateway-util-urltemplate/src/main/java/org/apache/knox/gateway/util/urltemplate/Expander.java
gateway-util-urltemplate/src/main/java/org/apache/knox/gateway/util/urltemplate/Function.java
gateway-util-urltemplate/src/main/java/org/apache/knox/gateway/util/urltemplate/Matcher.java
gateway-util-urltemplate/src/main/java/org/apache/knox/gateway/util/urltemplate/Parser.java
gateway-util-urltemplate/src/main/java/org/apache/knox/gateway/util/urltemplate/Segment.java
gateway-util-urltemplate/src/main/java/org/apache/knox/gateway/util/urltemplate/Template.java
gateway-util-urltemplate/src/main/java/org/apache/knox/gateway/util/urltemplate/Token.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/FunctionTest.java
gateway-util-urltemplate/src/test/java/org/apache/knox/gateway/util/urltemplate/RewriterTest.java

index 6146fdc..f098b75 100644 (file)
@@ -147,9 +147,7 @@ class AmbariCluster implements ServiceDiscovery.Cluster {
 
     @Override
     public List<String> getServiceURLs(String serviceName, Map<String, String> serviceParams) {
-        List<String> urls = new ArrayList<>();
-        urls.addAll(urlFactory.create(serviceName, serviceParams));
-        return urls;
+        return new ArrayList<>(urlFactory.create(serviceName, serviceParams));
     }
 
     @Override
@@ -253,7 +251,7 @@ class AmbariCluster implements ServiceDiscovery.Cluster {
         }
 
         private String applyPortToEnsemble(String ensemble, String port) {
-            String updatedEnsemble = "";
+            StringBuilder updatedEnsemble = new StringBuilder();
 
             String[] hosts = ensemble.split(",");
             int index = 0;
@@ -262,13 +260,13 @@ class AmbariCluster implements ServiceDiscovery.Cluster {
                 if (portIndex > 0) {
                     host = host.substring(0, portIndex);
                 }
-                updatedEnsemble += host + ":" + port;
+                updatedEnsemble.append(host).append(":").append(port);
                 if (++index < hosts.length) {
-                    updatedEnsemble += ",";
+                    updatedEnsemble.append(",");
                 }
             }
 
-            return updatedEnsemble;
+            return updatedEnsemble.toString();
         }
     }
 }
index f694ee8..7e7ceba 100644 (file)
@@ -23,14 +23,14 @@ import java.util.Map;
 
 class AmbariComponent {
 
-    private String clusterName = null;
-    private String serviceName = null;
-    private String name        = null;
-    private String version     = null;
+    private String clusterName;
+    private String serviceName;
+    private String name;
+    private String version;
 
     private List<String> hostNames = new ArrayList<>();
 
-    private Map<String, String> properties = null;
+    private Map<String, String> properties;
 
     AmbariComponent(String              name,
                     String              version,
index 2d61280..141df87 100644 (file)
@@ -76,7 +76,7 @@ class AmbariConfigurationMonitor implements ClusterConfigurationMonitor {
 
     PollingConfigAnalyzer internalMonitor;
 
-    GatewayConfig gatewayConfig = null;
+    GatewayConfig gatewayConfig;
 
     static String getType() {
         return TYPE;
@@ -407,8 +407,7 @@ class AmbariConfigurationMonitor implements ClusterConfigurationMonitor {
         configVersionsLock.readLock().lock();
         try {
             for (Entry<String, Map<String, Map<String, String>>> ambariClusterConfigVersion : ambariClusterConfigVersions.entrySet()) {
-                List<String> clusterNames = new ArrayList<>();
-                clusterNames.addAll(ambariClusterConfigVersion.getValue().keySet());
+              List<String> clusterNames = new ArrayList<>(ambariClusterConfigVersion.getValue().keySet());
                 result.put(ambariClusterConfigVersion.getKey(), clusterNames);
             }
         } finally {
@@ -469,7 +468,7 @@ class AmbariConfigurationMonitor implements ClusterConfigurationMonitor {
         private static final int DEFAULT_POLLING_INTERVAL = 60;
 
         // Polling interval in seconds
-        private int interval = DEFAULT_POLLING_INTERVAL;
+        private int interval;
 
         private AmbariConfigurationMonitor delegate;
 
index 83a7542..1af52ae 100644 (file)
@@ -19,11 +19,11 @@ package org.apache.knox.gateway.topology.discovery.ambari;
 
 class PropertyEqualsHandler implements ConditionalValueHandler {
 
-    private String serviceName                        = null;
-    private String propertyName                       = null;
-    private String propertyValue                      = null;
-    private ConditionalValueHandler affirmativeResult = null;
-    private ConditionalValueHandler negativeResult    = null;
+    private String serviceName;
+    private String propertyName;
+    private String propertyValue;
+    private ConditionalValueHandler affirmativeResult;
+    private ConditionalValueHandler negativeResult;
 
     PropertyEqualsHandler(String                  serviceName,
                           String                  propertyName,
index e897604..fa9fa39 100644 (file)
@@ -29,7 +29,7 @@ public class ServiceURLFactory {
 
   private Map<String, ServiceURLCreator> urlCreators = new HashMap<>();
 
-  private ServiceURLCreator defaultURLCreator = null;
+  private ServiceURLCreator defaultURLCreator;
 
 
   private ServiceURLFactory(AmbariCluster cluster) {
@@ -69,16 +69,13 @@ public class ServiceURLFactory {
    * @return A List of service URL strings; the list may be empty.
    */
   public List<String> create(String service, Map<String, String> serviceParams) {
-    List<String> urls = new ArrayList<>();
 
     ServiceURLCreator creator = urlCreators.get(service);
     if (creator == null) {
       creator = defaultURLCreator;
     }
 
-    urls.addAll(creator.create(service, serviceParams));
-
-    return urls;
+    return new ArrayList<>(creator.create(service, serviceParams));
   }
 
 }
index 4d8864f..25eedc6 100644 (file)
@@ -104,7 +104,7 @@ class ServiceURLPropertyConfig {
             for (int i=0; i < serviceNodes.getLength(); i++) {
                 Node serviceNode = serviceNodes.item(i);
                 String serviceName = serviceNode.getAttributes().getNamedItem(ATTR_NAME).getNodeValue();
-                properties.put(serviceName, new HashMap<String, Property>());
+                properties.put(serviceName, new HashMap<>());
 
                 Node urlPatternNode = (Node) URL_PATTERN.evaluate(serviceNode, XPathConstants.NODE);
                 if (urlPatternNode != null) {
@@ -252,7 +252,7 @@ class ServiceURLPropertyConfig {
         String service;
         String serviceConfig;
         String value;
-        ConditionalValueHandler conditionHandler = null;
+        ConditionalValueHandler conditionHandler;
 
         private Property(String type,
                          String propertyName,
index 449a2a5..fcdbcad 100644 (file)
@@ -149,7 +149,7 @@ public class AmbariConfigurationMonitorTest {
 //            System.out.println("Cluster config changed: " + cname + " @ " + src);
             // Record the notification
             Integer notificationCount  = changeNotifications.computeIfAbsent(src, s -> new HashMap<>())
-                                                            .computeIfAbsent(cname, c -> Integer.valueOf(0));
+                                                            .computeIfAbsent(cname, c -> 0);
             changeNotifications.get(src).put(cname, (notificationCount+=1));
 
             // Update the config version
index 1c31444..2166337 100644 (file)
@@ -26,7 +26,7 @@ import java.util.List;
 
 public class TestMessageLogger implements MessageLogger {
 
-  public final List<TestMessageRecord> records = Collections.synchronizedList( new ArrayList<TestMessageRecord>() );
+  public final List<TestMessageRecord> records = Collections.synchronizedList(new ArrayList<>() );
 
   public final String name;
 
index c551366..77bf113 100644 (file)
@@ -85,7 +85,7 @@ public class ResourcesInvoker implements InvocationHandler {
     return pattern;
   }
 
-  protected static final String getDefaultPattern( final Method method ) {
+  protected static String getDefaultPattern(final Method method ) {
     final String prefix = method.getName();
     String suffix;
     final int params = method.getParameterTypes().length;
index aff38c7..f0fe690 100644 (file)
@@ -19,7 +19,6 @@ package org.apache.knox.gateway.ha.provider;
 
 import org.apache.knox.gateway.ha.provider.impl.DefaultURLManager;
 
-import java.util.Iterator;
 import java.util.ServiceLoader;
 
 public class URLManagerLoader {
@@ -28,10 +27,8 @@ public class URLManagerLoader {
     if (config != null) {
       ServiceLoader<URLManager> loader = ServiceLoader.load(URLManager.class);
       if ( loader != null ) {
-        Iterator<URLManager> iterator = loader.iterator();
-        while ( iterator.hasNext() ) {
-          URLManager urlManager = iterator.next();
-          if ( urlManager.supportsConfig(config) ) {
+        for (URLManager urlManager : loader) {
+          if (urlManager.supportsConfig(config)) {
             urlManager.setConfig(config);
             return urlManager;
           }
index 6107d2f..c1005ee 100644 (file)
@@ -72,7 +72,7 @@ public abstract class BaseZookeeperURLManager implements URLManager {
     }
 
     String zookeeperEnsemble = config.getZookeeperEnsemble();
-    return zookeeperEnsemble != null && (zookeeperEnsemble.trim().length() > 0);
+    return zookeeperEnsemble != null && (!zookeeperEnsemble.trim().isEmpty());
   }
 
   @Override
@@ -198,7 +198,7 @@ public abstract class BaseZookeeperURLManager implements URLManager {
    * @return Apache HttpClient
    */
   private CloseableHttpClient buildHttpClient() {
-    CloseableHttpClient client = null;
+    CloseableHttpClient client;
 
     // Construct a HttpClient with short term timeout
     RequestConfig.Builder requestBuilder = RequestConfig.custom()
index 91f7971..a260774 100644 (file)
@@ -78,7 +78,7 @@ public class HBaseZookeeperURLManager extends BaseZookeeperURLManager {
   @Override
   protected String getServiceName() {
     return "WEBHBASE";
-  };
+  }
 
   @Override
   protected String getZookeeperNamespace() {
@@ -149,14 +149,11 @@ public class HBaseZookeeperURLManager extends BaseZookeeperURLManager {
   private String constructURL(String serverInfo) {
     String scheme = "http";
 
-    StringBuffer buffer = new StringBuffer();
-    buffer.append(scheme);
-    buffer.append("://");
     // Strip off the host name
-    buffer.append(serverInfo.substring(0, serverInfo.indexOf(',')));
-    buffer.append(":");
-    buffer.append(PORT_NUMBER);
-
-    return buffer.toString();
+    return scheme +
+               "://" +
+               serverInfo.substring(0, serverInfo.indexOf(',')) +
+               ":" +
+               PORT_NUMBER;
   }
 }
index e7855b3..112d3df 100644 (file)
@@ -56,7 +56,7 @@ public class HS2ZookeeperURLManager extends DefaultURLManager {
     }
     String zookeeperEnsemble = config.getZookeeperEnsemble();
     String zookeeperNamespace = config.getZookeeperNamespace();
-    if ( zookeeperEnsemble != null && zookeeperNamespace != null && zookeeperEnsemble.trim().length() > 0 && zookeeperNamespace.trim().length() > 0) {
+    if ( zookeeperEnsemble != null && zookeeperNamespace != null && !zookeeperEnsemble.trim().isEmpty() && !zookeeperNamespace.trim().isEmpty()) {
       return true;
     }
     return false;
@@ -116,15 +116,13 @@ public class HS2ZookeeperURLManager extends DefaultURLManager {
         }
       }
     }
-    StringBuffer buffer = new StringBuffer();
-    buffer.append(scheme);
-    buffer.append("://");
-    buffer.append(host);
-    buffer.append(":");
-    buffer.append(port);
-    buffer.append("/");
-    buffer.append(httpPath);
-    return buffer.toString();
+    return scheme +
+               "://" +
+               host +
+               ":" +
+               port +
+               "/" +
+               httpPath;
   }
 
   @Override
index 0637cec..4ee4dd4 100644 (file)
@@ -52,19 +52,19 @@ public abstract class HaDescriptorFactory implements HaServiceConfigConstants {
       int failoverSleep = DEFAULT_FAILOVER_SLEEP;
       int maxRetryAttempts = DEFAULT_MAX_RETRY_ATTEMPTS;
       int retrySleep = DEFAULT_RETRY_SLEEP;
-      if (enabledValue != null && enabledValue.trim().length() > 0) {
+      if (enabledValue != null && !enabledValue.trim().isEmpty()) {
          enabled = Boolean.parseBoolean(enabledValue);
       }
-      if (maxFailoverAttemptsValue != null && maxFailoverAttemptsValue.trim().length() > 0) {
+      if (maxFailoverAttemptsValue != null && !maxFailoverAttemptsValue.trim().isEmpty()) {
          maxFailoverAttempts = Integer.parseInt(maxFailoverAttemptsValue);
       }
-      if (failoverSleepValue != null && failoverSleepValue.trim().length() > 0) {
+      if (failoverSleepValue != null && !failoverSleepValue.trim().isEmpty()) {
          failoverSleep = Integer.parseInt(failoverSleepValue);
       }
-      if (maxRetryAttemptsValue != null && maxRetryAttemptsValue.trim().length() > 0) {
+      if (maxRetryAttemptsValue != null && !maxRetryAttemptsValue.trim().isEmpty()) {
          maxRetryAttempts = Integer.parseInt(maxRetryAttemptsValue);
       }
-      if (retrySleepValue != null && retrySleepValue.trim().length() > 0) {
+      if (retrySleepValue != null && !retrySleepValue.trim().isEmpty()) {
          retrySleep = Integer.parseInt(retrySleepValue);
       }
       DefaultHaServiceConfig serviceConfig = new DefaultHaServiceConfig(serviceName);
index 59727f7..f1ec065 100644 (file)
@@ -68,10 +68,7 @@ public class HaDescriptorManager implements HaDescriptorConstants {
 
          Transformer t = XmlUtils.getTransformer( true, true, 2, false );
          XmlUtils.writeXml( document, writer, t );
-      } catch (ParserConfigurationException e) {
-         LOG.failedToWriteHaDescriptor(e);
-         throw new IOException(e);
-      } catch (TransformerException e) {
+      } catch (ParserConfigurationException | TransformerException e) {
          LOG.failedToWriteHaDescriptor(e);
          throw new IOException(e);
       }
@@ -96,14 +93,11 @@ public class HaDescriptorManager implements HaDescriptorConstants {
                descriptor.addServiceConfig(config);
             }
          }
-      } catch (ParserConfigurationException e) {
-         LOG.failedToLoadHaDescriptor(e);
-         throw new IOException(e);
-      } catch (SAXException e) {
+      } catch (ParserConfigurationException | SAXException e) {
          LOG.failedToLoadHaDescriptor(e);
          throw new IOException(e);
       }
-      return descriptor;
+     return descriptor;
    }
 
 }
index f09fc15..a94834b 100644 (file)
@@ -82,7 +82,7 @@ public class KafkaZookeeperURLManager extends BaseZookeeperURLManager {
   @Override
   protected String getServiceName() {
     return "KAFKA";
-  };
+  }
 
   // -------------------------------------------------------------------------------------
   // Private methods
@@ -131,7 +131,7 @@ public class KafkaZookeeperURLManager extends BaseZookeeperURLManager {
   private String constructURL(String serverInfo) throws ParseException {
     String scheme = "http";
 
-    StringBuffer buffer = new StringBuffer();
+    StringBuilder buffer = new StringBuilder();
 
     buffer.append(scheme);
     buffer.append("://");
index 24a9e53..582fc14 100644 (file)
@@ -62,7 +62,7 @@ public class SOLRZookeeperURLManager extends BaseZookeeperURLManager {
   @Override
   protected String getServiceName() {
     return "SOLR";
-  };
+  }
 
   // -------------------------------------------------------------------------------------
   // Private methods
@@ -106,10 +106,8 @@ public class SOLRZookeeperURLManager extends BaseZookeeperURLManager {
   private String constructURL(String serverInfo) {
     String scheme = "http";
 
-    StringBuffer buffer = new StringBuffer();
-    buffer.append(scheme);
-    buffer.append("://");
-    buffer.append(serverInfo.replace("_", "/"));
-    return buffer.toString();
+    return scheme +
+               "://" +
+               serverInfo.replace("_", "/");
   }
 }
index e948ca9..e3f3ba4 100644 (file)
@@ -306,34 +306,34 @@ public class HaProviderDeploymentContributorTest {
 
       builder.append(HaServiceConfigConstants.CONFIG_PARAM_ENABLED);
       builder.append(HaServiceConfigConstants.CONFIG_PAIR_DELIMITER);
-      builder.append(String.valueOf(enabled));
+      builder.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(String.valueOf(maxRetryAttempts));
+         builder.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(String.valueOf(retrySleep));
+         builder.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(String.valueOf(maxFailoverAttempts));
+         builder.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(String.valueOf(failoverSleep));
+         builder.append(failoverSleep);
       }
 
       if (zooKeeperNamespace != null) {
index 27491c5..b5b2a3f 100644 (file)
@@ -39,6 +39,7 @@ public class DefaultHaProviderTest {
          new DefaultHaProvider(null);
          fail("provider construction should have failed with null descriptor");
       } catch (IllegalArgumentException e) {
+        // Expected exception
       }
       HaDescriptor descriptor = new DefaultHaDescriptor();
       HaProvider provider = new DefaultHaProvider(descriptor);
index f6dbae6..c210128 100644 (file)
@@ -88,14 +88,14 @@ public abstract class AbstractIdentityAssertionFilter extends
   protected void continueChainAsPrincipal(HttpServletRequestWrapper request, ServletResponse response,
       FilterChain chain, String mappedPrincipalName, String[] groups) throws IOException,
       ServletException {
-        Subject subject = null;
-        Principal impersonationPrincipal = null;
-        Principal primaryPrincipal = null;
+        Subject subject;
+        Principal impersonationPrincipal;
+        Principal primaryPrincipal;
 
         // get the current subject and determine whether we need another doAs with
         // an impersonatedPrincipal and/or mapped group principals
         boolean impersonationNeeded = false;
-        boolean groupsMapped = false;
+        boolean groupsMapped;
 
         // look up the current Java Subject and assosciated group principals
         Subject currentSubject = Subject.getSubject(AccessController.getContext());
@@ -182,8 +182,8 @@ public abstract class AbstractIdentityAssertionFilter extends
       auditor.audit( Action.IDENTITY_MAPPING, mappedPrincipalName, ResourceType.PRINCIPAL,
           ActionOutcome.SUCCESS, RES.groupsList( Arrays.toString( groups ) ) );
 
-      for (int i = 0; i < groups.length; i++) {
-        subject.getPrincipals().add(new GroupPrincipal(groups[i]));
+      for (String group : groups) {
+        subject.getPrincipals().add(new GroupPrincipal(group));
       }
     }
   }
index db75424..9e9987b 100644 (file)
@@ -107,11 +107,9 @@ public class CommonIdentityAssertionFilter extends AbstractIdentityAssertionFilt
       ServletRequest request, String mappedPrincipalName) {
     // wrap the request so that the proper principal is returned
     // from request methods
-    IdentityAsserterHttpServletRequestWrapper wrapper =
-        new IdentityAsserterHttpServletRequestWrapper(
-        (HttpServletRequest)request,
+    return new IdentityAsserterHttpServletRequestWrapper(
+        (HttpServletRequest) request,
         mappedPrincipalName);
-    return wrapper;
   }
 
   protected String[] mapGroupPrincipalsBase(String mappedPrincipalName, Subject subject) {
index b4395d8..71251ca 100644 (file)
@@ -129,9 +129,9 @@ private static SpiGatewayMessages log = MessagesFactory.get( SpiGatewayMessages.
 
   private Map<String, List<String>> getParams( String qString )
       throws UnsupportedEncodingException {
-    Map<String, List<String>> params = null;
+    Map<String, List<String>> params;
     if (getMethod().equals("GET")) {
-      if (qString != null && qString.length() > 0) {
+      if (qString != null && !qString.isEmpty()) {
         params = HttpUtils.splitQuery( qString );
       }
       else {
@@ -139,7 +139,7 @@ private static SpiGatewayMessages log = MessagesFactory.get( SpiGatewayMessages.
       }
     }
     else {
-      if (qString == null || qString.length() == 0) {
+      if (qString == null || qString.isEmpty()) {
         return null;
       }
       else {
@@ -259,7 +259,7 @@ private static SpiGatewayMessages log = MessagesFactory.get( SpiGatewayMessages.
     StringBuilder sb = new StringBuilder();
     for( Map.Entry<String,List<String>> entry : map.entrySet() ) {
       String name = entry.getKey();
-      if( name != null && name.length() > 0 ) {
+      if( name != null && !name.isEmpty()) {
         List<String> values = entry.getValue();
         if( values == null || values.isEmpty() ) {
           sb.append( entry.getKey() );
index 7290e0d..4ff9efb 100644 (file)
@@ -257,7 +257,7 @@ public class IdentityAssertionHttpServletRequestWrapperTest {
     assertThat( s, is( "null-values" ) );
 
     m = new HashMap<>();
-    m.put( "no-values", new ArrayList<String>(0) );
+    m.put( "no-values", new ArrayList<>(0) );
     s = IdentityAsserterHttpServletRequestWrapper.urlEncode( m, StandardCharsets.UTF_8.name() );
     assertThat( s, is( "no-values" ) );
 
index 1af3a43..b6f699b 100644 (file)
@@ -21,7 +21,6 @@ import org.apache.knox.gateway.filter.rewrite.api.UrlRewriteFunctionDescriptor;
 import org.apache.knox.gateway.identityasserter.common.function.UsernameFunctionDescriptor;
 import org.junit.Test;
 
-import java.util.Iterator;
 import java.util.ServiceLoader;
 
 import static org.hamcrest.CoreMatchers.is;
@@ -39,10 +38,8 @@ public class UsernameFunctionDescriptorTest {
   @Test
   public void testServiceLoader() throws Exception {
     ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class );
-    Iterator iterator = loader.iterator();
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof UsernameFunctionDescriptor ) {
+    for (Object object : loader) {
+      if (object instanceof UsernameFunctionDescriptor) {
         return;
       }
     }
index 785751f..3d9876b 100644 (file)
@@ -54,10 +54,9 @@ import java.nio.charset.StandardCharsets;
 import java.security.PrivilegedActionException;
 import java.security.PrivilegedExceptionAction;
 import java.util.ArrayDeque;
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.EnumSet;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.Map;
 import java.util.Queue;
 import java.util.ServiceLoader;
@@ -77,8 +76,7 @@ public class UsernameFunctionProcessorTest {
 
   private static URL getTestResource( String name ) {
     name = UsernameFunctionProcessorTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
-    URL url = ClassLoader.getSystemResource( name );
-    return url;
+    return ClassLoader.getSystemResource( name );
   }
 
   public void setUp( String username, Map<String,String> initParams ) throws Exception {
@@ -139,7 +137,7 @@ public class UsernameFunctionProcessorTest {
   public void testResolve() throws Exception {
     final UsernameFunctionProcessor processor = new UsernameFunctionProcessor();
     assertThat( processor.resolve( null, null ), nullValue() );
-    assertThat( processor.resolve( null, Arrays.asList( "test-input" ) ), contains( "test-input" ) );
+    assertThat( processor.resolve( null, Collections.singletonList("test-input")), contains( "test-input" ) );
     Subject subject = new Subject();
     subject.getPrincipals().add( new PrimaryPrincipal( "test-username" ) );
     subject.setReadOnly();
@@ -147,7 +145,7 @@ public class UsernameFunctionProcessorTest {
       @Override
       public Object run() throws Exception {
         assertThat( processor.resolve( null, null ), contains( "test-username" ) );
-        assertThat( processor.resolve( null, Arrays.asList( "test-ignored" ) ), contains( "test-username" ) );
+        assertThat( processor.resolve( null, Collections.singletonList("test-ignored")), contains( "test-username" ) );
         return null;
       }
     } );
@@ -156,10 +154,8 @@ public class UsernameFunctionProcessorTest {
   @Test
   public void testServiceLoader() throws Exception {
     ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionProcessor.class );
-    Iterator iterator = loader.iterator();
-    while( iterator.hasNext() ) {
-      Object object = iterator.next();
-      if( object instanceof UsernameFunctionProcessor ) {
+    for (Object object : loader) {
+      if (object instanceof UsernameFunctionProcessor) {
         return;
       }
     }
index 391f4a4..95026a3 100644 (file)
@@ -94,7 +94,7 @@ public class HadoopGroupProviderFilter extends CommonIdentityAssertionFilter {
   public String[] mapGroupPrincipals(final String mappedPrincipalName,
                                      final Subject subject) {
     /* return the groups as seen by Hadoop */
-    String[] groups = null;
+    String[] groups;
     try {
       final List<String> groupList = hadoopGroups
           .getGroups(mappedPrincipalName);
index 273c103..72d4606 100644 (file)
@@ -93,8 +93,8 @@ public class DefaultIdentityAssertionFilterTest {
 
   private boolean groupFoundIn(String expected, String[] mappedGroups) {
     if (mappedGroups == null) return false;
-    for(int i = 0; i < mappedGroups.length; i++) {
-      if (mappedGroups[i].equals(expected)) {
+    for (String mappedGroup : mappedGroups) {
+      if (mappedGroup.equals(expected)) {
         return true;
       }
     }
index e405ae4..6eee0b3 100644 (file)
@@ -36,7 +36,7 @@ import org.easymock.EasyMock;
 import org.junit.Test;
 
 import java.net.URL;
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.ServiceLoader;
 
@@ -75,10 +75,10 @@ public class HostmapFunctionProcessorTest {
 
     UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
     EasyMock.expect( environment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();
-    EasyMock.expect( environment.resolve( "cluster.name" ) ).andReturn( Arrays.asList( "test-cluster-name" ) ).anyTimes();
+    EasyMock.expect( environment.resolve( "cluster.name" ) ).andReturn(Collections.singletonList("test-cluster-name")).anyTimes();
     EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
     Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-inbound-host" ) ).anyTimes();
+    EasyMock.expect( resolver.resolve( "host" ) ).andReturn(Collections.singletonList("test-inbound-host")).anyTimes();
     EasyMock.replay( gatewayServices, hm, hms, environment, resolver );
 
     UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
@@ -104,7 +104,7 @@ public class HostmapFunctionProcessorTest {
     UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
     EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
     Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-internal-host" ) ).anyTimes();
+    EasyMock.expect( resolver.resolve( "host" ) ).andReturn(Collections.singletonList("test-internal-host")).anyTimes();
     EasyMock.replay( environment, resolver );
 
     UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
@@ -138,7 +138,7 @@ public class HostmapFunctionProcessorTest {
     UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
     EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
     Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-internal-host" ) ).anyTimes();
+    EasyMock.expect( resolver.resolve( "host" ) ).andReturn(Collections.singletonList("test-internal-host")).anyTimes();
     EasyMock.replay( environment, resolver );
 
     UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
@@ -172,7 +172,7 @@ public class HostmapFunctionProcessorTest {
     UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
     EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
     Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-inbound-unmapped-host" ) ).anyTimes();
+    EasyMock.expect( resolver.resolve( "host" ) ).andReturn(Collections.singletonList("test-inbound-unmapped-host")).anyTimes();
     EasyMock.replay( environment, resolver );
 
     UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
@@ -199,7 +199,7 @@ public class HostmapFunctionProcessorTest {
     UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
     EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
     Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-inbound-host" ) ).anyTimes();
+    EasyMock.expect( resolver.resolve( "host" ) ).andReturn(Collections.singletonList("test-inbound-host")).anyTimes();
     EasyMock.replay( environment, resolver );
 
     UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
@@ -225,7 +225,7 @@ public class HostmapFunctionProcessorTest {
     UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
     EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
     Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-inbound-host" ) ).anyTimes();
+    EasyMock.expect( resolver.resolve( "host" ) ).andReturn(Collections.singletonList("test-inbound-host")).anyTimes();
     EasyMock.replay( environment, resolver );
 
     UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
@@ -251,7 +251,7 @@ public class HostmapFunctionProcessorTest {
     UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
     EasyMock.expect( environment.getResource( "/WEB-INF/hostmap.txt" ) ).andReturn( configUrl ).anyTimes();
     Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "host" ) ).andReturn( Arrays.asList( "test-inbound-host" ) ).anyTimes();
+    EasyMock.expect( resolver.resolve( "host" ) ).andReturn(Collections.singletonList("test-inbound-host")).anyTimes();
     EasyMock.replay( environment, resolver );
 
     UrlRewriteRulesDescriptor descriptor = UrlRewriteRulesDescriptorFactory.create();
index 2fe2adf..bd7f987 100644 (file)
@@ -44,7 +44,7 @@ public class InboundUrlFunctionProcessor
 
   @Override
   public List<String> resolve( UrlRewriteContext context, List<String> parameters ) throws Exception {
-      if( parameters == null || parameters.size() == 0 ) {
+      if( parameters == null || parameters.isEmpty()) {
         return Collections.emptyList();
       } else {
         switch( context.getDirection() ) {
index 5981437..9851b82 100644 (file)
@@ -29,7 +29,7 @@ import org.easymock.EasyMock;
 import org.junit.Before;
 import org.junit.Test;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.ServiceLoader;
 
@@ -133,8 +133,8 @@ public class ServiceAddressFunctionProcessorTest {
     ServiceAddressFunctionProcessor func = new ServiceAddressFunctionProcessor();
     func.initialize( env, desc );
 
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-host:777" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("test-service")), contains( "test-host:777" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("invalid-test-service")), contains( "invalid-test-service" ) );
     assertThat( func.resolve( ctx, null ), nullValue() );
 
     func.destroy();
index 46f4063..042792e 100644 (file)
@@ -29,7 +29,7 @@ import org.easymock.EasyMock;
 import org.junit.Before;
 import org.junit.Test;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.ServiceLoader;
 
@@ -134,8 +134,8 @@ public class ServiceHostFunctionProcessorTest {
     ServiceHostFunctionProcessor func = new ServiceHostFunctionProcessor();
     func.initialize( env, desc );
 
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-host" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("test-service")), contains( "test-host" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("invalid-test-service")), contains( "invalid-test-service" ) );
     assertThat( func.resolve( ctx, null ), nullValue() );
 
     func.destroy();
index 11384fe..62a39a8 100644 (file)
@@ -32,7 +32,7 @@ import org.easymock.EasyMock;
 import org.junit.Before;
 import org.junit.Test;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.ServiceLoader;
 
@@ -146,8 +146,8 @@ public class ServiceMappedAddressFunctionProcessorTest {
     ServiceMappedAddressFunctionProcessor func = new ServiceMappedAddressFunctionProcessor();
     func.initialize( env, desc );
 
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-internal-host:777" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("test-service")), contains( "test-internal-host:777" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("invalid-test-service")), contains( "invalid-test-service" ) );
     assertThat( func.resolve( ctx, null ), nullValue() );
 
     func.destroy();
index 1b79f9b..4b869f5 100644 (file)
@@ -32,7 +32,7 @@ import org.easymock.EasyMock;
 import org.junit.Before;
 import org.junit.Test;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.ServiceLoader;
 
@@ -146,8 +146,8 @@ public class ServiceMappedHostFunctionProcessorTest {
     ServiceMappedHostFunctionProcessor func = new ServiceMappedHostFunctionProcessor();
     func.initialize( env, desc );
 
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-internal-host" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("test-service")), contains( "test-internal-host" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("invalid-test-service")), contains( "invalid-test-service" ) );
     assertThat( func.resolve( ctx, null ), nullValue() );
 
     func.destroy();
index 5fc6546..dd978bd 100644 (file)
@@ -32,7 +32,7 @@ import org.easymock.EasyMock;
 import org.junit.Before;
 import org.junit.Test;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.ServiceLoader;
 
@@ -147,8 +147,8 @@ public class ServiceMappedUrlFunctionProcessorTest {
     ServiceMappedUrlFunctionProcessor func = new ServiceMappedUrlFunctionProcessor();
     func.initialize( env, desc );
 
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-scheme://test-internal-host:777/test-path" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("test-service")), contains( "test-scheme://test-internal-host:777/test-path" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("invalid-test-service")), contains( "invalid-test-service" ) );
     assertThat( func.resolve( ctx, null ), nullValue() );
 
     func.destroy();
index a66bcf0..0a96d99 100644 (file)
@@ -29,7 +29,7 @@ import org.easymock.EasyMock;
 import org.junit.Before;
 import org.junit.Test;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.ServiceLoader;
 
@@ -134,7 +134,7 @@ public class ServicePathFunctionProcessorTest {
     func.initialize( env, desc );
 
 //    assertThat( func.resolve( ctx, "test-service" ), is( "/test-path" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("invalid-test-service")), contains( "invalid-test-service" ) );
 //    assertThat( func.resolve( ctx, null ), nullValue() );
 
     func.destroy();
index 7b25957..d9b6d1f 100644 (file)
@@ -29,7 +29,7 @@ import org.easymock.EasyMock;
 import org.junit.Before;
 import org.junit.Test;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.ServiceLoader;
 
@@ -133,8 +133,8 @@ public class ServicePortFunctionProcessorTest {
     ServicePortFunctionProcessor func = new ServicePortFunctionProcessor();
     func.initialize( env, desc );
 
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "777" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("test-service")), contains( "777" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("invalid-test-service")), contains( "invalid-test-service" ) );
     assertThat( func.resolve( ctx, null ), nullValue() );
 
     func.destroy();
index 081eeeb..b014589 100644 (file)
@@ -71,8 +71,7 @@ public class ServiceRegistryFunctionsTest {
 
   private static URL getTestResource( String name ) {
     name = ServiceRegistryFunctionsTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
-    URL url = ClassLoader.getSystemResource( name );
-    return url;
+    return ClassLoader.getSystemResource( name );
   }
 
   public void setUp( String username, Map<String,String> initParams ) throws Exception {
index 49c9872..0aad5eb 100644 (file)
@@ -29,7 +29,7 @@ import org.easymock.EasyMock;
 import org.junit.Before;
 import org.junit.Test;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.ServiceLoader;
 
@@ -133,8 +133,8 @@ public class ServiceSchemeFunctionProcessorTest {
     ServiceSchemeFunctionProcessor func = new ServiceSchemeFunctionProcessor();
     func.initialize( env, desc );
 
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-scheme" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("test-service")), contains( "test-scheme" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("invalid-test-service")), contains( "invalid-test-service" ) );
     assertThat( func.resolve( ctx, null ), nullValue() );
 
     func.destroy();
index ad146ca..8a8d05b 100644 (file)
@@ -32,7 +32,7 @@ import org.easymock.EasyMock;
 import org.junit.Before;
 import org.junit.Test;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.ServiceLoader;
 
@@ -146,8 +146,8 @@ public class ServiceUrlFunctionProcessorTest {
     ServiceUrlFunctionProcessor func = new ServiceUrlFunctionProcessor();
     func.initialize( env, desc );
 
-    assertThat( func.resolve( ctx, Arrays.asList( "test-service" ) ), contains( "test-scheme://test-host:777/test-path" ) );
-    assertThat( func.resolve( ctx, Arrays.asList( "invalid-test-service" ) ), contains( "invalid-test-service" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("test-service")), contains( "test-scheme://test-host:777/test-path" ) );
+    assertThat( func.resolve( ctx, Collections.singletonList("invalid-test-service")), contains( "invalid-test-service" ) );
     assertThat( func.resolve( ctx, null ), nullValue() );
 
     func.destroy();
index 959c27b..ee9ca85 100644 (file)
@@ -19,7 +19,7 @@ package org.apache.knox.gateway.encrypturi.impl;
 
 import java.io.UnsupportedEncodingException;
 import java.nio.charset.StandardCharsets;
-import java.util.Arrays;
+import java.util.Collections;
 
 import org.apache.commons.codec.binary.Base64;
 import org.apache.knox.gateway.encrypturi.EncryptStepContextParams;
@@ -66,7 +66,7 @@ public class EncryptUriProcessor
       if( resolvedTemplate != null && !resolvedTemplate.isEmpty() ) {
         String endcoedUrl = encode( resolvedTemplate );
         EncryptStepContextParams params = new EncryptStepContextParams();
-        params.addParam( param, Arrays.asList( endcoedUrl ) );
+        params.addParam( param, Collections.singletonList(endcoedUrl));
         context.addParameters( params );
         return UrlRewriteStepStatus.SUCCESS;
       }
index 2ee3c22..89bf8ea 100644 (file)
@@ -31,7 +31,7 @@ import org.easymock.Capture;
 import org.easymock.EasyMock;
 import org.junit.Test;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.ServiceLoader;
 
@@ -93,8 +93,8 @@ public class EncryptDecryptUriProcessorTest {
     UrlRewriteContext encContext = EasyMock.createNiceMock( UrlRewriteContext.class );
 
     EncryptStepContextParams hostPortParams = new EncryptStepContextParams();
-    hostPortParams.addParam( "host", Arrays.asList( "host.yarn.com" ) );
-    hostPortParams.addParam( "port", Arrays.asList( "8088" ) );
+    hostPortParams.addParam( "host", Collections.singletonList("host.yarn.com"));
+    hostPortParams.addParam( "port", Collections.singletonList("8088"));
     EasyMock.expect( encContext.getParameters() ).andReturn( hostPortParams );
 
 
@@ -131,8 +131,8 @@ public class EncryptDecryptUriProcessorTest {
     UrlRewriteContext decContext = EasyMock.createNiceMock( UrlRewriteContext.class );
 
     EncryptStepContextParams encryptedParams = new EncryptStepContextParams();
-    encryptedParams.addParam( decParam, Arrays.asList( encryptedAdrress ) ); //Value was encrypted by EncryptUriProcessor
-    encryptedParams.addParam( "foo1", Arrays.asList( "test" ) );
+    encryptedParams.addParam( decParam, Collections.singletonList(encryptedAdrress)); //Value was encrypted by EncryptUriProcessor
+    encryptedParams.addParam( "foo1", Collections.singletonList("test"));
     EasyMock.expect( decContext.getParameters() ).andReturn( encryptedParams );
 
     Capture<EncryptStepContextParams> decodedValue = Capture.newInstance();
index 211f98d..9a75c27 100644 (file)
@@ -32,7 +32,7 @@ import org.easymock.EasyMock;
 import org.junit.Test;
 import org.junit.Assert;
 
-import java.util.Arrays;
+import java.util.Collections;
 
 import static org.hamcrest.CoreMatchers.is;
 import static org.hamcrest.CoreMatchers.notNullValue;
@@ -88,7 +88,7 @@ public class SecureQueryEncryptDecryptProcessorTest {
     EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();
     EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster-name" ).anyTimes();
     Params decParams = EasyMock.createNiceMock( Params.class );
-    EasyMock.expect( decParams.resolve( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( Arrays.asList("test-cluster-name") ).anyTimes();
+    EasyMock.expect( decParams.resolve( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn(Collections.singletonList("test-cluster-name")).anyTimes();
     UrlRewriteContext decContext = EasyMock.createNiceMock( UrlRewriteContext.class );
     EasyMock.expect( decContext.getCurrentUrl() ).andReturn( encTemplate.getValue() );
     EasyMock.expect( decContext.getParameters() ).andReturn( decParams );
@@ -155,7 +155,7 @@ public class SecureQueryEncryptDecryptProcessorTest {
     EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE ) ).andReturn( gatewayServices ).anyTimes();
     EasyMock.expect( decEnvironment.getAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( "test-cluster-name" ).anyTimes();
     Params decParams = EasyMock.createNiceMock( Params.class );
-    EasyMock.expect( decParams.resolve( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn( Arrays.asList("test-cluster-name") ).anyTimes();
+    EasyMock.expect( decParams.resolve( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE ) ).andReturn(Collections.singletonList("test-cluster-name")).anyTimes();
     UrlRewriteContext decContext = EasyMock.createNiceMock( UrlRewriteContext.class );
     EasyMock.expect( decContext.getCurrentUrl() ).andReturn( encTemplate.getValue() );
     EasyMock.expect( decContext.getParameters() ).andReturn( decParams );
index 15b81dd..507b7a7 100644 (file)
@@ -35,9 +35,7 @@ public abstract class UrlRewriteFunctionDescriptorFactory {
     try {
       Class<? extends UrlRewriteFunctionDescriptor> descriptorClass = MAP.get( name );
       return (T)descriptorClass.newInstance();
-    } catch( InstantiationException e ) {
-      throw new IllegalArgumentException( name );
-    } catch( IllegalAccessException e ) {
+    } catch( InstantiationException | IllegalAccessException e ) {
       throw new IllegalArgumentException( name );
     }
   }
index d7eb05f..631cecc 100644 (file)
@@ -43,7 +43,7 @@ public class UrlRewriteServletContextListener implements ServletContextListener
 
   @Override
   public void contextInitialized( ServletContextEvent event ) {
-    UrlRewriteRulesDescriptor descriptor = null;
+    UrlRewriteRulesDescriptor descriptor;
     try {
       URL url = locateDescriptor( event.getServletContext() );
       descriptor = loadDescriptor( url );
index cc1c125..09b5f36 100644 (file)
@@ -20,7 +20,7 @@ package org.apache.knox.gateway.filter.rewrite.api;
 import javax.servlet.ServletContext;
 import java.net.MalformedURLException;
 import java.net.URL;
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
 
 public class UrlRewriteServletEnvironment implements UrlRewriteEnvironment {
@@ -33,14 +33,12 @@ public class UrlRewriteServletEnvironment implements UrlRewriteEnvironment {
 
   @Override
   public URL getResource( String name ) throws MalformedURLException {
-    URL url = context.getResource( name );
-    return url;
+    return context.getResource( name );
   }
 
   @Override
   public <T> T getAttribute( String name ) {
-    T attribute = (T)context.getAttribute( name );
-    return attribute;
+    return (T)context.getAttribute( name );
   }
 
   @Override
@@ -48,7 +46,7 @@ public class UrlRewriteServletEnvironment implements UrlRewriteEnvironment {
     List<String> values = null;
     String value = context.getInitParameter( name );
     if( value != null ) {
-      values = Arrays.asList( value );
+      values = Collections.singletonList(value);
     }
     return values;
   }
index 5047bee..1b3d309 100644 (file)
@@ -34,9 +34,7 @@ public abstract class UrlRewriteStepDescriptorFactory {
     try {
       Class<? extends UrlRewriteStepDescriptor> descriptorClass = MAP.get( type );
       return (T)descriptorClass.newInstance();
-    } catch( InstantiationException e ) {
-      throw new IllegalArgumentException( type );
-    } catch( IllegalAccessException e ) {
+    } catch( InstantiationException | IllegalAccessException e ) {
       throw new IllegalArgumentException( type );
     }
   }
index 716c582..350e5c5 100644 (file)
@@ -65,7 +65,7 @@ public class ScopedMatcher extends Matcher<UrlRewriteRuleProcessorHolder> {
         matches.add(match);
       }
     }
-    if (matches.size() == 0) {
+    if (matches.isEmpty()) {
       return null;
     }
     if (matches.size() == 1) {
@@ -115,7 +115,7 @@ public class ScopedMatcher extends Matcher<UrlRewriteRuleProcessorHolder> {
   private Matcher<UrlRewriteRuleProcessorHolder> getMatcher(Template template, UrlRewriteRuleProcessorHolder holder) {
     String scope = holder.getScope();
     if (!matchers.containsKey(scope)) {
-      matchers.put(scope, new Matcher<UrlRewriteRuleProcessorHolder>());
+      matchers.put(scope, new Matcher<>());
     }
 
     return matchers.get(scope);
index c45a3d0..219a8cf 100644 (file)
@@ -89,8 +89,7 @@ public class FrontendFunctionProcessor implements UrlRewriteFunctionProcessor<Fr
     if( resolver == null ) {
       throw new IllegalArgumentException( RES.invalidFrontendFunctionParameter( parameter ) );
     }
-    List<String> results = resolver.resolve( context, parameters );
-    return results;
+    return resolver.resolve( context, parameters );
   }
 
   private static class ParamResolver implements UrlRewriteResolver {
index f3aab7d..a369830 100644 (file)
@@ -50,7 +50,7 @@ import java.net.URISyntaxException;
 import java.net.URL;
 import java.net.URLDecoder;
 import java.nio.charset.StandardCharsets;
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.Enumeration;
 import java.util.List;
 
@@ -91,7 +91,7 @@ public class UrlRewriteRequest extends GatewayRequestWrapper implements Resolver
     Template urlTemplate;
     //KNOX-439[
     //StringBuffer urlString = super.getRequestURL();
-    StringBuffer urlString = new StringBuffer( 128 );
+    StringBuilder urlString = new StringBuilder( 128 );
     urlString.append( getScheme() );
     urlString.append( "://" );
     urlString.append( getServerName() );
@@ -185,7 +185,7 @@ public class UrlRewriteRequest extends GatewayRequestWrapper implements Resolver
 
   @Override
   public String getHeader( String name ) {
-    String value = null;
+    String value;
     if (name.equalsIgnoreCase("Host")) {
       String uri = getRequestURI();
       try {
@@ -217,7 +217,7 @@ public class UrlRewriteRequest extends GatewayRequestWrapper implements Resolver
 
   @Override
   public List<String> resolve( String name ) {
-    return Arrays.asList( config.getInitParameter( name ) );
+    return Collections.singletonList(config.getInitParameter(name));
   }
 
   private class EnumerationRewriter implements Enumeration<String> {
@@ -265,7 +265,7 @@ public class UrlRewriteRequest extends GatewayRequestWrapper implements Resolver
       UrlRewriteFilterContentDescriptor filterContentConfig = getRewriteFilterConfig( bodyFilterName, mimeType );
       if (filterContentConfig != null) {
         String asType = filterContentConfig.asType();
-        if ( asType != null && asType.trim().length() > 0 ) {
+        if ( asType != null && !asType.trim().isEmpty()) {
           mimeType = MimeTypes.create(asType, getCharacterEncoding());
         }
       }
index c8516b9..783e9d5 100644 (file)
@@ -153,7 +153,7 @@ public class UrlRewriteResponse extends GatewayResponseWrapper implements Params
         getRewriteFilterConfig(rewriter.getConfig(), bodyFilterName, mimeType);
     if (filterContentConfig != null) {
       String asType = filterContentConfig.asType();
-      if ( asType != null && asType.trim().length() > 0 ) {
+      if ( asType != null && !asType.trim().isEmpty()) {
         mimeType = MimeTypes.create(asType, getCharacterEncoding());
       }
     }
@@ -215,15 +215,15 @@ public class UrlRewriteResponse extends GatewayResponseWrapper implements Params
   @SuppressWarnings( "unchecked" )
   public List<String> resolve( String name ) {
     if( name.startsWith( REQUEST_PARAM_PREFIX ) ) {
-      return Arrays.asList( getRequestParam( name.substring( REQUEST_PARAM_PREFIX.length() ) ) );
+      return Collections.singletonList(getRequestParam(name.substring(REQUEST_PARAM_PREFIX.length())));
     } else if ( name.startsWith( GATEWAY_PARAM_PREFIX ) ) {
-      return Arrays.asList( getGatewayParam( name.substring( GATEWAY_PARAM_PREFIX.length() ) ) );
+      return Collections.singletonList(getGatewayParam(name.substring(GATEWAY_PARAM_PREFIX.length())));
     } else if ( name.startsWith( CLUSTER_PARAM_PREFIX ) ) {
-      return Arrays.asList( getClusterParam( name.substring( GATEWAY_PARAM_PREFIX.length() ) ) );
+      return Collections.singletonList(getClusterParam(name.substring(GATEWAY_PARAM_PREFIX.length())));
     } else if ( name.startsWith( INBOUND_QUERY_PARAM_PREFIX ) ) {
       return getInboundQueryParam(name.substring(INBOUND_QUERY_PARAM_PREFIX.length()));
     } else {
-      return Arrays.asList( config.getInitParameter( name ) );
+      return Collections.singletonList(config.getInitParameter(name));
     }
   }
 
index 33afb45..2d31fbf 100644 (file)
@@ -74,7 +74,7 @@ public class UrlRewriteRulesDescriptorImpl implements UrlRewriteRulesDescriptor
   public void addRule( UrlRewriteRuleDescriptor rule ) {
     ruleList.add( rule );
     String name = rule.name();
-    if( name != null && name.length() > 0 ) {
+    if( name != null && !name.isEmpty()) {
       ruleMap.put( rule.name(), rule );
     }
   }
@@ -87,8 +87,7 @@ public class UrlRewriteRulesDescriptorImpl implements UrlRewriteRulesDescriptor
   @Override
   @SuppressWarnings("unchecked")
   public <T extends UrlRewriteFunctionDescriptor<?>> T getFunction( String name ) {
-    T descriptor = (T)funcMap.get( name );
-    return descriptor;
+    return (T)funcMap.get( name );
   }
 
   @Override
@@ -101,8 +100,7 @@ public class UrlRewriteRulesDescriptorImpl implements UrlRewriteRulesDescriptor
 
   @SuppressWarnings("unchecked")
   protected <T extends UrlRewriteFunctionDescriptor<?>> T newFunction( String name ) {
-    T descriptor = UrlRewriteFunctionDescriptorFactory.create( name );
-    return descriptor;
+    return UrlRewriteFunctionDescriptorFactory.create( name );
   }
 
   protected void addFunction( UrlRewriteFunctionDescriptor descriptor ) {
index 51d627f..87291f6 100644 (file)
@@ -28,7 +28,6 @@ import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteStepStatus;
 import org.apache.knox.gateway.i18n.messages.MessagesFactory;
 
 import java.util.ArrayList;
-import java.util.Iterator;
 import java.util.List;
 
 public class UrlRewriteStepProcessorHolder implements UrlRewriteStepProcessor {
@@ -72,12 +71,10 @@ public class UrlRewriteStepProcessorHolder implements UrlRewriteStepProcessor {
       UrlRewriteFlowDescriptor flowDescriptor = (UrlRewriteFlowDescriptor)descriptor;
       List<UrlRewriteStepDescriptor> stepList = flowDescriptor.steps();
       if( stepList != null && !stepList.isEmpty() ) {
-        Iterator<UrlRewriteStepDescriptor> stepIterator = stepList.iterator();
-        while( stepIterator.hasNext() ) {
-          UrlRewriteStepDescriptor stepDescriptor = stepIterator.next();
+        for (UrlRewriteStepDescriptor stepDescriptor : stepList) {
           UrlRewriteStepProcessorHolder stepProcessor = new UrlRewriteStepProcessorHolder();
-          stepProcessor.initialize( environment, stepDescriptor );
-          childProcessors.add( stepProcessor );
+          stepProcessor.initialize(environment, stepDescriptor);
+          childProcessors.add(stepProcessor);
         }
       }
     }
index c77843d..b7b665c 100644 (file)
@@ -60,7 +60,7 @@ public class UrlRewriteUtil {
 
   public static String filterJavaScript( String inputValue, UrlRewriteFilterContentDescriptor config,
       UrlRewriteFilterReader filterReader, UrlRewriteFilterPathDescriptor.Compiler<Pattern> regexCompiler ) {
-    StringBuffer tbuff = new StringBuffer();
+    StringBuilder tbuff = new StringBuilder();
     StringBuffer sbuff = new StringBuffer();
     sbuff.append( inputValue );
     if( config != null && !config.getSelectors().isEmpty() ) {
index 35ade84..76d8dd5 100644 (file)
@@ -79,7 +79,7 @@ public class FormFilterReader extends Reader {
   private void processPair() throws IOException {
     FormPair pair = parser.getCurrentPair();
     String name = pair.getName();
-    String value = pair.getValue();
+    String value;
     String rule = UrlRewriteUtil.pickFirstRuleWithEqualsIgnoreCasePathMatch( config, name );
     try {
       value = filterValue( name, pair.getValue(), rule );
index 83fa735..5687a40 100644 (file)
@@ -25,7 +25,7 @@ import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteFunctionProcessorFa
 import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
 import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
 
 /**
@@ -79,7 +79,7 @@ public class HtmlImportFunctionProcessor implements UrlRewriteFunctionProcessor<
       parameters = parameters.subList(1, parameters.size());
     }
     List<String> frontendValues = frontend.resolve(context, parameters);
-    StringBuffer buffer = new StringBuffer(IMPORT_LITERAL);
+    StringBuilder buffer = new StringBuilder(IMPORT_LITERAL);
     buffer.append(" ");
     buffer.append(prefix);
     if ( frontendValues != null && !frontendValues.isEmpty() ) {
@@ -87,7 +87,7 @@ public class HtmlImportFunctionProcessor implements UrlRewriteFunctionProcessor<
         buffer.append(value);
       }
     }
-    return Arrays.asList(buffer.toString());
+    return Collections.singletonList(buffer.toString());
   }
 
   @Override
index f986963..f55aa43 100644 (file)
@@ -24,7 +24,7 @@ import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteFunctionProcessorFa
 import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
 import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
 
 /**
@@ -90,15 +90,15 @@ public class HtmlInfixProcessor
 
     final List<String> frontendValues = frontend.resolve(context, parameters);
 
-    final StringBuffer buffer = new StringBuffer();
+    final StringBuilder buffer = new StringBuilder();
     buffer.append(prefix);
-    if (frontendValues != null && frontendValues.size() > 0) {
+    if (frontendValues != null && !frontendValues.isEmpty()) {
       for (final String value : frontendValues) {
         buffer.append(value);
       }
     }
     buffer.append(postfix);
 
-    return Arrays.asList(buffer.toString());
+    return Collections.singletonList(buffer.toString());
   }
 }
index 4915cb6..72e3664 100644 (file)
@@ -24,7 +24,7 @@ import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteFunctionProcessorFa
 import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
 import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
 
 /**
@@ -90,14 +90,14 @@ public class HtmlPostfixProcessor
 
     final List<String> frontendValues = frontend.resolve(context, parameters);
 
-    final StringBuffer buffer = new StringBuffer();
-    if (frontendValues != null && frontendValues.size() > 0) {
+    final StringBuilder buffer = new StringBuilder();
+    if (frontendValues != null && !frontendValues.isEmpty()) {
       for (final String value : frontendValues) {
         buffer.append(value);
       }
     }
     buffer.append(postfix);
 
-    return Arrays.asList(buffer.toString());
+    return Collections.singletonList(buffer.toString());
   }
 }
index 303e9c2..aaf9803 100644 (file)
@@ -24,7 +24,7 @@ import org.apache.knox.gateway.filter.rewrite.impl.UrlRewriteFunctionProcessorFa
 import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteContext;
 import org.apache.knox.gateway.filter.rewrite.spi.UrlRewriteFunctionProcessor;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
 
 /**
@@ -98,7 +98,7 @@ public class HtmlPrefixProcessor
 
     final List<String> frontendValues = frontend.resolve(context, parameters);
 
-    final StringBuffer buffer = new StringBuffer();
+    final StringBuilder buffer = new StringBuilder();
     buffer.append(prefix);
     if (frontendValues != null && !frontendValues.isEmpty()) {
       for (final String value : frontendValues) {
@@ -106,6 +106,6 @@ public class HtmlPrefixProcessor
       }
     }
 
-    return Arrays.asList(buffer.toString());
+    return Collections.singletonList(buffer.toString());
   }
 }
index be67dac..379d9f0 100644 (file)
@@ -125,9 +125,7 @@ public abstract class XmlFilterReader extends Reader {
         try {
           XMLEvent event = parser.nextEvent();
           processEvent( event );
-        } catch( IOException e ) {
-          throw e;
-        } catch( RuntimeException e ) {
+        } catch( IOException | RuntimeException e ) {
           throw e;
         } catch ( Exception e ) {
           throw new RuntimeException( e );
@@ -370,7 +368,7 @@ public abstract class XmlFilterReader extends Reader {
         Object node = path.evaluate( level.scopeNode, XPathConstants.NODE );
         if( node != null ) {
           UrlRewriteFilterDetectDescriptor detect = (UrlRewriteFilterDetectDescriptor)selector;
-          String value = null;
+          String value;
           if( node instanceof Element ) {
             Element element = (Element)node;
             value = element.getTextContent();
index d6f6453..d4c8d80 100644 (file)
@@ -91,17 +91,9 @@ public class XmlUrlRewriteRulesExporter implements UrlRewriteRulesExporter, XmlR
 
       XmlUtils.writeXml( document, writer );
 
-    } catch( ParserConfigurationException e ) {
+    } catch( ParserConfigurationException | TransformerException e ) {
       throw new IOException( e );
-    } catch( TransformerException e ) {
-      throw new IOException( e );
-    } catch( InvocationTargetException e ) {
-      LOG.failedToWriteRulesDescriptor( e );
-    } catch( NoSuchMethodException e ) {
-      LOG.failedToWriteRulesDescriptor( e );
-    } catch( IntrospectionException e ) {
-      LOG.failedToWriteRulesDescriptor( e );
-    } catch( IllegalAccessException e ) {
+    } catch( InvocationTargetException | IllegalAccessException | IntrospectionException | NoSuchMethodException e ) {
       LOG.failedToWriteRulesDescriptor( e );
     }
   }
index a061d22..0d2b68b 100644 (file)
@@ -43,8 +43,7 @@ public class XmlUrlRewriteRulesImporter implements UrlRewriteRulesImporter {
     Digester digester = loader.newDigester( new ExtendedBaseRules() );
     digester.setValidating( false );
     try {
-      UrlRewriteRulesDescriptor rules = digester.parse( reader );
-      return rules;
+      return digester.parse( reader );
     } catch( SAXException e ) {
       throw new IOException( e );
     }
index 568a0f6..15e2a25 100644 (file)
@@ -57,9 +57,7 @@ public class XmlUrlRewriteStreamFilter implements UrlRewriteStreamFilter {
       return new ReaderInputStream(
           new XmlUrlRewriteFilterReader(
               new InputStreamReader( stream, encoding ), rewriter, resolver, direction, config ), encoding );
-    } catch( ParserConfigurationException e ) {
-      throw new IOException( e );
-    } catch( XMLStreamException e ) {
+    } catch( ParserConfigurationException | XMLStreamException e ) {
       throw new IOException( e );
     }
   }
index 5728cb6..3a31894 100644 (file)
@@ -59,8 +59,7 @@ public class UrlRewriteProcessorTest {
 
   private static InputStream getTestResourceStream( String name ) throws IOException {
     URL url = getTestResourceUrl( name );
-    InputStream stream = url.openStream();
-    return stream;
+    return url.openStream();
   }
 
   private static Reader getTestResourceReader( String name ) throws IOException {
index 0552b00..2c067bc 100644 (file)
@@ -42,8 +42,7 @@ public class UrlRewriteServletContextListenerTest {
 
   private static URL getTestResource( String name ) {
     name = UrlRewriteServletFilterTest.class.getName().replaceAll( "\\.", "/" ) + "/" + name;
-    URL url = ClassLoader.getSystemResource( name );
-    return url;
+    return ClassLoader.getSystemResource( name );
   }
 
   @Before
index 0a25a3a..df5572a 100644 (file)
@@ -267,7 +267,7 @@ public class UrlRewriteServletFilterTest {
   public void testInboundXmlBodyRewrite() throws Exception {
     setUp( null );
     String input = "<root attribute=\"http://mock-host:1/test-input-path\">http://mock-host:1/test-input-path</root>";
-    String output = null;
+    String output;
     if(System.getProperty("java.vendor").contains("IBM")){
       output = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><root attribute=\"http://mock-host:1/test-output-path-1\">http://mock-host:1/test-output-path-1</root>";
     }else {
index 80ab1d0..9c8ae91 100644 (file)
@@ -27,7 +27,7 @@ import org.apache.knox.gateway.util.urltemplate.Template;
 import org.easymock.EasyMock;
 import org.junit.Test;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -42,10 +42,10 @@ public class UrlRewriteContextImplTest {
   public void testResolve() throws Exception {
 
     UrlRewriteEnvironment environment = EasyMock.createNiceMock( UrlRewriteEnvironment.class );
-    EasyMock.expect( environment.resolve( "test-env-param-name" ) ).andReturn( Arrays.asList( "test-env-param-value" ) ).anyTimes();
+    EasyMock.expect( environment.resolve( "test-env-param-name" ) ).andReturn(Collections.singletonList("test-env-param-value")).anyTimes();
 
     Resolver resolver = EasyMock.createNiceMock( Resolver.class );
-    EasyMock.expect( resolver.resolve( "test-ctx-param-name" ) ).andReturn( Arrays.asList( "test-ctx-param-value" ) );
+    EasyMock.expect( resolver.resolve( "test-ctx-param-name" ) ).andReturn(Collections.singletonList("test-ctx-param-value"));
 
     EasyMock.replay( environment, resolver );
 
index 927d22b..4d643b3 100644 (file)
@@ -144,7 +144,7 @@ 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 = null, output = null;
+    OutputStream outStream, output;
     InputStream inStream = null, input = null;
     try {
       outStream = isGzip ? new GZIPOutputStream( new FileOutputStream( inputFile ) ) : new FileOutputStream( inputFile );
index 6701198..29dc38b 100644 (file)
@@ -53,8 +53,8 @@ public class AclsAuthorizationFilter implements Filter {
   private String resourceRole = null;
   private String aclProcessingMode = null;
   private AclParser parser = new AclParser();
-  private ArrayList<String> adminGroups = new ArrayList<>();;
-  private ArrayList<String> adminUsers = new ArrayList<>();;
+  private ArrayList<String> adminGroups = new ArrayList<>();
+  private ArrayList<String> adminUsers = new ArrayList<>();
 
   @Override
   public void init(FilterConfig filterConfig) throws ServletException {
@@ -120,13 +120,13 @@ public class AclsAuthorizationFilter implements Filter {
 
     // before enforcing acls check whether there are no acls defined
     // which would mean that there are no restrictions
-    if (parser.users.size() == 0 && parser.groups.size() == 0 && parser.ipv.getIPAddresses().size() == 0) {
+    if (parser.users.isEmpty() && parser.groups.isEmpty() && parser.ipv.getIPAddresses().isEmpty()) {
       return true;
     }
 
-    boolean userAccess = false;
+    boolean userAccess;
     boolean groupAccess = false;
-    boolean ipAddrAccess = false;
+    boolean ipAddrAccess;
 
     Subject subject = Subject.getSubject(AccessController.getContext());
     Principal primaryPrincipal = (Principal)subject.getPrincipals(PrimaryPrincipal.class).toArray()[0];
@@ -178,7 +178,7 @@ public class AclsAuthorizationFilter implements Filter {
   }
 
   private boolean checkRemoteIpAcls(String remoteAddr) {
-    boolean allowed = false;
+    boolean allowed;
     if (remoteAddr == null) {
       return false;
     }
@@ -207,7 +207,7 @@ public class AclsAuthorizationFilter implements Filter {
   }
 
   boolean checkGroupAcls(Object[] userGroups) {
-    boolean allowed = false;
+    boolean allowed;
     if (userGroups == null) {
       return false;
     }
@@ -225,8 +225,8 @@ public class AclsAuthorizationFilter implements Filter {
 
   private boolean hasAllowedPrincipal(List<String> allowed, Object[] userGroups) {
     boolean rc = false;
-    for (int i = 0; i < userGroups.length; i++) {
-      if (allowed.contains(((Principal)userGroups[i]).getName())) {
+    for (Object userGroup : userGroups) {
+      if (allowed.contains(((Principal) userGroup).getName())) {
         rc = true;
         break;
       }
index 7639a11..2ad4c1b 100644 (file)
@@ -229,8 +229,7 @@ public abstract class AbstractJWTFilter implements Filter {
     // To modify the Principals Set, the caller must have AuthPermission("modifyPrincipals").
     // To modify the public credential Set, the caller must have AuthPermission("modifyPublicCredentials").
     // To modify the private credential Set, the caller must have AuthPermission("modifyPrivateCredentials").
-    javax.security.auth.Subject subject = new javax.security.auth.Subject(true, principals, emptySet, emptySet);
-    return subject;
+    return new Subject(true, principals, emptySet, emptySet);
   }
 
   protected boolean validateToken(HttpServletRequest request, HttpServletResponse response,
index 3af06be..c4de8ab 100644 (file)
@@ -71,7 +71,7 @@ public class JWTAccessTokenAssertionFilter extends AbstractIdentityAssertionFilt
   @Override
   public void doFilter(ServletRequest request, ServletResponse response,
       FilterChain chain) throws IOException, ServletException {
-    String jsonResponse = null;
+    String jsonResponse;
 
     String header = ((HttpServletRequest) request).getHeader("Authorization");
     if (header != null && header.startsWith(BEARER)) {
@@ -147,7 +147,7 @@ public class JWTAccessTokenAssertionFilter extends AbstractIdentityAssertionFilt
         return principalName;
       }
     };
-    JWT token = null;
+    JWT token;
     try {
       token = authority.issueToken(p, serviceName, "RS256", expires);
       // Coverity CID 1327961
index 4624caa..1f40d57 100644 (file)
@@ -75,7 +75,7 @@ public class JWTFederationFilter extends AbstractJWTFilter {
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
       throws IOException, ServletException {
     String header = ((HttpServletRequest) request).getHeader("Authorization");
-    String wireToken = null;
+    String wireToken;
     if (header != null && header.startsWith(BEARER)) {
       // what follows the bearer designator should be the JWT token being used to request or as an access token
       wireToken = header.substring(BEARER.length());
index 05743ee..bf6ad94 100644 (file)
@@ -100,7 +100,7 @@ private String gatewayPath;
   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
       throws IOException, ServletException {
-    String wireToken = null;
+    String wireToken;
     HttpServletRequest req = (HttpServletRequest) request;
 
     String loginURL = constructLoginURL(req);
@@ -185,10 +185,9 @@ private String gatewayPath;
     if (authenticationProviderUrl.contains("?")) {
       delimiter = "&";
     }
-    String loginURL = authenticationProviderUrl + delimiter
+    return authenticationProviderUrl + delimiter
         + ORIGINAL_URL_QUERY_PARAM
         + request.getRequestURL().append(getOriginalQueryString(request));
-    return loginURL;
   }
 
   /**
@@ -198,9 +197,9 @@ private String gatewayPath;
    * @return url that is based on KnoxSSO endpoint
    */
   public String deriveDefaultAuthenticationProviderUrl(HttpServletRequest request) {
-    String scheme = null;
-    String host = null;
-    int port = 0;
+    String scheme;
+    String host;
+    int port;
     if (!beingProxied(request)) {
       scheme = request.getScheme();
       host = request.getServerName();
index 387b274..9712ca8 100644 (file)
@@ -580,7 +580,7 @@ public abstract class AbstractJWTFilterTest  {
       handler.doFilter(request, response, chain);
       Assert.assertTrue("doFilterCalled should not be false.", chain.doFilterCalled);
       Set<PrimaryPrincipal> principals = chain.subject.getPrincipals(PrimaryPrincipal.class);
-      Assert.assertTrue("No PrimaryPrincipal", principals.size() > 0);
+      Assert.assertTrue("No PrimaryPrincipal", !principals.isEmpty());
       Assert.assertEquals("Not the expected principal", "alice", ((Principal)principals.toArray()[0]).getName());
     } catch (ServletException se) {
       fail("Should NOT have thrown a ServletException.");
@@ -726,7 +726,7 @@ public abstract class AbstractJWTFilterTest  {
   }
 
   protected static class TestFilterConfig implements FilterConfig {
-    Properties props = null;
+    Properties props;
 
     public TestFilterConfig(Properties props) {
       this.props = props;
index db95a8d..e0da4f1 100644 (file)
@@ -214,7 +214,7 @@ public class SSOCookieProviderTest extends AbstractJWTFilterTest {
   @Override
   protected String getVerificationPemProperty() {
     return SSOCookieFederationFilter.SSO_VERIFICATION_PEM;
-  };
+  }
 
   private static class TestSSOCookieFederationProvider extends SSOCookieFederationFilter {
     public String testConstructLoginURL(HttpServletRequest req) {
@@ -224,6 +224,6 @@ public class SSOCookieProviderTest extends AbstractJWTFilterTest {
     public void setTokenService(JWTokenAuthority ts) {
       authority = ts;
     }
-  };
+  }
 
 }
index 516dc5d..78c2449 100644 (file)
@@ -152,7 +152,7 @@ public class Pac4jDispatcherFilter implements Filter {
       final PropertiesConfigFactory propertiesConfigFactory = new PropertiesConfigFactory(pac4jCallbackUrl, properties);
       config = propertiesConfigFactory.build();
       final List<Client> clients = config.getClients().getClients();
-      if (clients == null || clients.size() == 0) {
+      if (clients == null || clients.isEmpty()) {
         log.atLeastOnePac4jClientMustBeDefined();
         throw new ServletException("At least one pac4j client must be defined.");
       }
index c1f4cb0..bce82ac 100644 (file)
@@ -74,7 +74,7 @@ public class KnoxSessionStore implements SessionStore {
     }
 
     private Serializable uncompressDecryptBase64(final String v) {
-        if (v != null && v.length() > 0) {
+        if (v != null && !v.isEmpty()) {
             byte[] bytes = Base64.decodeBase64(v);
             EncryptionResult result = EncryptionResult.fromByteArray(bytes);
             byte[] clear = cryptoService.decryptForCluster(this.clusterName,
index 15bc657..2cd6235 100644 (file)
@@ -56,8 +56,8 @@ public class HeaderPreAuthFederationFilter extends AbstractPreAuthFederationFilt
       String headers = request.getHeader(groupHeaderName);
       if (headers != null) {
         String[] groups = headers.split(",");
-        for (int i = 0; i < groups.length; i++) {
-          principals.add(new GroupPrincipal(groups[i]));
+        for (String group : groups) {
+          principals.add(new GroupPrincipal(group));
         }
       }
     }
index 638b89b..f282d06 100644 (file)
@@ -29,9 +29,9 @@ public class ShiroConfig {
 
   public ShiroConfig(Provider provider, String clusterName) {
     Map<String, String> params = provider.getParams();
-    String name = null;
-    String sectionName = null;
-    String value = null;
+    String name;
+    String sectionName;
+    String value;
     for(Entry<String, String> entry : params.entrySet()) {
       int sectionDot = entry.getKey().indexOf('.');
       if (sectionDot > 0) {
index 84c81d5..b379d36 100644 (file)
@@ -73,7 +73,7 @@ public class ShiroDeploymentContributor extends ProviderDeploymentContributorBas
     SessionConfigType<WebAppDescriptor> sessionConfig = context.getWebAppDescriptor().createSessionConfig();
     Map<String, String> params = provider.getParams();
     String sts = params.get( SESSION_TIMEOUT );
-    if( sts != null && sts.trim().length() != 0 ) {
+    if( sts != null && !sts.trim().isEmpty()) {
       st = Integer.parseInt( sts.trim() );
     }
     if( st <= 0 ) {
index 6da6170..a98ace9 100644 (file)
@@ -72,9 +72,9 @@ public class ShiroSubjectIdentityAdapter implements Filter {
   }
 
   private static class CallableChain implements Callable<Void> {
-    private FilterChain chain = null;
-    ServletRequest request = null;
-    ServletResponse response = null;
+    private FilterChain chain;
+    ServletRequest request;
+    ServletResponse response;
 
     CallableChain(ServletRequest request, ServletResponse response, FilterChain chain) {
       this.request = request;
@@ -106,7 +106,7 @@ public class ShiroSubjectIdentityAdapter implements Filter {
       String sourceUri = (String)request.getAttribute( AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME );
       auditor.audit( Action.AUTHENTICATION , sourceUri, ResourceType.URI, ActionOutcome.SUCCESS );
 
-      Set<String> userGroups = null;
+      Set<String> userGroups;
       // map ldap groups saved in session to Java Subject GroupPrincipal(s)
       if (SecurityUtils.getSubject().getSession().getAttribute(SUBJECT_USER_GROUPS) != null) {
         userGroups = (Set<String>)SecurityUtils.getSubject().getSession().getAttribute(SUBJECT_USER_GROUPS);
index 09f10ba..7ebf554 100644 (file)
@@ -75,7 +75,7 @@ public class KnoxLdapContextFactory extends JndiLdapContextFactory {
       }
 
       systemPass = systemPass.trim();
-      if (systemPass.length() == 0) {
+      if (systemPass.isEmpty()) {
         return;
       }
 
index e1d1c34..1a33d57 100644 (file)
@@ -572,7 +572,7 @@ public class KnoxLdapRealm extends JndiLdapRealm {
     }
     // search for the filter, substituting base with userDn
     // search for base_dn=userDn, scope=base, filter=filter
-    LdapContext systemLdapCtx = null;
+    LdapContext systemLdapCtx;
     systemLdapCtx = ldapContextFactory.getSystemLdapContext();
     NamingEnumeration<SearchResult> searchResultEnum = null;
     try {
@@ -607,8 +607,7 @@ public class KnoxLdapRealm extends JndiLdapRealm {
       principalRegex = DEFAULT_PRINCIPAL_REGEX;
     } else {
       regex = regex.trim();
-      Pattern pattern = Pattern.compile( regex );
-      principalPattern = pattern;
+      principalPattern = Pattern.compile( regex );
       principalRegex = regex;
     }
   }
@@ -694,7 +693,7 @@ public class KnoxLdapRealm extends JndiLdapRealm {
 
       // Create the searchBase and searchFilter from config.
       String searchBase = expandTemplate( getUserSearchBase(), matchedPrincipal );
-      String searchFilter = null;
+      String searchFilter;
       if ( userSearchFilter == null ) {
         if ( userSearchAttributeName == null ) {
           searchFilter = String.format( Locale.ROOT, "(objectclass=%1$s)", getUserObjectClass() );
index 7d2c2e7..12b2bc1 100644 (file)
@@ -84,7 +84,7 @@ public class StrictTransportFilter implements Filter {
 
     @Override
     public String getHeader(String name) {
-        String headerValue = null;
+        String headerValue;
         if (name.equals(STRICT_TRANSPORT)) {
             headerValue = option;
         }
index 6cec81e..4b70cd6 100644 (file)
@@ -85,7 +85,7 @@ public class XContentTypeOptionsFilter implements Filter {
 
     @Override
     public String getHeader(String name) {
-      String headerValue = null;
+      String headerValue;
       if (name.equals(X_CONTENT_TYPE_OPTIONS_HEADER)) {
         headerValue = option;
       }
index 467bd9a..977664f 100644 (file)
@@ -84,7 +84,7 @@ public class XFrameOptionsFilter implements Filter {
 
     @Override
     public String getHeader(String name) {
-        String headerValue = null;
+        String headerValue;
         if (name.equals(X_FRAME_OPTIONS)) {
             headerValue = option;
         }
index 4045fab..a8746ee 100644 (file)
@@ -82,7 +82,7 @@ public class XSSProtectionFilter implements Filter {
 
     @Override
     public String getHeader(String name) {
-      String headerValue = null;
+      String headerValue;
       if (name.equals(X_XSS_PROTECTION)) {
         headerValue = option;
       }
index 86000d3..a4a5730 100644 (file)
@@ -101,7 +101,7 @@ public class StrictTransportFilterTest {
   }
 
   class TestFilterConfig implements FilterConfig {
-    Properties props = null;
+    Properties props;
 
     TestFilterConfig(Properties props) {
       this.props = props;
index d233a09..eb085d6 100644 (file)
@@ -130,7 +130,7 @@ public class XFrameOptionsFilterTest {
 //  }
 
   class TestFilterConfig implements FilterConfig {
-    Properties props = null;
+    Properties props;
 
     TestFilterConfig(Properties props) {
       this.props = props;
index 6fe1bb9..8d0dbca 100644 (file)
@@ -93,7 +93,7 @@ public class XSSProtectionFilterTest {
   }
 
   private static class TestFilterConfig implements FilterConfig {
-    Properties props = null;
+    Properties props;
 
     TestFilterConfig(Properties props) {
       this.props = props;
index 93db80a..3c60e0b 100644 (file)
@@ -25,6 +25,7 @@ public class CompositeEnumeration<T> implements Enumeration<T> {
   private int index = 0;
   private Enumeration<T>[] array;
 
+  @SafeVarargs
   public CompositeEnumeration(Enumeration<T>... enumerations) {
     if( enumerations == null ) {
       throw new IllegalArgumentException( "enumerations==null" );
index c0ed341..0ed303d 100644 (file)
@@ -19,7 +19,6 @@ package org.apache.knox.gateway.filter;
 
 import javax.servlet.http.HttpServletRequest;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Collections;
 import java.util.Enumeration;
 import java.util.Hashtable;
@@ -73,7 +72,7 @@ public class XForwardedHeaderRequestWrapper extends GatewayRequestWrapper {
     Enumeration<String> values;
     String value = proxyHeaders.get( name );
     if( value != null ) {
-      values = Collections.enumeration(Arrays.asList(value));
+      values = Collections.enumeration(Collections.singletonList(value));
     } else {
       values = super.getHeaders( name );
     }
index 3dbe6a2..e52bab5 100644 (file)
@@ -37,8 +37,7 @@ public class GatewayCommandLine {
 
   public static CommandLine parse( String[] args ) throws ParseException {
     CommandLineParser parser = new PosixParser();
-    CommandLine commandLine = parser.parse( createCommandLine(), args );
-    return commandLine;
+    return parser.parse( createCommandLine(), args );
   }
 
   public static void printUsage() {
index b95ade1..e93daee 100644 (file)
@@ -141,9 +141,8 @@ public class GatewayFilter implements Filter {
               int index = origUrl.indexOf(path);
               url = origUrl.substring(0, index) + "/" + defaultServicePath + path;
             }
-            String contextPath = defaultServicePath;
             servletRequest = new ForwardedRequest((HttpServletRequest) servletRequest,
-                contextPath,
+                defaultServicePath,
                 url);
           } catch (URISyntaxException e) {
             throw new ServletException( e );
index ad15c65..0a90220 100644 (file)
@@ -505,9 +505,9 @@ public class GatewayServer {
     } else {
       /* check for port conflict */
       final Connector[] connectors = jetty.getConnectors();
-      for (int i = 0; i < connectors.length; i++) {
-        if (connectors[i] instanceof ServerConnector
-            && ((ServerConnector) connectors[i]).getPort() == port) {
+      for (Connector connector : connectors) {
+        if (connector instanceof ServerConnector
+                && ((ServerConnector) connector).getPort() == port) {
           log.portAlreadyInUse(port, topologyName);
           throw new IOException(String.format(Locale.ROOT,
               " Port %d used by topology %s is used by other topology, ports for topologies (if defined) have to be unique. ",
@@ -950,8 +950,7 @@ public class GatewayServer {
   }
 
   private File calculateDeploymentDir( Topology topology ) {
-    File dir = new File( calculateAbsoluteDeploymentsDir(), calculateDeploymentName( topology ) );
-    return dir;
+    return new File( calculateAbsoluteDeploymentsDir(), calculateDeploymentName( topology ) );
   }
 
   private String calculateDeploymentExtension( Topology topology ) {
@@ -959,8 +958,7 @@ public class GatewayServer {
   }
 
   private String calculateDeploymentName( Topology topology ) {
-    String name = topology.getName() + calculateDeploymentExtension( topology ) + Long.toHexString( topology.getTimestamp() );
-    return name;
+    return topology.getName() + calculateDeploymentExtension( topology ) + Long.toHexString( topology.getTimestamp() );
   }
 
   private static void checkAddressAvailability( InetSocketAddress address ) throws IOException {
index ef2a27d..1f63f90 100644 (file)
@@ -80,13 +80,12 @@ public class GatewayServlet implements Servlet, Filter {
   }
 
   public synchronized void setFilter( GatewayFilter filter ) throws ServletException {
-    Filter prev = filter;
     if( filterConfig != null ) {
       filter.init( filterConfig );
     }
     this.filter = filter;
-    if( prev != null && filterConfig != null ) {
-      prev.destroy();
+    if( filter != null && filterConfig != null ) {
+      ((Filter) filter).destroy();
     }
   }
 
@@ -100,10 +99,7 @@ public class GatewayServlet implements Servlet, Filter {
       if( filter != null ) {
         filter.init( filterConfig );
       }
-    } catch( ServletException e ) {
-      LOG.failedToInitializeServletInstace( e );
-      throw e;
-    } catch( RuntimeException e ) {
+    } catch( ServletException | RuntimeException e ) {
       LOG.failedToInitializeServletInstace( e );
       throw e;
     }
@@ -118,10 +114,7 @@ public class GatewayServlet implements Servlet, Filter {
       if( filter != null ) {
         filter.init( filterConfig );
       }
-    } catch( ServletException e ) {
-      LOG.failedToInitializeServletInstace( e );
-      throw e;
-    } catch( RuntimeException e ) {
+    } catch( ServletException | RuntimeException e ) {
       LOG.failedToInitializeServletInstace( e );
       throw e;
     }
@@ -140,13 +133,7 @@ public class GatewayServlet implements Servlet, Filter {
       if( f != null ) {
         try {
           f.doFilter( servletRequest, servletResponse, null );
-        } catch( IOException e ) {
-          LOG.failedToExecuteFilter( e );
-          throw e;
-        } catch( ServletException e ) {
-          LOG.failedToExecuteFilter( e );
-          throw e;
-        } catch( RuntimeException e ) {
+        } catch( IOException | RuntimeException | ServletException e ) {
           LOG.failedToExecuteFilter( e );
           throw e;
         }
@@ -176,13 +163,7 @@ public class GatewayServlet implements Servlet, Filter {
             chain.doFilter( servletRequest, servletResponse );
           }
 
-        } catch( IOException e ) {
-          LOG.failedToExecuteFilter( e );
-          throw e;
-        } catch( ServletException e ) {
-          LOG.failedToExecuteFilter( e );
-          throw e;
-        } catch( RuntimeException e ) {
+        } catch( IOException | RuntimeException | ServletException e ) {
           LOG.failedToExecuteFilter( e );
           throw e;
         }
@@ -233,9 +214,7 @@ public class GatewayServlet implements Servlet, Filter {
         }
       }
       return filter;
-    } catch( IOException e ) {
-      throw new ServletException( e );
-    } catch( URISyntaxException e ) {
+    } catch( IOException | URISyntaxException e ) {
       throw new ServletException( e );
     }
   }
index 51533b7..8a613fe 100644 (file)
@@ -266,7 +266,7 @@ public class GatewayConfigImpl extends Configuration implements GatewayConfig {
   public String getGatewayDataDir() {
     String systemValue =
         System.getProperty(GATEWAY_DATA_HOME_VAR, System.getenv(GATEWAY_DATA_HOME_VAR));
-    String dataDir = null;
+    String dataDir;
     if (systemValue != null) {
       dataDir = systemValue;
     } else {
@@ -928,15 +928,13 @@ public class GatewayConfigImpl extends Configuration implements GatewayConfig {
 
   @Override
   public List<String> getAutoDeployTopologyNames() {
-    List<String> topologyNames = new ArrayList<>();
 
     String value = get(AUTO_DEPLOY_TOPOLOGIES);
     if (value == null) {
       value = DEFAULT_AUTO_DEPLOY_TOPOLOGIES;
     }
-    topologyNames.addAll(Arrays.asList(value.trim().split("\\s*,\\s*")));
 
-    return topologyNames;
+    return new ArrayList<>(Arrays.asList(value.trim().split("\\s*,\\s*")));
   }
 
   @Override
index ca497a3..6358107 100644 (file)
@@ -213,13 +213,10 @@ public abstract class DeploymentFactory {
       marshaller.marshal( topology, writer );
       writer.close();
       xml = writer.toString();
-    } catch (IOException e) {
-      throw new DeploymentException( "Failed to marshall topology.", e );
-    } catch (JAXBException e) {
+    } catch (IOException | JAXBException e) {
       throw new DeploymentException( "Failed to marshall topology.", e );
     }
-    StringAsset asset = new StringAsset( xml );
-    return asset;
+    return new StringAsset( xml );
   }
 
   private static DeploymentContext createDeploymentContext(
@@ -231,9 +228,8 @@ public abstract class DeploymentFactory {
     WebArchive webArchive = ShrinkWrap.create( WebArchive.class, archivePath );
     WebAppDescriptor webAppDesc = Descriptors.create( WebAppDescriptor.class );
     GatewayDescriptor gateway = GatewayDescriptorFactory.create();
-    DeploymentContext context = new DeploymentContextImpl(
+    return new DeploymentContextImpl(
         config, topology, gateway, webArchive, webAppDesc, providers );
-    return context;
   }
 
   // Scan through the providers in the topology.  Collect any named providers in their roles list.
@@ -445,7 +441,7 @@ public abstract class DeploymentFactory {
 
   private static void injectServices(Object contributor) {
     if (gatewayServices != null) {
-      Statement stmt = null;
+      Statement stmt;
       for(String serviceName : gatewayServices.getServiceNames()) {
 
         try {
@@ -550,7 +546,7 @@ public abstract class DeploymentFactory {
     ServiceDeploymentContributor contributor = null;
     Map<String,Map<Version, ServiceDeploymentContributor>> nameMap = SERVICE_CONTRIBUTOR_MAP.get( role );
     if( nameMap != null && !nameMap.isEmpty()) {
-      Map<Version, ServiceDeploymentContributor> versionMap = null;
+      Map<Version, ServiceDeploymentContributor> versionMap;
       if ( name == null ) {
         versionMap = nameMap.values().iterator().next();
       } else {
@@ -746,25 +742,23 @@ public abstract class DeploymentFactory {
         = new HashMap<>();
 
     ServiceLoader<ProviderDeploymentContributor> loader = ServiceLoader.load( ProviderDeploymentContributor.class );
-    Iterator<ProviderDeploymentContributor> contributors = loader.iterator();
-    while( contributors.hasNext() ) {
-      ProviderDeploymentContributor contributor = contributors.next();
-      if( contributor.getName() == null ) {
-        log.ignoringProviderContributorWithMissingName( contributor.getClass().getName() );
-        continue;
-      }
-      if( contributor.getRole() == null ) {
-        log.ignoringProviderContributorWithMissingRole( contributor.getClass().getName() );
-        continue;
-      }
-      set.add( contributor );
-      Map nameMap = roleMap.get( contributor.getRole() );
-      if( nameMap == null ) {
-        nameMap = new HashMap<>();
-        roleMap.put( contributor.getRole(), nameMap );
-      }
-      nameMap.put( contributor.getName(), contributor );
-    }
+     for (ProviderDeploymentContributor contributor : loader) {
+       if (contributor.getName() == null) {
+         log.ignoringProviderContributorWithMissingName(contributor.getClass().getName());
+         continue;
+       }
+       if (contributor.getRole() == null) {
+         log.ignoringProviderContributorWithMissingRole(contributor.getClass().getName());
+         continue;
+       }
+       set.add(contributor);
+       Map nameMap = roleMap.get(contributor.getRole());
+       if (nameMap == null) {
+         nameMap = new HashMap<>();
+         roleMap.put(contributor.getRole(), nameMap);
+       }
+       nameMap.put(contributor.getName(), contributor);
+     }
     PROVIDER_CONTRIBUTORS = set;
     PROVIDER_CONTRIBUTOR_MAP = roleMap;
   }
index 26a4690..8cbe8bc 100644 (file)
@@ -112,9 +112,7 @@ public class ApplicationDeploymentContributor extends ServiceDeploymentContribut
       File rewriteFile = new File( appDir, REWRITE_RULES_FILE_NAME );
       serviceDefinition = loadServiceDefinition( application, serviceFile );
       serviceRules = loadRewriteRules( application, rewriteFile );
-    } catch ( IOException e ) {
-      throw new DeploymentException( "Failed to deploy application: " + application.getName(), e );
-    } catch ( JAXBException e ){
+    } catch ( IOException | JAXBException e ) {
       throw new DeploymentException( "Failed to deploy application: " + application.getName(), e );
     }
   }
index 363964f..5523763 100644 (file)
@@ -52,9 +52,7 @@ public class XmlGatewayDescriptorExporter implements GatewayDescriptorExporter,
 
       XmlUtils.writeXml( document, writer );
 
-    } catch( ParserConfigurationException e ) {
-      throw new IOException( e );
-    } catch( TransformerException e ) {
+    } catch( ParserConfigurationException | TransformerException e ) {
       throw new IOException( e );
     }
   }
index 875fb07..1757526 100644 (file)
@@ -43,8 +43,7 @@ public class XmlGatewayDescriptorImporter implements GatewayDescriptorImporter {
     Digester digester = loader.newDigester( new ExtendedBaseRules() );
     digester.setValidating( false );
     try {
-      GatewayDescriptor descriptor = digester.parse( reader );
-      return descriptor;
+      return digester.parse( reader );
     } catch( SAXException e ) {
       throw new IOException( e );
     }
index 3aa8f4a..43fb579 100644 (file)
@@ -82,8 +82,7 @@ public class UrlConnectionDispatch extends AbstractGatewayFilter {
       str.append('?');
       str.append(query);
     }
-    URI url = URI.create(str.toString());
-    return url;
+    return URI.create(str.toString());
   }
 
   public void doGet( URI url, HttpServletRequest request, HttpServletResponse response ) throws IOException, URISyntaxException {
index 07d5280..1c005d3 100644 (file)
@@ -70,7 +70,7 @@ public class BasicAuthChallengeFilter extends AbstractGatewayFilter {
         if( parts.length == 2 ) {
           String username = parts[0];
           String password = parts[1];
-          if( username.length() > 0 && password.length() > 0 ) {
+          if(!username.isEmpty() && !password.isEmpty()) {
             credentials = new UsernamePasswordCredentials( username, password );
           }
         }
index 599f882..a11f52a 100644 (file)
@@ -64,7 +64,7 @@ public class PortMappingHelperHandler extends HandlerWrapper {
 
       for(final Map.Entry<String, Integer> entry: config.getGatewayPortMappings().entrySet()) {
 
-        if(entry.getValue().intValue() == config.getGatewayPort()) {
+        if(entry.getValue() == config.getGatewayPort()) {
           defaultTopologyRedirectContext = "/" + config.getGatewayPath() + "/" + entry.getKey();
           break;
         }
index 7b90380..7691422 100644 (file)
@@ -46,7 +46,7 @@ public class RequestUpdateHandler extends ScopedHandler {
   private static final GatewayMessages LOG = MessagesFactory
       .get(GatewayMessages.class);
 
-  private String redirectContext = null;
+  private String redirectContext;
 
   public RequestUpdateHandler(final GatewayConfig config,
       final String topologyName, final GatewayServices services) {
index 26f08a1..c6bee57 100644 (file)
@@ -38,7 +38,6 @@ import org.apache.knox.gateway.services.metrics.MetricsService;
 import java.lang.management.ManagementFactory;
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.Map;
 import java.util.ServiceLoader;
 import java.util.concurrent.TimeUnit;
@@ -79,21 +78,18 @@ public class DefaultMetricsService implements MetricsService {
 
   private void loadInstrumentationProviders() {
     ServiceLoader<InstrumentationProviderDescriptor> descriptors = ServiceLoader.load(InstrumentationProviderDescriptor.class);
-    Iterator<InstrumentationProviderDescriptor> descriptorIterator = descriptors.iterator();
-    while ( descriptorIterator.hasNext() ) {
-      instrumentationProviders.putAll(descriptorIterator.next().providesInstrumentation());
+    for (InstrumentationProviderDescriptor descriptor : descriptors) {
+      instrumentationProviders.putAll(descriptor.providesInstrumentation());
     }
   }
 
   private void loadAndInitReporters(GatewayConfig config) {
     ServiceLoader<MetricsReporter> reporters = ServiceLoader.load(MetricsReporter.class);
-    Iterator<MetricsReporter> reportersIterator = reporters.iterator();
-    while ( reportersIterator.hasNext() ) {
-      MetricsReporter metricsReporter = reportersIterator.next();
+    for (MetricsReporter metricsReporter : reporters) {
       try {
         metricsReporter.init(config);
         metricsReporters.add(metricsReporter);
-      } catch ( MetricsReporterException e ) {
+      } catch (MetricsReporterException e) {
         LOG.failedToInitializeReporter(metricsReporter.getName(), e);
       }
     }
index 5777ac7..d15ff45 100644 (file)
 package org.apache.knox.gateway.services.registry.impl;
 
 import com.fasterxml.jackson.core.JsonFactory;
-import com.fasterxml.jackson.core.JsonParseException;
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.JsonMappingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import org.apache.commons.codec.binary.Base64;
 import org.apache.commons.io.FileUtils;
@@ -147,7 +145,7 @@ public class DefaultServiceRegistryService implements ServiceRegistry, Service {
 
   @Override
   public List<String> lookupServiceURLs( String clusterName, String serviceName ) {
-    RegEntry entry = null;
+    RegEntry entry;
     HashMap<String, RegEntry> clusterServices = registry.get(clusterName);
     if (clusterServices != null) {
       entry = clusterServices.get(serviceName);
@@ -166,10 +164,6 @@ public class DefaultServiceRegistryService implements ServiceRegistry, Service {
           = new TypeReference<Registry>() {};
     try {
       map = mapper.readValue(json, typeRef);
-    } catch (JsonParseException e) {
-      LOG.failedToGetMapFromJsonString( json, e );
-    } catch (JsonMappingException e) {
-      LOG.failedToGetMapFromJsonString( json, e );
     } catch (IOException e) {
       LOG.failedToGetMapFromJsonString( json, e );
     }
index 9a173f4..2cafd3f 100644 (file)
@@ -81,7 +81,7 @@ public class DefaultAliasService implements AliasService {
   @Override
   public char[] getPasswordFromAliasForCluster(String clusterName, String alias, boolean generate)
       throws AliasServiceException {
-    char[] credential = null;
+    char[] credential;
     try {
       credential = keystoreService.getCredentialForCluster(clusterName, alias);
       if (credential == null) {
@@ -164,11 +164,9 @@ public class DefaultAliasService implements AliasService {
     Certificate cert = null;
     try {
       cert = this.keystoreService.getKeystoreForGateway().getCertificate(alias);
-    } catch (KeyStoreException e) {
+    } catch (KeyStoreException | KeystoreServiceException e) {
       LOG.unableToRetrieveCertificateForGateway(e);
       // should we throw an exception?
-    } catch (KeystoreServiceException e) {
-      LOG.unableToRetrieveCertificateForGateway(e);
     }
     return cert;
   }
@@ -180,7 +178,7 @@ public class DefaultAliasService implements AliasService {
     try {
       keyStore = keystoreService.getCredentialStoreForCluster(clusterName);
       if (keyStore != null) {
-        String alias = null;
+        String alias;
         try {
           Enumeration<String> e = keyStore.aliases();
           while (e.hasMoreElements()) {
index 7cfc4ee..7010d29 100644 (file)
@@ -44,7 +44,7 @@ public class DefaultCryptoService implements CryptoService {
   private AliasService as = null;
   private KeystoreService ks = null;
   private HashMap<String,ConfigurableEncryptor> encryptorCache =
-      new HashMap<String,ConfigurableEncryptor>();
+      new HashMap<>();
   private GatewayConfig config = null;
 
   public void setKeystoreService(KeystoreService ks) {
@@ -94,10 +94,6 @@ public class DefaultCryptoService implements CryptoService {
     if (password != null) {
       try {
         return getEncryptor(clusterName,password).encrypt( clear );
-      } catch (NoSuchAlgorithmException e1) {
-        LOG.failedToEncryptPasswordForCluster( clusterName, e1 );
-      } catch (InvalidKeyException e) {
-        LOG.failedToEncryptPasswordForCluster( clusterName, e );
       } catch (Exception e) {
         LOG.failedToEncryptPasswordForCluster( clusterName, e );
       }
@@ -113,8 +109,8 @@ public class DefaultCryptoService implements CryptoService {
   @Override
   public byte[] decryptForCluster(String clusterName, String alias, byte[] cipherText, byte[] iv, byte[] salt) {
     try {
-      char[] password = null;
-      ConfigurableEncryptor encryptor = null;
+      char[] password;
+      ConfigurableEncryptor encryptor;
         password = as.getPasswordFromAliasForCluster(clusterName, alias);
         if (password != null) {
           encryptor = getEncryptor(clusterName,password );
@@ -141,15 +137,7 @@ public class DefaultCryptoService implements CryptoService {
       sig.initVerify(ks.getKeystoreForGateway().getCertificate(alias).getPublicKey());
       sig.update(signed.getBytes(StandardCharsets.UTF_8));
       verified = sig.verify(signature);
-    } catch (SignatureException e) {
-      LOG.failedToVerifySignature( e );
-    } catch (NoSuchAlgorithmException e) {
-      LOG.failedToVerifySignature( e );
-    } catch (InvalidKeyException e) {
-      LOG.failedToVerifySignature( e );
-    } catch (KeyStoreException e) {
-      LOG.failedToVerifySignature( e );
-    } catch (KeystoreServiceException e) {
+    } catch (SignatureException | KeystoreServiceException | KeyStoreException | InvalidKeyException | NoSuchAlgorithmException e) {
       LOG.failedToVerifySignature( e );
     }
     LOG.signatureVerified( verified );
@@ -159,22 +147,14 @@ public class DefaultCryptoService implements CryptoService {
   @Override
   public byte[] sign(String algorithm, String alias, String payloadToSign) {
     try {
-      char[] passphrase = null;
+      char[] passphrase;
       passphrase = as.getGatewayIdentityPassphrase();
       PrivateKey privateKey = (PrivateKey) ks.getKeyForGateway(alias, passphrase);
       Signature signature = Signature.getInstance(algorithm);
       signature.initSign(privateKey);
       signature.update(payloadToSign.getBytes(StandardCharsets.UTF_8));
       return signature.sign();
-    } catch (NoSuchAlgorithmException e) {
-      LOG.failedToSignData( e );
-    } catch (InvalidKeyException e) {
-      LOG.failedToSignData( e );
-    } catch (SignatureException e) {
-      LOG.failedToSignData( e );
-    } catch (KeystoreServiceException e) {
-      LOG.failedToSignData( e );
-    } catch (AliasServiceException e) {
+    } catch (NoSuchAlgorithmException | AliasServiceException | KeystoreServiceException | SignatureException | InvalidKeyException e) {
       LOG.failedToSignData( e );
     }
     return null;
index 11afe75..e72681f 100644 (file)
@@ -194,7 +194,7 @@ public class DefaultKeystoreService extends BaseKeystoreService implements
         if (hostname == null) {
           hostname = System.getProperty(CERT_GEN_MODE, CERT_GEN_MODE_LOCALHOST);
         }
-        X509Certificate cert = null;
+        X509Certificate cert;
         if(hostname.equals(CERT_GEN_MODE_HOSTNAME)) {
           String dn = buildDistinguishedName(InetAddress.getLocalHost().getHostName());
           cert = X509CertificateUtil.generateCertificate(dn, KPair, 365, "SHA1withRSA");
@@ -242,15 +242,13 @@ public class DefaultKeystoreService extends BaseKeystoreService implements
 
   @Override
   public boolean isCredentialStoreForClusterAvailable(String clusterName) throws KeystoreServiceException {
-    boolean rc = false;
+    boolean rc;
     final File  keyStoreFile = new File( keyStoreDir + clusterName + CREDENTIALS_SUFFIX  );
     readLock.lock();
     try {
       try {
         rc = isKeystoreAvailable(keyStoreFile, "JCEKS");
-      } catch (KeyStoreException e) {
-        throw new KeystoreServiceException(e);
-      } catch (IOException e) {
+      } catch (KeyStoreException | IOException e) {
         throw new KeystoreServiceException(e);
       }
       return rc;
@@ -262,15 +260,13 @@ public class DefaultKeystoreService extends BaseKeystoreService implements
 
   @Override
   public boolean isKeystoreForGatewayAvailable() throws KeystoreServiceException {
-    boolean rc = false;
+    boolean rc;
     final File  keyStoreFile = new File( keyStoreDir + GATEWAY_KEYSTORE  );
     readLock.lock();
     try {
       try {
         rc = isKeystoreAvailable(keyStoreFile, "JKS");
-      } catch (KeyStoreException e) {
-        throw new KeystoreServiceException(e);
-      } catch (IOException e) {
+      } catch (KeyStoreException | IOException e) {
         throw new KeystoreServiceException(e);
       }
       return rc;
@@ -293,11 +289,7 @@ public class DefaultKeystoreService extends BaseKeystoreService implements
       if (ks != null) {
         try {
           key = ks.getKey(alias, passphrase);
-        } catch (UnrecoverableKeyException e) {
-          LOG.failedToGetKeyForGateway( alias, e );
-        } catch (KeyStoreException e) {
-          LOG.failedToGetKeyForGateway( alias, e );
-        } catch (NoSuchAlgorithmException e) {
+        } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) {
           LOG.failedToGetKeyForGateway( alias, e );
         }
       }
@@ -326,11 +318,7 @@ public class DefaultKeystoreService extends BaseKeystoreService implements
       if (ks != null) {
         try {
           key = ks.getKey(alias, passphrase);
-        } catch (UnrecoverableKeyException e) {
-          LOG.failedToGetKeyForGateway( alias, e );
-        } catch (KeyStoreException e) {
-          LOG.failedToGetKeyForGateway( alias, e );
-        } catch (NoSuchAlgorithmException e) {
+        } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) {
           LOG.failedToGetKeyForGateway( alias, e );
         }
       }
@@ -365,13 +353,7 @@ public class DefaultKeystoreService extends BaseKeystoreService implements
       final File  keyStoreFile = new File( keyStoreDir + clusterName + CREDENTIALS_SUFFIX  );
       try {
         writeKeystoreToFile(ks, keyStoreFile);
-      } catch (KeyStoreException e) {
-        LOG.failedToAddCredentialForCluster( clusterName, e );
-      } catch (NoSuchAlgorithmException e) {
-        LOG.failedToAddCredentialForCluster( clusterName, e );
-      } catch (CertificateException e) {
-        LOG.failedToAddCredentialForCluster( clusterName, e );
-      } catch (IOException e) {
+      } catch (KeyStoreException | IOException | CertificateException | NoSuchAlgorithmException e) {
         LOG.failedToAddCredentialForCluster( clusterName, e );
       }
     } finally {
@@ -382,7 +364,7 @@ public class DefaultKeystoreService extends BaseKeystoreService implements
   @Override
   public char[] getCredentialForCluster(String clusterName, String alias)
       throws KeystoreServiceException {
-    char[] credential = null;
+    char[] credential;
     readLock.lock();
     try {
       credential = checkCache(clusterName, alias);
@@ -398,11 +380,7 @@ public class DefaultKeystoreService extends BaseKeystoreService implements
               credential = credentialString.toCharArray();
               addToCache(clusterName, alias, credentialString);
             }
-          } catch (UnrecoverableKeyException e) {
-            LOG.failedToGetCredentialForCluster( clusterName, e );
-          } catch (KeyStoreException e) {
-            LOG.failedToGetCredentialForCluster( clusterName, e );
-          } catch (NoSuchAlgorithmException e) {
+          } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) {
             LOG.failedToGetCredentialForCluster( clusterName, e );
           }
 
@@ -425,13 +403,7 @@ public class DefaultKeystoreService extends BaseKeystoreService implements
       removeCredential(alias, ks);
       try {
         writeKeystoreToFile(ks, keyStoreFile);
-      } catch (KeyStoreException e) {
-        LOG.failedToRemoveCredentialForCluster(clusterName, e);
-      } catch (NoSuchAlgorithmException e) {
-        LOG.failedToRemoveCredentialForCluster(clusterName, e);
-      } catch (CertificateException e) {
-        LOG.failedToRemoveCredentialForCluster(clusterName, e);
-      } catch (IOException e) {
+      } catch (KeyStoreException | IOException | CertificateException | NoSuchAlgorithmException e) {
         LOG.failedToRemoveCredentialForCluster(clusterName, e);
       }
     }
@@ -445,7 +417,7 @@ public class DefaultKeystoreService extends BaseKeystoreService implements
    */
   private char[] checkCache(String clusterName, String alias) {
     char[] c = null;
-    String cred = null;
+    String cred;
     Map<String, String> clusterCache = cache.get(clusterName);
     if (clusterCache == null) {
       return null;
index 8041a83..75613c3 100644 (file)
@@ -102,7 +102,7 @@ public class JettySSLService implements SSLService {
       if (!ks.isKeystoreForGatewayAvailable()) {
         log.creatingKeyStoreForGateway();
         ks.createKeystoreForGateway();
-        char[] passphrase = null;
+        char[] passphrase;
         try {
           passphrase = as.getGatewayIdentityPassphrase();
         } catch (AliasServiceException e) {
@@ -185,7 +185,7 @@ public class JettySSLService implements SSLService {
     }
     sslContextFactory.setKeyManagerPassword(new String(keypass));
 
-    String truststorePassword = null;
+    String truststorePassword;
     if (clientAuthNeeded || clientAuthWanted) {
       if (truststorePath != null) {
         char[] truststorePwd = null;
@@ -220,13 +220,13 @@ public class JettySSLService implements SSLService {
     }
     sslContextFactory.setTrustAll( trustAllCerts );
     if (sslIncludeCiphers != null && !sslIncludeCiphers.isEmpty()) {
-      sslContextFactory.setIncludeCipherSuites( sslIncludeCiphers.toArray(new String[sslIncludeCiphers.size()]) );
+      sslContextFactory.setIncludeCipherSuites( sslIncludeCiphers.toArray(new String[0]) );
     }
     if (sslExcludeCiphers != null && !sslExcludeCiphers.isEmpty()) {
-      sslContextFactory.setExcludeCipherSuites( sslExcludeCiphers.toArray(new String[sslExcludeCiphers.size()]) );
+      sslContextFactory.setExcludeCipherSuites( sslExcludeCiphers.toArray(new String[0]) );
     }
     if (sslExcludeProtocols != null && !sslExcludeProtocols.isEmpty()) {
-      sslContextFactory.setExcludeProtocols( sslExcludeProtocols.toArray(new String[sslExcludeProtocols.size()]) );
+      sslContextFactory.setExcludeProtocols( sslExcludeProtocols.toArray(new String[0]) );
     }
     return sslContextFactory;
   }
@@ -241,16 +241,9 @@ public class JettySSLService implements SSLService {
 
   private static KeyStore loadKeyStore( String fileName, String storeType, char[] storePass ) throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException {
     KeyStore keystore = KeyStore.getInstance(storeType);
-    //Coverity CID 1352655
-    InputStream is = new FileInputStream(fileName);
-    try {
-      keystore.load( is, storePass );
-    } finally {
-      if( is != null ) {
-        is.close();
-      }
+    try (InputStream is = new FileInputStream(fileName)) {
+      keystore.load(is, storePass);
     }
     return keystore;
   }
-
 }
index 2b54c3c..cdc4907 100644 (file)
@@ -128,14 +128,7 @@ public class DefaultTopologyService
       try {
         topology = loadTopologyAttempt(file);
         break;
-      } catch (IOException e) {
-        if (System.currentTimeMillis() - start < TIMEOUT) {
-          log.failedToLoadTopologyRetrying(file.getAbsolutePath(), Long.toString(DELAY), e);
-          Thread.sleep(DELAY);
-        } else {
-          throw e;
-        }
-      } catch (SAXException e) {
+      } catch (IOException | SAXException e) {
         if (System.currentTimeMillis() - start < TIMEOUT) {
           log.failedToLoadTopologyRetrying(file.getAbsolutePath(), Long.toString(DELAY), e);
           Thread.sleep(DELAY);
@@ -281,16 +274,6 @@ public class DefaultTopologyService
                       ActionOutcome.FAILURE);
               log.failedToLoadTopology(file.getAbsolutePath());
             }
-          } catch (IOException e) {
-            // Maybe it makes sense to throw exception
-            auditor.audit(Action.LOAD, file.getAbsolutePath(), ResourceType.TOPOLOGY,
-                    ActionOutcome.FAILURE);
-            log.failedToLoadTopology(file.getAbsolutePath(), e);
-          } catch (SAXException e) {
-            // Maybe it makes sense to throw exception
-            auditor.audit(Action.LOAD, file.getAbsolutePath(), ResourceType.TOPOLOGY,
-                    ActionOutcome.FAILURE);
-            log.failedToLoadTopology(file.getAbsolutePath(), e);
           } catch (Exception e) {
             // Maybe it makes sense to throw exception
             auditor.audit(Action.LOAD, file.getAbsolutePath(), ResourceType.TOPOLOGY,
@@ -337,15 +320,9 @@ public class DefaultTopologyService
       }
 
 
-    } catch (JAXBException e) {
+    } catch (JAXBException | SAXException | IOException e) {
       auditor.audit(Action.DEPLOY, t.getName(), ResourceType.TOPOLOGY, ActionOutcome.FAILURE);
       log.failedToDeployTopology(t.getName(), e);
-    } catch (IOException io) {
-      auditor.audit(Action.DEPLOY, t.getName(), ResourceType.TOPOLOGY, ActionOutcome.FAILURE);
-      log.failedToDeployTopology(t.getName(), io);
-    } catch (SAXException sx){
-      auditor.audit(Action.DEPLOY, t.getName(), ResourceType.TOPOLOGY, ActionOutcome.FAILURE);
-      log.failedToDeployTopology(t.getName(), sx);
     }
     reloadTopologies();
   }
@@ -875,7 +852,7 @@ public class DefaultTopologyService
         String providerConfig =
                       FilenameUtils.normalize(result.get(SimpleDescriptorHandler.RESULT_REFERENCE).getAbsolutePath());
         if (!providerConfigReferences.containsKey(providerConfig)) {
-          providerConfigReferences.put(providerConfig, new ArrayList<String>());
+          providerConfigReferences.put(providerConfig, new ArrayList<>());
         }
         List<String> refs = providerConfigReferences.get(providerConfig);
         String descriptorName = FilenameUtils.normalize(file.getAbsolutePath());
@@ -986,8 +963,8 @@ public class DefaultTopologyService
    */
   private static class TopologyDiscoveryTrigger implements ClusterConfigurationMonitor.ConfigurationChangeListener {
 
-    private TopologyService topologyService = null;
-    private ClusterConfigurationMonitorService ccms = null;
+    private TopologyService topologyService;
+    private ClusterConfigurationMonitorService ccms;
 
     TopologyDiscoveryTrigger(TopologyService topologyService, ClusterConfigurationMonitorService ccms) {
       this.topologyService = topologyService;
index 04e0e8c..d6e3d50 100644 (file)
@@ -17,7 +17,7 @@
 package org.apache.knox.gateway.topology.discovery;
 
 public class DefaultServiceDiscoveryConfig implements ServiceDiscoveryConfig {
-    private String address  = null;
+    private String address;
     private String user     = null;
     private String pwdAlias = null;
 
index 950bc04..1408ca9 100644 (file)
@@ -91,7 +91,7 @@ public class ProviderConfigurationParser {
 
 
   static ProviderConfiguration parseXML(InputStream in) throws Exception {
-    XMLProviderConfiguration providerConfig = null;
+    XMLProviderConfiguration providerConfig;
 
     JAXBContext jaxbContext = JAXBContext.newInstance(XMLProviderConfiguration.class);
     Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
@@ -108,8 +108,7 @@ public class ProviderConfigurationParser {
 
   static ProviderConfiguration parseJSON(InputStream in) throws IOException {
     final ObjectMapper mapper = new ObjectMapper();
-    JSONProviderConfiguration providerConfig = mapper.readValue(in, JSONProviderConfiguration.class);
-    return providerConfig;
+    return mapper.readValue(in, JSONProviderConfiguration.class);
   }
 
 
@@ -119,8 +118,7 @@ public class ProviderConfigurationParser {
 
   static ProviderConfiguration parseYAML(InputStream in) throws IOException {
     final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
-    JSONProviderConfiguration providerConfig = mapper.readValue(in, JSONProviderConfiguration.class);
-    return providerConfig;
+    return mapper.readValue(in, JSONProviderConfiguration.class);
   }
 
 
index 1a7359b..0b678a2 100644 (file)
@@ -117,7 +117,7 @@ public class TopologyValidator {
     StringBuilder out = new StringBuilder();
     out.append("");
     for(String s : getTopologyErrors()){
-      out.append(s + "\n");
+      out.append(s).append("\n");
     }
     return out.toString();
   }
index 37b0335..2fae90e 100644 (file)
@@ -497,9 +497,8 @@ public class KnoxCLI extends Configured implements Tool {
     }
 
     protected Service getService(String serviceName) {
-      Service service = null;
 
-      return service;
+      return null;
     }
 
     public abstract void execute() throws Exception;
@@ -507,18 +506,15 @@ public class KnoxCLI extends Configured implements Tool {
     public abstract String getUsage();
 
     protected AliasService getAliasService() {
-      AliasService as = services.getService(GatewayServices.ALIAS_SERVICE);
-      return as;
+      return services.getService(GatewayServices.ALIAS_SERVICE);
     }
 
     protected KeystoreService getKeystoreService() {
-      KeystoreService ks = services.getService(GatewayServices.KEYSTORE_SERVICE);
-      return ks;
+      return services.getService(GatewayServices.KEYSTORE_SERVICE);
     }
 
     protected TopologyService getTopologyService()  {
-      TopologyService ts = services.getService(GatewayServices.TOPOLOGY_SERVICE);
-      return ts;
+      return services.getService(GatewayServices.TOPOLOGY_SERVICE);
     }
 
     protected RemoteConfigurationRegistryClientService getRemoteConfigRegistryClientService() {
@@ -707,7 +703,7 @@ public class KnoxCLI extends Configured implements Tool {
                                        + "the --value option or --generate (will create a random secret\n"
                                        + "for you) or user will be prompt to provide password.";
 
-  private String name = null;
+  private String name;
 
    public AliasCreateCommand(String alias) {
      name = alias;
@@ -774,7 +770,7 @@ public class KnoxCLI extends Configured implements Tool {
                                     "indicated alias from the --cluster specific\n" +
                                     "credential store or the gateway credential store.";
 
-  private String name = null;
+  private String name;
 
    public AliasDeleteCommand(String alias) {
      name = alias;
@@ -1087,7 +1083,8 @@ public class KnoxCLI extends Configured implements Tool {
     }
 
     protected class MissingUsernameException extends Exception {
-      public MissingUsernameException() {};
+      public MissingUsernameException() {}
+
       public MissingUsernameException(String message) { super(message); }
     }
 
@@ -1244,12 +1241,8 @@ public class KnoxCLI extends Configured implements Tool {
 
     protected boolean authenticateUser(String config, UsernamePasswordToken token) throws ConfigurationException {
       Ini ini = new Ini();
-      try {
-        ini.loadFromPath(config);
-        return authenticateUser(ini, token);
-      } catch (ConfigurationException e) {
-        throw e;
-      }
+      ini.loadFromPath(config);
+      return authenticateUser(ini, token);
     }
 
     /**
@@ -1258,7 +1251,7 @@ public class KnoxCLI extends Configured implements Tool {
      * @return - returns the principal found in the userDn after "uid="
      */
     protected String getPrincipal(String userDn){
-      String result = "";
+      String result;
 
 //      Need to determine whether we are using AD or LDAP?
 //      LDAP userDn usually starts with "uid="
@@ -1313,9 +1306,7 @@ public class KnoxCLI extends Configured implements Tool {
         username = getSystemUsername(t);
         password = getSystemPassword(t);
         result = authenticateUser(ini, new UsernamePasswordToken(username, password));
-      } catch (MissingUsernameException | NoSuchProviderException | MissingPasswordException e) {
-        out.println(e.toString());
-      } catch (NullPointerException e) {
+      } catch (MissingUsernameException | NoSuchProviderException | MissingPasswordException | NullPointerException e) {
         out.println(e.toString());
       }
       return result;
@@ -1328,12 +1319,11 @@ public class KnoxCLI extends Configured implements Tool {
      */
     private String getSystemUsername(Topology t) throws MissingUsernameException, NoSuchProviderException {
       final String SYSTEM_USERNAME = "main.ldapRealm.contextFactory.systemUsername";
-      String user = null;
+      String user;
       Provider shiroProvider = t.getProvider("authentication", "ShiroProvider");
       if(shiroProvider != null){
         Map<String, String> params = shiroProvider.getParams();
-        String userDn = params.get(SYSTEM_USERNAME);
-        user = userDn;
+        user = params.get(SYSTEM_USERNAME);
       } else {
         throw new NoSuchProviderException("ShiroProvider", "authentication", t.getName());
       }
@@ -1347,7 +1337,7 @@ public class KnoxCLI extends Configured implements Tool {
      */
     private char[] getSystemPassword(Topology t) throws NoSuchProviderException, MissingPasswordException{
       final String SYSTEM_PASSWORD = "main.ldapRealm.contextFactory.systemPassword";
-      String pass = null;
+      String pass;
       Provider shiro = t.getProvider("authentication", "ShiroProvider");
       if(shiro != null){
         Map<String, String> params = shiro.getParams();
@@ -1650,7 +1640,7 @@ public class KnoxCLI extends Configured implements Tool {
     private int attempts = 0;
 
     @Override
-    public String getUsage() { return USAGE + ":\n\n" + DESC; };
+    public String getUsage() { return USAGE + ":\n\n" + DESC; }
 
     @Override
     public void execute() {
@@ -1899,7 +1889,7 @@ public class KnoxCLI extends Configured implements Tool {
    */
   public abstract class RemoteRegistryUploadCommand extends RemoteRegistryCommand {
     private File sourceFile = null;
-    protected String filename = null;
+    protected String filename;
 
     protected RemoteRegistryUploadCommand(String sourceFileName) {
       this.filename = sourceFileName;
@@ -1998,7 +1988,7 @@ public class KnoxCLI extends Configured implements Tool {
     static final String USAGE = "get-registry-acl entry --registry-client name";
     static final String DESC = "Presents the ACL settings for the specified remote registry entry.\n";
 
-    private String entry = null;
+    private String entry;
 
     RemoteRegistryGetACLCommand(String entry) {
       this.entry = entry;
@@ -2028,7 +2018,7 @@ public class KnoxCLI extends Configured implements Tool {
    * Base class for remote config registry delete commands
    */
   public abstract class RemoteRegistryDeleteCommand extends RemoteRegistryCommand {
-    protected String entryName = null;
+    protected String entryName;
 
     protected RemoteRegistryDeleteCommand(String entryName) {
       this.entryName = entryName;
index ffe423e..1e8e8a9 100644 (file)
@@ -183,7 +183,7 @@ public class GatewayWebsocketHandler extends WebSocketHandler
     String backendURL = urlFromServiceDefinition(serviceDefs,
         serviceRegistryService, entry, path);
 
-    StringBuffer backend = new StringBuffer();
+    StringBuilder backend = new StringBuilder();
     try {
 
       /* if we do not find websocket URL we default to HTTP */
@@ -227,14 +227,12 @@ public class GatewayWebsocketHandler extends WebSocketHandler
 
     final String[] contexts = path.split("/");
 
-    final String serviceURL = serviceRegistry.lookupServiceURL(contexts[2],
-        entry.getName().toUpperCase(Locale.ROOT));
-
     /*
      * we have a match, if ws:// is present it is returned else http:// is
      * returned
      */
-    return serviceURL;
+    return serviceRegistry.lookupServiceURL(contexts[2],
+        entry.getName().toUpperCase(Locale.ROOT));
 
   }
 
index 300dffd..e324902 100644 (file)
@@ -89,13 +89,13 @@ public class AuditLoggingTest {
     AuditServiceFactory.getAuditService().detachContext();
   }
 
-  @Test
-  /**
+  /*
    * Empty filter chain. Two events with same correlation ID are expected:
    *
    * action=access request_type=uri outcome=unavailable
    * action=access request_type=uri outcome=success message=Response status: 404
    */
+  @Test
   public void testNoFiltersAudit() throws Exception {
     FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
     EasyMock.replay( config );
@@ -167,12 +167,12 @@ public class AuditLoggingTest {
     assertThat(requestIds.size(), is(numberTotalRequests));
   }
 
-  @Test
-  /**
+  /*
    * One NoOp filter in chain. Single audit event with same with specified request URI is expected:
    *
    * action=access request_type=uri outcome=unavailable
    */
+  @Test
   public void testNoopFilter() throws ServletException, IOException,
       URISyntaxException {
 
@@ -219,19 +219,19 @@ public class AuditLoggingTest {
 
   }
 
-  @Test
-  /**
+  /*
    * Dispatching outbound request. Remote host is unreachable. Two log events is expected:
    *
    * action=dispatch request_type=uri outcome=FAILED
    * action=dispatch request_type=uri outcome=unavailable
    */
+  @Test
   public void testHttpClientOutboundException() throws IOException,
       URISyntaxException {
     String uri = "http://outbound-host:port/path";
 
     HttpServletRequest inboundRequest = EasyMock.createNiceMock( HttpServletRequest.class );
-    EasyMock.expect( inboundRequest.getHeaderNames() ).andReturn( Collections.enumeration( new ArrayList<String>() ) ).anyTimes();
+    EasyMock.expect( inboundRequest.getHeaderNames() ).andReturn( Collections.enumeration(new ArrayList<>() ) ).anyTimes();
     EasyMock.replay( inboundRequest );
 
     HttpServletResponse outboundResponse = EasyMock.createNiceMock( HttpServletResponse.class );
index 24b2755..4bc2d73 100644 (file)
@@ -39,8 +39,7 @@ public class GatewayGlobalConfigTest {
     URL url = ClassLoader.getSystemResource( resource );
     String fileName = url.getFile();
     File file = new File( fileName );
-    String dirName = file.getParentFile().getParent();
-    return dirName;
+    return file.getParentFile().getParent();
   }
 
   @Test
index 84a829e..c28dcaa 100644 (file)
@@ -125,7 +125,7 @@ public class CryptoServiceTest {
     String queryString = "url=http://localhost:50070/api/v1/blahblah";
     ConfigurableEncryptor aes0 = new ConfigurableEncryptor("password");
     aes0.init(config);
-    cs.init(config, new HashMap<String,String>());
+    cs.init(config, new HashMap<>());
     EncryptionResult result0 = cs.encryptForCluster("Test", "encrypt_url", queryString.getBytes(StandardCharsets.UTF_8));
     byte[] decrypted0 = cs.decryptForCluster("Test", "encrypt_url", result0.cipher, result0.iv, result0.salt);
     assertEquals(queryString, new String(decrypted0, StandardCharsets.UTF_8));
@@ -148,7 +148,7 @@ public class CryptoServiceTest {
     String queryString = "url=http://localhost:50070/api/v1/blahblah";
     ConfigurableEncryptor aes0 = new ConfigurableEncryptor("password");
     aes0.init(config);
-    cs.init(config, new HashMap<String,String>());
+    cs.init(config, new HashMap<>());
     EncryptionResult result0 = cs.encryptForCluster("Test", "encrypt_url", queryString.getBytes(StandardCharsets.UTF_8));
     byte[] decrypted0 = cs.decryptForCluster("Test", "encrypt_url", result0.cipher, result0.iv, result0.salt);
     assertEquals(queryString, new String(decrypted0, StandardCharsets.UTF_8));
index e778a7d..24f1665 100644 (file)
@@ -65,13 +65,13 @@ public class DefaultTokenAuthorityServiceTest extends org.junit.Assert {
     DefaultKeystoreService ks = new DefaultKeystoreService();
     ks.setMasterService(ms);
 
-    ks.init(config, new HashMap<String, String>());
+    ks.init(config, new HashMap<>());
 
     DefaultTokenAuthorityService ta = new DefaultTokenAuthorityService();
     ta.setAliasService(as);
     ta.setKeystoreService(ks);
 
-    ta.init(config, new HashMap<String, String>());
+    ta.init(config, new HashMap<>());
 
     JWT token = ta.issueToken(principal, "RS256");
     assertEquals("KNOXSSO", token.getIssuer());
@@ -107,13 +107,13 @@ public class DefaultTokenAuthorityServiceTest extends org.junit.Assert {
     DefaultKeystoreService ks = new DefaultKeystoreService();
     ks.setMasterService(ms);
 
-    ks.init(config, new HashMap<String, String>());
+    ks.init(config, new HashMap<>());
 
     DefaultTokenAuthorityService ta = new DefaultTokenAuthorityService();
     ta.setAliasService(as);
     ta.setKeystoreService(ks);
 
-    ta.init(config, new HashMap<String, String>());
+    ta.init(config, new HashMap<>());
 
     JWT token = ta.issueToken(principal, "https://login.example.com", "RS256");
     assertEquals("KNOXSSO", token.getIssuer());
@@ -150,13 +150,13 @@ public class DefaultTokenAuthorityServiceTest extends org.junit.Assert {
     DefaultKeystoreService ks = new DefaultKeystoreService();
     ks.setMasterService(ms);
 
-    ks.init(config, new HashMap<String, String>());
+    ks.init(config, new HashMap<>());
 
     DefaultTokenAuthorityService ta = new DefaultTokenAuthorityService();
     ta.setAliasService(as);
     ta.setKeystoreService(ks);
 
-    ta.init(config, new HashMap<String, String>());
+    ta.init(config, new HashMap<>());
 
     JWT token = ta.issueToken(principal, null, "RS256");
     assertEquals("KNOXSSO", token.getIssuer());
@@ -192,13 +192,13 @@ public class DefaultTokenAuthorityServiceTest extends org.junit.Assert {
     DefaultKeystoreService ks = new DefaultKeystoreService();
     ks.setMasterService(ms);
 
-    ks.init(config, new HashMap<String, String>());
+    ks.init(config, new HashMap<>());
 
     DefaultTokenAuthorityService ta = new DefaultTokenAuthorityService();
     ta.setAliasService(as);
     ta.setKeystoreService(ks);
 
-    ta.init(config, new HashMap<String, String>());
+    ta.init(config, new HashMap<>());
 
     JWT token = ta.issueToken(principal, "RS512");
     assertEquals("KNOXSSO", token.getIssuer());
@@ -235,13 +235,13 @@ public class DefaultTokenAuthorityServiceTest extends org.junit.Assert {
     DefaultKeystoreService ks = new DefaultKeystoreService();
     ks.setMasterService(ms);
 
-    ks.init(config, new HashMap<String, String>());
+    ks.init(config, new HashMap<>());
 
     DefaultTokenAuthorityService ta = new DefaultTokenAuthorityService();
     ta.setAliasService(as);
     ta.setKeystoreService(ks);
 
-    ta.init(config, new HashMap<String, String>());
+    ta.init(config, new HashMap<>());
 
     try {
       ta.issueToken(principal, "none");
index 30c5ed6..079727c 100644 (file)
@@ -563,7 +563,7 @@ public class DefaultTopologyServiceTest {
         "ldapGroupRealm.contextFactory.systemAuthenticationMechanism"
     };
 
-    Param param = null;
+    Param param;
     for (String name : names) {
       param = new Param();
       param.setName(name);
index c44c26a..6a118a1 100644 (file)
@@ -105,16 +105,14 @@ public class PropertiesFileServiceDiscoveryTest {
 
     private void printServiceURLs(ServiceDiscovery.Cluster cluster, String...services) {
         for (String name : services) {
-            String value = "";
+            StringBuilder value = new StringBuilder();
             List<String> urls = cluster.getServiceURLs(name);
             if (urls != null && !urls.isEmpty()) {
                 for (String url : urls) {
-                    value += url + " ";
+                    value.append(url).append(" ");
                 }
             }
-            System.out.println(String.format(Locale.ROOT, "%18s: %s", name, value));
+            System.out.println(String.format(Locale.ROOT, "%18s: %s", name, value.toString()));
         }
     }
-
-
 }
index 6bef201..fa9a717 100644 (file)
@@ -156,9 +156,9 @@ class PropertiesFileServiceDiscovery implements ServiceDiscovery {
         }
 
         private static class ZooKeeperConfigImpl implements ZooKeeperConfig {
-            private boolean isEnabled = false;
-            private String  ensemble  = null;
-            private String  namespace = null;
+            private boolean isEnabled;
+            private String  ensemble;
+            private String  namespace;
 
             ZooKeeperConfigImpl(boolean enabled, String ensemble, String namespace) {
                 this.isEnabled = enabled;
index ec1864e..9e7921f 100644 (file)
@@ -395,7 +395,6 @@ public class KnoxCLITest {
     outContent.reset();
 
     final String descriptorName = "my-topology.json";
-    final String descriptorContent = testDescriptorContentJSON;
 
     final File testRoot = TestUtils.createTempDir(this.getClass().getName());
     try {
@@ -406,7 +405,7 @@ public class KnoxCLITest {
                              "--registry-client", "test_client",
                              "--master", "master"};
 
-      FileUtils.writeStringToFile(testDescriptor, descriptorContent, StandardCharsets.UTF_8);
+      FileUtils.writeStringToFile(testDescriptor, testDescriptorContentJSON, StandardCharsets.UTF_8);
 
       KnoxCLI cli = new KnoxCLI();
       Configuration config = new GatewayConfigImpl();
@@ -446,7 +445,7 @@ public class KnoxCLITest {
   public void testSuccessfulAliasLifecycle() throws Exception {
     outContent.reset();
     String[] args1 = {"create-alias", "alias1", "--value", "testvalue1", "--master", "master"};
-    int rc = 0;
+    int rc;
     KnoxCLI cli = new KnoxCLI();
     cli.setConf(new GatewayConfigImpl());
     rc = cli.run(args1);
@@ -481,7 +480,7 @@ public class KnoxCLITest {
     String[] args1 =
         { "create-alias", "alias1", "--cluster", "cluster1", "--value", "testvalue1", "--master",
             "master" };
-    int rc = 0;
+    int rc;
     KnoxCLI cli = new KnoxCLI();
     cli.setConf(new GatewayConfigImpl());
     rc = cli.run(args1);
@@ -512,7 +511,7 @@ public class KnoxCLITest {
     KnoxCLI cli = new KnoxCLI();
     cli.setConf(new GatewayConfigImpl());
     try {
-      int rc = 0;
+      int rc;
       outContent.reset();
       String[] args1 =
           { "create-alias", "alias1", "--cluster", "cluster1", "--value", "testvalue1", "--master",
@@ -537,7 +536,7 @@ public class KnoxCLITest {
     KnoxCLI cli = new KnoxCLI();
     cli.setConf(new GatewayConfigImpl());
     try {
-      int rc = 0;
+      int rc;
       outContent.reset();
       String[] args1 = { "create-alias", "alias1", "--value", "testvalue1", "--master", "master" };
       cli.run(args1);
@@ -572,7 +571,7 @@ public class KnoxCLITest {
     String[] args1 =
         { "create-alias", "alias1", "--cluster", "cluster1", "--value", "testvalue1", "--master",
             "master" };
-    int rc = 0;
+    int rc;
     KnoxCLI cli = new KnoxCLI();
     cli.setConf(new GatewayConfigImpl());
     rc = cli.run(args1);
@@ -609,7 +608,7 @@ public class KnoxCLITest {
 
     outContent.reset();
     String[] gwCreateArgs = {"create-alias", "alias1", "--value", "testvalue1", "--master", "master"};
-    int rc = 0;
+    int rc;
     KnoxCLI cli = new KnoxCLI();
     cli.setConf( config );
     rc = cli.run(gwCreateArgs);
@@ -687,7 +686,7 @@ public class KnoxCLITest {
     KnoxCLI cli = new KnoxCLI();
     cli.setConf( config );
     String[] gwCreateArgs = {"create-cert", "--hostname", "hostname1", "--master", "master"};
-    int rc = 0;
+    int rc;
     rc = cli.run(gwCreateArgs);
     assertEquals(0, rc);
     assertTrue(outContent.toString(StandardCharsets.UTF_8.name()), outContent.toString(StandardCharsets.UTF_8.name()).contains("gateway-identity has been successfully " +
@@ -767,7 +766,7 @@ public class KnoxCLITest {
     FileUtils.deleteQuietly( new File( config.getGatewaySecurityDir() ) );
     outContent.reset();
     String[] args = {"create-master", "--master", "master"};
-    int rc = 0;
+    int rc;
     KnoxCLI cli = new KnoxCLI();
     cli.setConf( config );
     rc = cli.run(args);
@@ -781,7 +780,7 @@ public class KnoxCLITest {
   @Test
   public void testCreateMasterGenerate() throws Exception {
     String[] args = {"create-master", "--generate" };
-    int rc = 0;
+    int rc;
     GatewayConfigImpl config = new GatewayConfigImpl();
     File masterFile = new File( config.getGatewaySecurityDir(), "master" );
 
@@ -833,7 +832,7 @@ public class KnoxCLITest {
     KnoxCLI cli = new KnoxCLI();
     cli.setConf(config);
     MasterService ms;
-    int rc = 0;
+    int rc;
     outContent.reset();
 
     String[] args = { "create-master", "--master", "test-master-1" };
@@ -889,7 +888,7 @@ public class KnoxCLITest {
   }
 
   private static XMLTag createBadTopology() {
-    XMLTag xml = XMLDoc.newDocument(true)
+    return XMLDoc.newDocument(true)
         .addRoot( "topology" )
         .addTag( "gateway" )
 
@@ -921,11 +920,10 @@ public class KnoxCLITest {
         .addTag( "service" )
         .addTag( "role" ).addText( "test-service-role" )
         .gotoRoot();
-    return xml;
   }
 
   private static XMLTag createGoodTopology() {
-    XMLTag xml = XMLDoc.newDocument( true )
+    return XMLDoc.newDocument( true )
         .addRoot( "topology" )
         .addTag( "gateway" )
 
@@ -957,7 +955,6 @@ public class KnoxCLITest {
         .addTag( "service" )
         .addTag( "role" ).addText( "test-service-role" )
         .gotoRoot();
-    return xml;
   }
 
   private File writeTestTopology( String name, XMLTag xml ) throws IOException {
index 0382a88..e61ddde 100644 (file)
@@ -264,11 +264,10 @@ public class BadUrlTest {
    * Intentionally add bad URL
    */
   private static XMLTag createKnoxTopology(final String backend) {
-    XMLTag xml = XMLDoc.newDocument(true).addRoot("topology").addTag("service")
+    // System.out.println( "GATEWAY=" + xml.toString() );
+    return XMLDoc.newDocument(true).addRoot("topology").addTag("service")
         .addTag("role").addText("WEBSOCKET").addTag("url").addText(backend)
         .gotoParent().gotoRoot();
-    // System.out.println( "GATEWAY=" + xml.toString() );
-    return xml;
   }
 
   private static class TestTopologyListener implements TopologyListener {
index 9891985..b8bfd2e 100644 (file)
@@ -346,11 +346,10 @@ public class WebsocketEchoTest {
   }
 
   private static XMLTag createKnoxTopology(final String backend) {
-    XMLTag xml = XMLDoc.newDocument(true).addRoot("topology").addTag("service")
+    // System.out.println( "GATEWAY=" + xml.toString() );
+    return XMLDoc.newDocument(true).addRoot("topology").addTag("service")
         .addTag("role").addText("WEBSOCKET").addTag("url").addText(backend)
         .gotoParent().gotoRoot();
-    // System.out.println( "GATEWAY=" + xml.toString() );
-    return xml;
   }
 
   private static class TestTopologyListener implements TopologyListener {
index fd28e7f..eb635ef 100644 (file)
@@ -343,11 +343,10 @@ public class WebsocketMultipleConnectionTest {
   }
 
   private static XMLTag createKnoxTopology(final String backend) {
-    XMLTag xml = XMLDoc.newDocument(true).addRoot("topology").addTag("service")
+    // System.out.println( "GATEWAY=" + xml.toString() );
+    return XMLDoc.newDocument(true).addRoot("topology").addTag("service")
         .addTag("role").addText("WEBSOCKET").addTag("url").addText(backend)
         .gotoParent().gotoRoot();
-    // System.out.println( "GATEWAY=" + xml.toString() );
-    return xml;
   }
 
   private static class TestTopologyListener implements TopologyListener {
index 0d67788..b9e0e00 100644 (file)
@@ -266,7 +266,7 @@ public class TopologiesResource {
     }
 
     if (providerConfigFile != null) {
-      byte[] content = null;
+      byte[] content;
       try {
         content = FileUtils.readFileToByteArray(providerConfigFile);
         response = ok().entity(content).build();
@@ -461,7 +461,7 @@ public class TopologiesResource {
     if (descriptorFile != null) {
       String mediaType = APPLICATION_JSON;
 
-      byte[] content = null;
+      byte[] content;
       try {
         if ("yml".equals(FilenameUtils.getExtension(descriptorFile.getName()))) {
           mediaType = TEXT_PLAIN;
index 1a24f2b..49d9a0d 100644 (file)
@@ -110,11 +110,8 @@ public class MetricsResource {
       response.setHeader("Cache-Control", "must-revalidate,no-cache,no-store");
       response.setStatus(HttpServletResponse.SC_OK);
 
-      final OutputStream output = response.getOutputStream();
-      try {
+      try (OutputStream output = response.getOutputStream()) {
         getWriter(request).writeValue(output, registry);
-      } finally {
-        output.close();
       }
     } catch (IOException ioe) {
       log.logException("metrics", ioe);
index 0aaf29e..5a73ef2 100644 (file)
@@ -71,17 +71,11 @@ public class PingResource {
     response.setStatus(HttpServletResponse.SC_OK);
     response.setHeader(CACHE_CONTROL, NO_CACHE);
     response.setContentType(CONTENT_TYPE);
-    PrintWriter writer = null;
-    try {
-      writer = response.getWriter();
+    try (PrintWriter writer = response.getWriter()) {
       writer.println(getPingContent());
     } catch (IOException ioe) {
       log.logException("ping", ioe);
       return Response.serverError().entity(String.format(Locale.ROOT, "Failed to reply correctly due to : %s ", ioe)).build();
-    } finally {
-      if (writer != null) {
-        writer.close();
-      }
     }
     return Response.ok().build();
   }
index 1a583f4..9371c4a 100644 (file)
@@ -80,8 +80,8 @@ public class TokenResource {
     String audiences = context.getInitParameter(TOKEN_AUDIENCES_PARAM);
     if (audiences != null) {
       String[] auds = audiences.split(",");
-      for (int i = 0; i < auds.length; i++) {
-        targetAudiences.add(auds[i].trim());
+      for (String aud : auds) {
+        targetAudiences.add(aud.trim());
       }
     }
 
@@ -91,8 +91,8 @@ public class TokenResource {
     String principals = context.getInitParameter(TOKEN_ALLOWED_PRINCIPALS);
     if (principals != null) {
       String[] dns = principals.split(";");
-      for (int i = 0; i < dns.length; i++) {
-        allowedDNs.add(dns[i].replaceAll("\\s+",""));
+      for (String dn : dns) {
+        allowedDNs.add(dn.replaceAll("\\s+", ""));
       }
     }
 
@@ -165,7 +165,7 @@ public class TokenResource {
     long expires = getExpiry();
 
     try {
-      JWT token = null;
+      JWT token;
       if (targetAudiences.isEmpty()) {
         token = ts.issueToken(p, signatureAlgorithm, expires);
       } else {
@@ -202,9 +202,9 @@ public class TokenResource {
 
   void addClientDataToMap(String[] tokenClientData,
       Map<String,Object> map) {
-    String[] kv = null;
-    for (int i = 0; i < tokenClientData.length; i++) {
-      kv = tokenClientData[i].split("=");
+    String[] kv;
+    for (String tokenClientDatum : tokenClientData) {
+      kv = tokenClientDatum.split("=");
       if (kv.length == 2) {
         map.put(kv[0], kv[1]);
       }
index ef02bd0..5d53e1e 100644 (file)
@@ -76,7 +76,7 @@ public class NiFiDispatch extends DefaultDispatch {
   }
 
   /**
-   * Overriden due to {@link DefaultDispatch#getInboundResponseContentType(HttpEntity) having private access, and the method is used by
+   * Overriden due to DefaultDispatch#getInboundResponseContentType(HttpEntity) having private access, and the method is used by
    * {@link #writeOutboundResponse(HttpUriRequest, HttpServletRequest, HttpServletResponse, HttpResponse)}}
    */
   private String getInboundResponseContentType( final HttpEntity entity ) {
index c79124c..a423708 100644 (file)
@@ -87,7 +87,7 @@ public class NiFiHaDispatch extends DefaultHaDispatch {
   }
 
   /**
-   * Overriden due to {@link DefaultDispatch#getInboundResponseContentType(HttpEntity) having private access, and the method is used by
+   * Overriden due to DefaultDispatch#getInboundResponseContentType(HttpEntity) having private access, and the method is used by
    * {@link #writeOutboundResponse(HttpUriRequest, HttpServletRequest, HttpServletResponse, HttpResponse)}}
    */
   private String getInboundResponseContentType( final HttpEntity entity ) {
index b2d9ebb..93441af 100644 (file)
@@ -45,7 +45,7 @@ class NiFiResponseUtil {
         } catch (URISyntaxException e) {
           throw new RuntimeException("Unable to parse URI from Location header", e);
         }
-        URIBuilder inboundRequestUriBuilder = null;
+        URIBuilder inboundRequestUriBuilder;
         try {
           inboundRequestUriBuilder = new URIBuilder(inboundRequest.getRequestURI());
         } catch (URISyntaxException e) {
index a8c5448..b419c9c 100644 (file)
@@ -70,10 +70,8 @@ class CuratorClientService implements ZooKeeperClientService {
     @Override
     public void init(GatewayConfig config, Map<String, String> options) throws ServiceLifecycleException {
 
-        List<RemoteConfigurationRegistryConfig> registryConfigs = new ArrayList<>();
-
-        // Load the remote registry configurations
-        registryConfigs.addAll(RemoteConfigurationRegistriesAccessor.getRemoteRegistryConfigurations(config));
+      // Load the remote registry configurations
+      List<RemoteConfigurationRegistryConfig> registryConfigs = new Arra